小编典典

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

sql

我有以下查询:

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;

我希望它存储多个值。

有任何想法吗?


阅读 305

收藏
2021-03-17

共1个答案

小编典典

您可以使用表变量:

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)
2021-03-17