Nulls and the MERGE statement: I need to set a value to infinity. How?

后端 未结 9 1305
慢半拍i
慢半拍i 2021-01-01 20:51

In SQL Server 2008, I\'m using MERGE. Everything is fine except that I have 2 nullable columns. If I pass a null value and the target isn\'t null, MERGE doesn\'t see a diffe

相关标签:
9条回答
  • 2021-01-01 20:51

    You can change the ON part of the merge statement, putting in a check for when both source and target are null.

    MERGE tgt
    USING src
    ON ( -- enter non-nullable columns to match on ...
        tgt.A = src.A
        AND (tgt.C = src.C OR (tgt.C IS NULL AND src.C IS NULL))
    )
    WHEN MATCHED -- ...
    
    0 讨论(0)
  • 2021-01-01 20:59

    Instead of using 0 when the values are null, why not use a value that is highly unlikely to exist? EG (IsNull(tgt.C, 2093128301).

    The datatypes are int so you have a lot to play with......

    0 讨论(0)
  • 2021-01-01 21:00
    WHEN MATCHED AND tgt.c <> src.c OR tgt.c IS NULL AND src.c IS NOT NULL OR tgt.c IS NOT NULL AND src.c IS NULL
    
    0 讨论(0)
  • 2021-01-01 21:00

    This works as well and may be better when you have multiple columns that you want to check if they are different.

      MERGE @t2 a
    
      using @t1 b
    
      ON a.PK = b.PK
    
      WHEN MATCHED AND CHECKSUM(a.PK,a.VALUE)!= CHECKSUM(b.pk,b.VALUE)
    
      THEN UPDATE SET a.VALUE = b.VALUE;
    
    0 讨论(0)
  • 2021-01-01 21:12

    Have you tried SET ANSI_NULLS OFF, which will make NULL=NULL return true? This may create additional issues but it could be a script-level workaround (turn it off then on once you run your proc).

    0 讨论(0)
  • 2021-01-01 21:12

    You can check for null in the ON Clause:

    MERGE TargetTable
    USING (VALUES (0)) as s(x)
    ON last_run is not null
    WHEN not matched then
    insert (last_run) values(getdate())
    when matched then
    update set last_run=getDate();
    
    0 讨论(0)
提交回复
热议问题