Created
September 12, 2013 12:44
-
-
Save codingbadger/6536694 to your computer and use it in GitHub Desktop.
Convert Comma separated values (or any token actually it doesn't need to be a comma) to a table in SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Create Function dbo.fn_ConvertCSVtoTable ( @input nvarchar(max), @token nchar(1)) | |
Returns @Result Table | |
(ColumnValue nvarchar(max)) | |
As | |
Begin | |
Declare @x XML | |
Select @x = CAST('<CSV>'+ REPLACE(@input, @token,'</CSV><CSV>')+ '</CSV>' AS XML) | |
Insert Into @Result | |
Select t.value('.', 'nvarchar(max)') AS ColumnValue | |
From @x.nodes('/CSV') AS x(t) | |
Return | |
End | |
Go | |
Create Table #Numbers | |
( | |
Numbers nvarchar(max) | |
) | |
Insert Into #Numbers | |
Values ('one'),('two'),('three'),('four'),('five'),('six'),('seven'),('eight'),('nine'),('ten') | |
Declare @FindMe nvarchar(max) | |
Set @FindMe = 'one,five,seven,nine' | |
Select n.* | |
From #Numbers n | |
Join dbo.fn_ConvertCSVtoTable(@FindMe, ',') csv on n.Numbers = csv.ColumnValue | |
Drop Table #Numbers | |
Drop Function dbo.fn_ConvertCSVtoTable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment