Sql server 2008 在一个变量中放入2个值以调节SQL Server

Sql server 2008 在一个变量中放入2个值以调节SQL Server,sql-server-2008,Sql Server 2008,上面的代码就是我激发的代码 有一个变量@cou 该变量在where中使用 我想要的是。。如果@cou为空,我想使用@firstCou和@secondCou 而不是执行where country in(@firstCou,@secondCou) 我想要where country in(@cou)和@cou中的这两个变量值 因为真正的东西不是2个额外的变量。。我将检索几张唱片,但我不知道固定的唱片 这就是为什么我想在()中使用IN 但我的问题是,当我将这两个值添加到@cou中时,@cou值变成'sg

上面的代码就是我激发的代码

有一个变量
@cou

该变量在where中使用

我想要的是。。如果
@cou
为空,我想使用
@firstCou
@secondCou

而不是执行
where country in(@firstCou,@secondCou)

我想要
where country in(@cou)
@cou
中的这两个变量值

因为真正的东西不是2个额外的变量。。我将检索几张唱片,但我不知道固定的唱片

这就是为什么我想在()中使用
IN

但我的问题是,当我将这两个值添加到
@cou
中时,
@cou
值变成
'sg,uk'
,而不是
'sg','uk'


这是预期的,但如何使其成为
'sg','uk'

您不能用字符串文字替换的参数。In将表达式列表或子查询作为参数

您可以使用一个表变量,每个国家一列一行

if(OBJECT_ID('EgTb')is not null)drop table [EgTB];
GO
create table [EgTB](Name varchar(50),country varchar(50))
insert into EgTB values('aaa','sg');
insert into EgTB values('bbb','uk');
insert into EgTB values('ccc','us');
insert into EgTB values('ddd','au');
GO
select * from EgTB;

declare @cou varchar(50), @firstCou varchar(50), @secondCou varchar(50);
set @firstCou='sg';
set @secondCou='uk';
if(@cou is null)
begin
set @cou=@firstCou+','+@secondCou;
end
select * from EgTB where (@cou is null or country in (@cou));
GO
if(OBJECT_ID('EgTb')is not null)drop table [EgTB];
GO
将要查找的国家/地区插入表变量,并使用如下所示的查询

declare @cou table(country varchar(50))

您的问题本质上是关于在子句中参数化
,这里已经讨论过很多次了。请看一看,并可能注意其链接部分以及。
select *
from EgTB
where country in (select country from @cou)