How to compare different values in sql server

不羁岁月 提交于 2019-12-19 04:51:13

问题


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 valueExists 
where  (@X is null and @Y is not null) 
    or (@Y is null and @X is not null) 
    or (@X <> @Y)

Is there a smart way to write this expression? Thanks!


回答1:


You can use ISNULL

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



回答2:


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.




回答3:


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.




回答4:


You could try using NULLIF like this:

WHERE NULLIF(@X,@Y) IS NOT NULL OR NULLIF(@Y,@X) IS NOT NULL


来源:https://stackoverflow.com/questions/24570954/how-to-compare-different-values-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!