Where IN a Comma delimited string

Weihui Guo picture Weihui Guo · May 28, 2015 · Viewed 35.9k times · Source

I would like to retrieve certain users from a full list of a temp table #temptable. The query looks like this:

DECLARE @List varchar(max)
SELECT @List = coalesce(@List + ',','') + '''' + StaffCode + ''''
FROM tblStaffs

SELECT UserName
FROM #temptable
WHERE #temptable.StaffCode IN (@List)

I can tell @List is in a right format:

'AAA','ABB','BBB','CCC','DDD','MMM'

And if I change it to

WHERE #temptable.StaffCode IN ('AAA','ABB','BBB','CCC','DDD','MMM')

It certainly works, then why not IN (@List)?

Answer

Pரதீப் picture Pரதீப் · May 28, 2015

Create some split string function and convert the comma separated values to rows then you can use the converted rows IN clause

DECLARE @List VARCHAR(max)

SELECT @List = COALESCE(@List + ',', '') +StaffCode
FROM   tblStaffs

SELECT UserName
FROM   #temptable
WHERE  #temptable.StaffCode IN (SELECT split_values
                                FROM   dbo.Splitstring_function(@list)) 

Check here for various Split String function

If you dont want to create functions then you can also directly use the code instead of creating a new function(M.Ali's answer).

Another way of doing it is using dynamic query.

Declare @List varchar(max), @sql nvarchar(max)

Select @List = coalesce(@List + ',','') + '''' + StaffCode + ''''
From tblStaffs

set @sql = '
Select UserName
From #temptable
Where #temptable.StaffCode IN ('+ @List + ')'

--print @sql
exec (@sql)

To debug the dynamic query always print the dynamic sql before executing.