当@ filter = 1 ....时,是否可以写出where case?

时间:2012-09-07 15:07:52

标签: sql sql-server subquery case

使用

  • SQL server 2005
  • 程序
  • 参数

我有一个正常的查询:

select column1, column2
from table1
where column3 in ( select columnb from table2 )

现在我有一个过滤器,例如int

declare @filtertype int /*@filtertype=1 then column3,@filtertype=2 then column2*/ 
set @filtertype int

我这样做了

select column1, column2
from table1
where
   case when @filtertype=1 then (column3 in (select columnb from table2))
   else (column2 in (select columnb from table2))

如果您看到它,您可以看到第2列的第3列

的唯一更改

我不想像这样重复我的大型查询:

if(@filtertype=1)
begin
   first query
end
else
   other query
begin
end

2 个答案:

答案 0 :(得分:3)

试试这个:

   select column1, column2 
    from table1 
    where 
    (@filtertype=1 AND (column3 in (select columnb from table2)))
    OR
    (@filtertype=2 AND (column2 in (select columnb from table2)))

答案 1 :(得分:1)

select 
...
from ...
where (@filtertype=1 and column3 in (select ... from table2))
or (@filtertype<>1 and column2 in (select ... from table2))