Home Forums SQL Server 2008 T-SQL (SS2K8) comparison in the merge statement about null values RE: comparison in the merge statement about null values

  • sqlfriends (8/22/2012)


    I use the merge statement in a sproc to insert, update and delete records from a staging table to a production table.

    In the long sql, here is a part of it,

    When Matched and

    ((Student.SchoolID <> esis.SchoolID

    OR

    Student.GradeLevel <> esis.GradeLevel

    OR

    Student.LegalName <> esis.LegalName

    OR

    Student.WithdrawDate <> esis.WithdrawDate

    Student.SPEDFlag <> esis.SPEDFlag

    OR

    Student.MailingAddress <> esis.MailingAddress)

    Then update

    Set Student.Schoolid=esis.schoolid,

    .....

    My question is how about if the column has null values in it.

    for example

    if schoolID is null in production table is null, but in staging table is not null, will the <> return true.

    or if either side of <> has a null value, will it return true.

    I don't want it to omit some records and causing the students records not get updated.

    If not return true, how to fix this?

    THanks

    No the NULLs will not evaluate to true. You would need to include some additional OR conditions.

    OR Student.SchoolID is null

    OR ...

    Anytime you have a NULL on either side of an (in)equality check NULL will not be returned.

    select *

    from sys.objects

    where 1 <> null

    or null <> 1

    or null <> null

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/