Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't setting a nvarchar variable to null return nothing in this stored proc?

When @RadioServiceGroup is set to NULL, I want to return all the records from the sbi_l_radioservicecodes table which has about 120 records. However, when I execute the following procedure and set the @RadioServiceGroup to NULL, it returns no records. Here is the stored proc:

CREATE PROCEDURE [dbo].[GetRadioServiceCodes] 
@RadioServiceGroup nvarchar(1000) = NULL
AS
BEGIN
IF(@RadioServiceGroup = NULL)
    BEGIN
        SELECT rsc.RadioService
        FROM sbi_l_radioservicecodes rsc    
    END
    ELSE
    BEGIN       
        SELECT rsc.RadioService
        FROM sbi_l_radioservicecodes rsc
        WHERE rsc.RadioServiceGroup = @RadioServiceGroup    
    END
END
like image 908
Xaisoft Avatar asked Dec 03 '22 08:12

Xaisoft


2 Answers

Try "IS NULL" instead of "= NULL"

like image 175
Corey Trager Avatar answered Apr 08 '23 21:04

Corey Trager


Curious, is it just a syntax thing on why = does not work on nvarchar for NULL

Some people are saying that NULL = NULL evaluates to false. This is wrong. NULL = NULL evaluates to NULL.

The result (NULL) is not true, so the ELSE condition is run.

See also : ThreeValuedLogic on Wikipedia

Another affect you should be aware of - Concatenation: NULL + @SomeVar evaluates to NULL. This can wipe out a computed string unexpectedly.

like image 45
Amy B Avatar answered Apr 08 '23 21:04

Amy B