我正在创建一个需要条件where子句的SQL查询。
where
应该是这样的:
SELECT DateAppr, TimeAppr, TAT, LaserLTR, Permit, LtrPrinter, JobName, JobNumber, JobDesc, ActQty, (ActQty-LtrPrinted) AS L, (ActQty-QtyInserted) AS M, ((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS N FROM [test].[dbo].[MM] WHERE DateDropped = 0 --This is where i need the conditional clause AND CASE WHEN @JobsOnHold = 1 THEN DateAppr >= 0 ELSE DateAppr != 0 END
上面的查询不起作用。这是不正确的语法,还是我不知道的另一种方式来做到这一点?
我不想使用动态SQL,是否还有其他方法,还是必须使用类似的解决方法,例如if else对不同的where子句使用和使用相同的查询?
if else
试试这个
SELECT DateAppr, TimeAppr, TAT, LaserLTR, Permit, LtrPrinter, JobName, JobNumber, JobDesc, ActQty, (ActQty-LtrPrinted) AS L, (ActQty-QtyInserted) AS M, ((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS N FROM [test].[dbo].[MM] WHERE DateDropped = 0 AND ( (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0) OR (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0) )
您可以在此处阅读有关条件WHERE的更多信息。