Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server store multiple values in sql variable

I have the following query:

select * 
from cars 
where make in ('BMW', 'Toyota', 'Nissan')

What I want to do is store the where parameters in a SQL variable.

Something like:

declare @caroptions varchar(max);
select @caroptions =  select distinct(make) from carsforsale;
print @caroptions;
select * from cars where make in (@caroptions)

Problem is the print of @caroptions only has the last result returned from:

select distinct(make) from carsforsale;

I want it to store multiple values.

Any ideas?

like image 847
Smudger Avatar asked Jul 19 '13 11:07

Smudger


People also ask

Can you assign multiple values to a variable in SQL?

Assigning multiple values to multiple variablesIf you have to populate multiple variables, instead of using separate SET statements each time consider using SELECT for populating all variables in a single statement. This can be used for populating variables directly or by selecting values from database.

How do you store multiple values in a variable?

With JavaScript array variables, we can store several pieces of data in one place. You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this: var sandwich = ["peanut butter", "jelly", "bread"].


2 Answers

You can use a table variable:

declare @caroptions table
(
    car varchar(1000)
)

insert into @caroptions values ('BMW')
insert into @caroptions values ('Toyota')
insert into @caroptions values ('Nissan')

select * from cars where make in (select car from @caroptions)
like image 65
Christian Specht Avatar answered Sep 29 '22 13:09

Christian Specht


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 );
like image 45
Kenneth Fisher Avatar answered Sep 29 '22 12:09

Kenneth Fisher