Skip to content

Instantly share code, notes, and snippets.

@codingbadger
Created September 12, 2013 12:44
Show Gist options
  • Save codingbadger/6536694 to your computer and use it in GitHub Desktop.
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
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