1
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

The above code is the one I stimulated.

there is a variable @cou.

That variable is the one using in where.

what I want is.. if @cou is null, I want to use @firstCou and @secondCou.

Instead of doing where country in (@firstCou,@secondCou)

I want where country in (@cou) with those 2 variable values in @cou.

cos the real thing is not 2 extra variable.. I will retreieve several records and I won't know the fixed record.

That's why I want to use IN()

But my problem is when I add those 2 values into @cou, the @cou value becomes 'sg,uk' instead of 'sg','uk'.

it is expected but how can i make it so that it becomes 'sg','uk'

william
  • 7,284
  • 19
  • 66
  • 106
  • 1
    Your question is essentially about parametrising the `IN` clause, which has been covered here many times. Please have a look at [this question](http://stackoverflow.com/questions/337704/parameterizing-a-sql-in-clause) and possibly pay attention to its *Linked* section as well. – Andriy M Sep 06 '11 at 05:32

1 Answers1

0

You can not replace the parameters for IN with a string literal. In takes a list of expressions or a sub-query as an argument.

You could use a table variable instead with one column and one row for each country.

declare @cou table(country varchar(50))

Insert the countries you look for to the table variable and use a query that looks like this.

select *
from EgTB
where country in (select country from @cou)
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281