Developer comes to us with a problem statement: How do we convert a delimited string variable into rows using T-SQL?
For example:
DECLARE @str VARCHAR(200)='aaa,bbb,ccc,ddd'
Expected output:
Result |
aaa |
bbb |
ccc |
ddd |
Okay, I manage to find 3 methods on the Internet. :D
Method 1
SELECT SUBSTRING(@str,CHARINDEX(',',','+@str+',',number),CHARINDEX(',',','+@str+',',number+1)-CHARINDEX(',',','+@str+',',number)-1)
FROM master.dbo.spt_values
WHERE name IS NULL AND number <= LEN(@str)
AND number=CHARINDEX(',',','+@str+',',number)
Method 2
DECLARE @xml xml
SET @xml=N'
FROM @xml.node('//root/r's) AS a(x)
Method 3
SET @str='SELECT '''+REPLACE(@str,',',''' UNION ALL SELECT ''')+''''
EXEC(@str)
Somehow, I find that method 3 is the fastest on my machine.
Some benchmark data:
Method | Avg Speed (ms) |
Method 1 | 143 |
Method 2 | 33 |
Method 3 | 3 |
Do you get same result on your machine?
No comments:
Post a Comment