SQL Server在sql变量中存储多个值 [英] SQL Server store multiple values in sql variable

查看:444
本文介绍了SQL Server在sql变量中存储多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询:

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

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

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

类似的东西:

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

问题是@caroptions的打印仅从以下位置返回了最后结果:

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

select distinct(make) from carsforsale;

我希望它存储多个值.

有什么想法吗?

推荐答案

您可以使用表变量:

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)

这篇关于SQL Server在sql变量中存储多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆