Conditional WHERE clause in SQL Server Conditional WHERE clause in SQL Server sql-server sql-server

Conditional WHERE clause in SQL Server


Try this

SELECT     DateAppr,    TimeAppr,    TAT,    LaserLTR,    Permit,    LtrPrinter,    JobName,    JobNumber,    JobDesc,    ActQty,    (ActQty-LtrPrinted) AS L,    (ActQty-QtyInserted) AS M,    ((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS NFROM     [test].[dbo].[MM]WHERE     DateDropped = 0    AND (    (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0)     OR     (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)    )

You can read more about conditional WHERE here.


Try this one -

WHERE DateDropped = 0    AND (        (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0)         OR         (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)    )


To answer the underlying question of how to use a CASE expression in the WHERE clause:

First remember that the value of a CASE expression has to have a normal data type value, not a boolean value. It has to be a varchar, or an int, or something. It's the same reason you can't say SELECT Name, 76 = Age FROM [...] and expect to get 'Frank', FALSE in the result set.

Additionally, all expressions in a WHERE clause need to have a boolean value. They can't have a value of a varchar or an int. You can't say WHERE Name; or WHERE 'Frank';. You have to use a comparison operator to make it a boolean expression, so WHERE Name = 'Frank';

That means that the CASE expression must be on one side of a boolean expression. You have to compare the CASE expression to something. It can't stand by itself!

Here:

WHERE     DateDropped = 0    AND CASE            WHEN @JobsOnHold  = 1 AND DateAppr >= 0 THEN 'True'            WHEN DateAppr != 0 THEN 'True'            ELSE 'False'        END = 'True'

Notice how in the end the CASE expression on the left will turn the boolean expression into either 'True' = 'True' or 'False' = 'True'.

Note that there's nothing special about 'False' and 'True'. You can use 0 and 1 if you'd rather, too.

You can typically rewrite the CASE expression into boolean expressions we're more familiar with, and that's generally better for performance. However, sometimes is easier or more maintainable to use an existing expression than it is to convert the logic.