Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Check for null values in variables

I am trying to compare a table value to a variable which can be null, however since we cannot equate this to null hence this is not comparable.

declare @test varchar(33) -- This can or cannot be NULL;
select * from [dbo].[ViewsConfiguration] where PolicyId= 139 and EventName= @test

This can be done using switch or if , however looking for a more elegant way to do this.

like image 497
SJMan Avatar asked Sep 29 '22 03:09

SJMan


2 Answers

You can compare both to NULL:

DECLARE @test VARCHAR(33) 
SELECT  *
FROM    [dbo].[ViewsConfiguration]
WHERE   PolicyId = 139
        AND ( EventName = @testd
              OR ( EventName IS NULL
                   AND @testd IS NULL
                 )
            )
like image 120
Giorgi Nakeuri Avatar answered Oct 03 '22 00:10

Giorgi Nakeuri


You can use ISNULL / COALESCE. Your query would be like

declare @test varchar(33) -- This can or cannot be NULL;
select * from [dbo].[ViewsConfiguration] where PolicyId= 139 and ISNULL(EventName,'')= ISNULL(@test,'')
like image 30
ughai Avatar answered Oct 03 '22 02:10

ughai