Thursday, February 16, 2012

Convert a SQL CSV Parameter into a table

Consider the need to pass in a CSV parameter like this:

DECLARE @UserIDs_CSV VARCHAR(50)
SET @UserIDs_CSV = '1,2,4,5,8,9'

If that CSV parameter happens to correlate to a table, like in this case, Users... Use a query like this to convert the CSV parameter into a temp table...

SELECT UserID
into #SelectedUserIDs
FROM Users
WHERE CHARINDEX(
',' + cast(UserID as varchar(10)) + ',',
',' + @UserIDs_CSV + ','
) > 0

So now just use the temp table as you need for future queries...

select * from #SelectedUserIDs

Credit goes to http://www.projectdmx.com/tsql/sqlarrays.aspx

No comments:

Post a Comment