5

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.

2
  • 1
    you can use ISNULL/ COALESCE like this and ISNULL(EventName,'')= ISNULL(@test,'') Commented Apr 28, 2015 at 12:10
  • @ughai can u please add it in the answer so that I can mark it as the answer. Commented Apr 28, 2015 at 12:19

5 Answers 5

2

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
                 )
            )
Sign up to request clarification or add additional context in comments.

Comments

1

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,'')

Comments

1

How about ISNULL?

Replaces NULL with the specified replacement value.

Something like

select * 
from [dbo].[ViewsConfiguration] 
where PolicyId= 139 
and EventName= ISNULL(@test,EventName)

1 Comment

This is not sargable and it will filter out eventnames where they are NULLs
0

You could check for it explicitly with the is operator:

SELECT * 
FROM   [dbo].[ViewsConfiguration] 
WHERE  PolicyId = 139 AND 
       (EventName = @test OR (@test IS NULL AND EventName IS NULL))

Comments

0

If you only want null rows if @test is null you can use a combination of NULLIF and ISNULL:

SELECT * FROM [dbo].[ViewsConfiguration] WHERE PolicyId= 139 
     AND ISNULL(NULLIF(EventName, @test), NULLIF(@test, EventName)) IS NULL

ISNULL(NULLIF(EventName, @test), NULLIF(@test, EventName)) delivers null if the values are both null or if they are equal:

EventName      @test        Result
----------------------------------
null           null         null   
[value]        null         [value]   
null           [value]      [value]  
[value1]       [value2]     [value1]  
[value]        [value]      null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.