You can't use STRING_SPLIT
to expand a delimited literal string into multiple delimited literal strings. STRING_SPLIT('abc,def',',')
doesn't result in 'abc','def'
, it results in a data set of 2 rows, containing the values 'abc'
and 'def'
.
If you want to pass a delimited string, you need to either JOIN
/CROSS APPLY
to STRING_SPLIT
or use a subquery:
SELECT T1.Col1,
T1.Col2
FROM dbo.table1 T1
JOIN STRING_SPLIT(@YourVariable,',') SS ON T1.Col1 = SS.Value;
SELECT T1.Col1,
T1.Col2
FROM dbo.table1 T1
WHERE T1.Col1 IN (SELECT SS.Value
FROM STRING_SPLIT(@YourVariable,',') SS);
You may, however, find even better performance with an indexed temporary table, if you are dealing with large data sets:
CREATE TABLE #temp (Value varchar(30) PRIMARY KEY); --Use an appropriate data type. I assume unique values in the delimited string
INSERT INTO #temp (Value)
SELECT SS.Value
FROM STRING_SPLIT(@YourVariable,',') SS;
SELECT T1.Col1,
T1.Col2
FROM dbo.table1 T1
JOIN #Temp T ON T1.Col1 = T.Value;
Finally, which may be better again, you could use a table type parameter. Then you would, like the above, just JOIN
to that or use an EXISTS
.