有条件地在where子句中的SQL Server案例

时间:2016-03-03 09:24:23

标签: sql sql-server case conditional-statements where

select * 
from someTable 
where currencyid = @currencyid  --CaseA
   or (Currencyid in (8,11) or (@Currencyid = 0)) --CaseB

如何修改此类查询,以便在@currencyid = 0时仅在CaseB上设置条件而其他人设置为CaseA?

例如: if @currencyid = 0然后要执行的结束查询是

select * 
from someTable 
where currencyid = (Currencyid in (8,11) or (@Currencyid = 0))

如果@currencyid = 8则要执行的结束查询是

select * 
from someTable 
where currencyid = @currencyid

1 个答案:

答案 0 :(得分:2)

SELECT *
FROM someTable
WHERE (currencyid = @Currencyid AND @Currencyid != 0)
    OR (Currencyid IN (8, 11) AND @Currencyid = 0)
--OPTION(RECOMPILE)