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

后端 未结 14 1786
情书的邮戳
情书的邮戳 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 15:17

    Use INTERSECT operator.

    It's NULL-sensitive and efficient if you have a composite index on all your fields:

    IF      EXISTS
            (
            SELECT  MY_FIELD1, MY_FIELD2, MY_FIELD3, MY_FIELD4, MY_FIELD5, MY_FIELD6
            FROM    MY_TABLE
            INTERSECT
            SELECT  @IN_MY_FIELD1, @IN_MY_FIELD2, @IN_MY_FIELD3, @IN_MY_FIELD4, @IN_MY_FIELD5, @IN_MY_FIELD6
            )
    BEGIN
            goto on_duplicate
    END
    

    Note that if you create a UNIQUE index on your fields, your life will be much simpler.

提交回复
热议问题