代码之家  ›  专栏  ›  技术社区  ›  Vaccano

SQL Server比较为空

  •  2
  • Vaccano  · 技术社区  · 6 年前

    我需要在一个值和它以前的值之间做很多比较。

    例如: ReceivedBy PreviousReceivedBy .

    我从:

    WHERE ReceivedBy != PreviousReceivedBy
    

    但如果其中一个值为空,则返回false(当我真正需要它为true时)。所以我把它更新成这样:

    WHERE ReceivedBy != PreviousReceivedBy
          OR (ReceivedBy IS NULL AND PreviousReceivedBy IS NOT NULL)
          OR (ReceivedBy IS NOT NULL AND PreviousReceivedBy IS NULL)
    

    这很好,但我有一个需要比较的字段的大列表。我想找到一种方法,在不关闭 ANSI_NULLS )

    显然,如果没有其他方法,那么我将把这三行代码放进去进行比较。

    更新:

    举个例子,我希望

    ReceivedBy = 123  
    PreviousReceivedBy = 123  
    Result = FALSE  
    
    ReceivedBy = 5  
    PreviousReceivedBy = 123  
    Result = TRUE  
    
    ReceivedBy = NULL  
    PreviousReceivedBy = 123  
    Result = TRUE
    
    ReceivedBy = 123  
    PreviousReceivedBy = NULL  
    Result = TRUE  
    
    ReceivedBy = NULL  
    PreviousReceivedBy = NULL  
    Result = FALSE  
    
    2 回复  |  直到 5 年前
        1
  •  2
  •   Siyual Lee    6 年前

    另一种不用修改数据的方法是 COALESCE

    Where ReceivedBy != PreviousReceivedBy
    And Coalesce(ReceivedBy, PreviousReceivedBy) Is Not Null
    

    NULL 不能等同于任何东西,甚至不能等同于另一个 无效的 ,因此如果任何值是 无效的 , ReceivedBy != PreviousReceivedBy 将评估为真。

    其次,如果两个值都是 无效的 , the Coalesce(ReceivedBy, PreviousReceivedBy) Is Not Null 将计算为false,强制对其进行筛选。

    如果两者都不是 无效的 ,如果它们相等,则第一个条件将失败。

    诚然,这并没有节省太多代码,但这是一个改进。

    对于需要检查的所有剩余字段,可以很容易地将其分组到括号中,并复制/pasta-d。

    Where (ReceivedBy != PreviousReceivedBy And Coalesce(ReceivedBy, PreviousReceivedBy) Is Not Null)
    And[Or] (Foo != Bar And Coalesce(Foo, Bar) Is Not Null)
    ...
    
        2
  •  2
  •   Michał Turczyn    6 年前

    如果两列都是 varchar S,我想这样说:

    coalesce(ReceivedBy, 'NULL') != coalesce(PreviousReceivedBy, 'NULL')
    

    如果它们是整数,我会把一些值大大降低到零以下(以便清楚地表示 null 值)而不是 'NULL' .

    根据列的名称,我假设它必须是字符串值还是整数值:)

    更新

    正如@siyual指出的,替换字符串应该是“不可能的”,您应该替换 “NULL” 上面有一些非字母字符,如 '#' :)