SQL Server在sql变量中存储多个值

时间:2013-07-19 11:50:17

标签: sql sql-server arrays variables stored-procedures

我有以下查询:

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

我想要做的是将where参数存储在SQL变量中。

类似的东西:

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

问题是@caroptions的打印只返回最后一个结果:

select distinct(make) from carsforsale;

我希望它存储多个值。

有什么想法吗?

7 个答案:

答案 0 :(得分:8)

您可以使用表变量:

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)

答案 1 :(得分:4)

如果您想详细查看,请写下这个here。与此同时,你无法完全按照自己的想法去做。

您的选择是:

使用LIKE命令:

DECLARE @CarOptions varchar(100)
SET @CarOptions = 'Ford, Nisan, Toyota'

SELECT *
FROM Cars
WHERE ','+@CarOptions+',' LIKE ',%'+CAST(Make AS varchar)+',%'

分离器功能

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

与此同时,您最好的选择是完全摆脱变量。

SELECT * FROM cars WHERE make IN (SELECT make FROM carsforsale );

答案 2 :(得分:1)

为什么不呢?

SELECT * FROM cars WHERE make IN (SELECT DISTINCT(make) FROM carsforsale)

答案 3 :(得分:1)

Fetch 1 value in table and store in variable    
=======================================================================================

Declare @query int

    select @query = p.ProductID From Product p inner join ReOrdering as r on 
    p.ProductID = r.ProductID and r.MinQty >= p.Qty_Available

    print @query

答案 4 :(得分:1)

使用CTE将多个值存储到单个变量中。

;WITH DATA1 AS 
(
    select car_name
    from cars 
    where make in ('BMW', 'Toyota', 'Nissan')
)
SELECT @car_name = CONCAT(@car_name,',',car_name)
FROM DATA1

select @car_name

答案 5 :(得分:0)

你可以使用JOIN语句。

SELECT distinct c.*
FROM cars c
JOIN carsfrosale s
ON s.id = c.fk_s

如果您想过滤carsforsale列表,可以添加

WHERE s.id in (....)

答案 6 :(得分:0)

在 TSQL 中你可以这样使用 STRING_AGG

select STRING_AGG(car_name,',') as csv
from cars 
where make in ('BMW', 'Toyota', 'Nissan')