1

  • SQL 服务器 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))

如果你看到它,你会看到独特的变化是 column3 的 column2

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

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

2 回答 2

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)))
于 2012-09-07T15:10:15.123 回答
1
select 
...
from ...
where (@filtertype=1 and column3 in (select ... from table2))
or (@filtertype<>1 and column2 in (select ... from table2))
于 2012-09-07T15:13:08.090 回答