I have the following query:
select *
from cars
where make in (\'BMW\', \'Toyota\', \'Nissan\')
What I want to do is store the where param
I wrote about this here if you want to see it in detail. In the mean time, you can't do it exactly how you are thinking.
Your choices are:
Using the LIKE command:
DECLARE @CarOptions varchar(100)
SET @CarOptions = 'Ford, Nisan, Toyota'
SELECT *
FROM Cars
WHERE ','+@CarOptions+',' LIKE ',%'+CAST(Make AS varchar)+',%'
A spliter function
DECLARE @CarOptions varchar(100)
SET @CarOptions = 'Ford, Nisan, Toyota'
SELECT Cars.*
FROM Cars
JOIN DelimitedSplit8K (@CarOptions,',') SplitString
ON Cars.Make = SplitString.Item
Dyanmic SQL
DECLARE @CarOptions varchar(100)
SET @CarOptions = 'Ford, Nisan, Toyota'
DECLARE @sql nvarchar(1000)
SET @sql = 'SELECT * ' +
'FROM Cars ' +
'WHERE Make IN ('+@CarOptions+') '
EXEC sp_executesql @sql
In the mean time your best option is going to be to get rid of the variable completely.
SELECT * FROM cars WHERE make IN (SELECT make FROM carsforsale );