2012-09-07 32 views
1

當@ filter = 1 ....時,是否可以寫出where case?

  • 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 

我NEDD出頭,因爲這

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

如果你看到它,你可以看到獨特的變化欄3爲COLUMN2

我不想重複我的大這樣的查詢:

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

回答

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
select 
... 
from ... 
where (@filtertype=1 and column3 in (select ... from table2)) 
or (@filtertype<>1 and column2 in (select ... from table2))