Ryan Balzan
Ryan Balzan

Reputation: 21

SQL update statement - comparing values for nullable fields

So we're using SQL Server in our DWH environment and we compare the values between the source and destination to update values accordingly. In some of the Merge statements we apply the match condition together with the intersect statement, however for some instances we use directly the update and check with the OR condition.

However, since sometimes we can have nullable fields which would need to be compared this is causing some issues.

We have tried to do the following 3 options:

We could use a similar approach to the Merge statement with the match and intersect but we have noticed that's not optimal for millions of records.

Are there any other viable options that can be implemented?

Upvotes: 1

Views: 83

Answers (1)

SQL_M
SQL_M

Reputation: 2475

Try this CASE WHEN code example:

    ;WITH CTE AS 
(
    SELECT *,
    CASE WHEN ColA IS NULL AND ColB IS NULL THEN 'Equal'
         WHEN ColB IS NOT NULL AND ColB IS NOT NULL 
                                               THEN CASE WHEN ColA = ColB THEN 'Equal'
                                               ELSE 'Not Equal' END
         WHEN ColA IS NULL AND ColB IS NOT NULL THEN 'Not Equal'
         WHEN ColB IS NULL AND ColA IS NOT NULL THEN 'Not Equal'
    END 'Comparison'
FROM YourTable
)                 

DELETE FROM CTE WHERE Comparison = 'Not Equal'

Upvotes: 1

Related Questions