How to compare different values in sql server

前端 未结 4 1162
日久生厌
日久生厌 2021-01-07 08:10

I must to check if two values, X and Y are different. If both are null, they must be considered as equal.

The unique way I found is:

select 1 as valu         


        
相关标签:
4条回答
  • 2021-01-07 08:29

    You could try using NULLIF like this:

    WHERE NULLIF(@X,@Y) IS NOT NULL OR NULLIF(@Y,@X) IS NOT NULL
    
    0 讨论(0)
  • 2021-01-07 08:31

    I think you could use COALESCE for that

    WHERE coalesce(@X, '') <> coalesce(@Y, '')
    

    What it does it returns an empty string if one of variables is null, so if two variables are null the two empty strings become equal.

    0 讨论(0)
  • 2021-01-07 08:37

    You can use ISNULL

    WHERE ISNULL(@X,'') <> ISNULL(@Y,'')
    
    0 讨论(0)
  • 2021-01-07 08:38

    I typically use a technique I picked up from here

    SELECT 1 AS valuesDifferent
    WHERE  EXISTS (SELECT @X
                   EXCEPT
                   SELECT @Y) 
    

    WHERE EXISTS returns true if the sub query it contains returns a row. This will happen in this case if the two values are distinct. null is treated as a distinct value for the purposes of this operation.

    0 讨论(0)
提交回复
热议问题