How to compare values which may both be null in T-SQL

后端 未结 14 1758
情书的邮戳
情书的邮戳 2020-12-23 14:20

I want to make sure I\'m not inserting a duplicate row into my table (e.g. only primary key different). All my fields allow NULLS as I\'ve decided null to mean \"all values

14条回答
  •  暖寄归人
    2020-12-23 14:58

    IF EXISTS(SELECT * FROM MY_TABLE WHERE 
                (MY_FIELD1 = @IN_MY_FIELD1 
                         or (MY_FIELD1 IS NULL and @IN_MY_FIELD1 is NULL))  AND
                (MY_FIELD2 = @IN_MY_FIELD2 
                         or (MY_FIELD2 IS NULL and @IN_MY_FIELD2 is NULL))  AND
                (MY_FIELD3 = @IN_MY_FIELD3 
                         or (MY_FIELD3 IS NULL and @IN_MY_FIELD3 is NULL))  AND
                (MY_FIELD4 = @IN_MY_FIELD4 
                         or (MY_FIELD4 IS NULL and @IN_MY_FIELD4 is NULL))  AND
                (MY_FIELD5 = @IN_MY_FIELD5 
                         or (MY_FIELD5 IS NULL and @IN_MY_FIELD5 is NULL))  AND
                (MY_FIELD6 = @IN_MY_FIELD6
                         or (MY_FIELD6 IS NULL and @IN_MY_FIELD6 is NULL)))
                BEGIN
                        goto on_duplicate
                END
    

    Wordy As compared to the IFNULL/COALESCE solution. But will work without having to think about what value will not appear in the data that can be used as the stand in for NULL.

提交回复
热议问题