加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 08:34:32 所属栏目:MsSql教程 来源:网络整理
导读:我有以下查询: 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
我有以下查询:
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;

我希望它存储多个值.

有任何想法吗?

解决方法

您可以使用表变量:
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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读