I have a need to filter records where:
NotificationRead = 0 || NULL --> IF GetRead = 0
NotificationRead = 1 --> IF GetRead = 1
NotificationRead = 0 || 1 || NULL --> IF GetRead = NULL
Here is the query I am using for this:
DECLARE @GetRead BIT
DECLARE @Query VARCHAR(20)
SET @GetRead = NULL
IF @GetRead = 0 SET @Query = '0,NULL'
ELSE IF @GetRead = 1 SET @Query = '1'
ELSE SET @Query = '0,1,NULL'
SELECT * FROM vwNotifications WHERE NotificationRead IN (@Query)
The query above basically fails when I supply NULL in the IN clause.
I do know the reason why thanks to this question.
But if I take an approach as suggested in that question's answer (using NotificationRead IN (@Query) OR NotificationRead IS NULL), I get all records where NotificationRead = NULL when I don't need them for example, when @GetRead = 1
Can you please point me to the right direction here?
No, the problem is that you are providing the values as strings.
1 IN (1, 2) -- true.
1 IN ('1, 2') -- false.
Try this instead:
SELECT *
FROM vwNotifications
WHERE (@GetRead = 0 AND (NotificationRead = 0 OR NotificationRead IS NULL))
OR (@GetRead = 1 AND NotificationRead = 1)
OR (@GetRead IS NULL AND (NotificationRead IN (0, 1) OR
NotificationRead IS NULL))
Others may have a better way, but I would move your select into each of the 'if' statements, and modify accordingly.
IF @GetRead = 0
SELECT * FROM vwNotifications WHERE NotificationRead IS NULL or NotificationRead = 0
ELSE IF @GetRead = 1
SELECT * FROM vwNotifications WHERE NotificationRead = 1
ELSE
SELECT * FROM vwNotifications WHERE NotificationRead IS NULL or NotificationRead in 0, 1
Note: Please don't actually use SELECT * in production code. Name your columns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With