I need help coding for the where
clause in a stored procedure passing in these input parameters:
DECLARE @UID_CUSTOMER int = 7
, @BOOL_HAS_DEFECT bit = 0
, @BOOL_HAS_INSPECTION bit = 0
, @DTTM_TRIP_START datetime = '2024-01-01'
, @DTTM_TRIP_END datetime = '2024-06-01'
;
In the T-SQL query, I would use this WHERE
clause:
WHERE ... other conditions ...
AND (PTI.UID_PTINSPECTION IS NOT NULL)
AND (TMD.UID_TMDEFECT IS NOT NULL);
However, I want to use the inbound parameter @BOOL_HAS_INSPECTION
as here:
AND (PTI.UID_PTINSPECTION (CASE WHEN @BOOL_HAS_INSPECTION = 1
THEN (IS NOT NULL)
ELSE (IS NULL) END))
This code fragment is invalid.
Question: how can I use the @BOOL_HAS_INSPECTION
to properly specify IS NOT NULL
and/or IS NULL
?
I need help coding for the where
clause in a stored procedure passing in these input parameters:
DECLARE @UID_CUSTOMER int = 7
, @BOOL_HAS_DEFECT bit = 0
, @BOOL_HAS_INSPECTION bit = 0
, @DTTM_TRIP_START datetime = '2024-01-01'
, @DTTM_TRIP_END datetime = '2024-06-01'
;
In the T-SQL query, I would use this WHERE
clause:
WHERE ... other conditions ...
AND (PTI.UID_PTINSPECTION IS NOT NULL)
AND (TMD.UID_TMDEFECT IS NOT NULL);
However, I want to use the inbound parameter @BOOL_HAS_INSPECTION
as here:
AND (PTI.UID_PTINSPECTION (CASE WHEN @BOOL_HAS_INSPECTION = 1
THEN (IS NOT NULL)
ELSE (IS NULL) END))
This code fragment is invalid.
Question: how can I use the @BOOL_HAS_INSPECTION
to properly specify IS NOT NULL
and/or IS NULL
?
2 Answers
Reset to default 7This will work, but there may be a more concise way.
WHERE ... AND
( (@BOOL_HAS_INSPECTION = 1 AND PTI.UID_PTINSPECTION IS NOT NULL)
OR (@BOOL_HAS_INSPECTION = 0 AND PTI.UID_PTINSPECTION IS NULL) )
For interest, some other possibilities:
1 - A shorter version, though possibly harder to understand (assumes @BOOL_HAS_INSPECTION will not be passed as NULL):
AND
@BOOL_HAS_INSPECTION = IIF(PTI.UID_PTINSPECTION IS NULL, 0, 1)
2 - A rather long winded version using nested CASE expressions. Possibly overkill in your specific case, but a technique which can come in handy when requirements are more complex:
AND
1 = (CASE WHEN @BOOL_HAS_INSEPECTION = 1 THEN CASE WHEN PTI.UID_PTINSPECTION IS NOT NULL THEN 1 END
ELSE CASE WHEN PTI.UID_PTINSPECTION IS NULL THEN 1 END
END)
Check your query plans if there are any performance concerns.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745241008a4618183.html
union all
^^^ – Dale K Commented Feb 4 at 18:44