2009-09-30 76 views
3

我要检查,如果@a是@b不同的 “ANSI_NULLS关”:SQL “ANSI_NULLS OFF” 比较

set ansi_nulls off 
declare @a int = 1; 
declare @b int = null; 
select case when @a<>@b then 'diff' else 'equal' end '@[email protected] ?' --RETURNS 'diff' 

但不使用 “SET ANSI_NULLS关闭”。我想出了以下内容,但它非常冗长:

select 
    case 
    when @a is null  and @b is not null then 'diff' -- null x 
    when @a is not null and @b is null  then 'diff' -- x null 
    when @a is null  and @b is null  then 'equal' -- null null 
    when @a <> @b         then 'diff' -- x x 
    else 'equal' 
    end 

有没有更简单的方法呢? 谢谢, 内斯特

回答

1

坚持你的逻辑,而不是使用ISNULL或COALESCE,试试这个:

select 
    case 
    when @[email protected]      then 'equal' -- x x 
    when @a is null and @b is null then 'equal' -- null null 
    else 'diff' 
    end 

这是更好的,但:

select 
    case 
    when @[email protected] OR COALESCE(@a,@b) is null then 'equal' 
    else 'diff' 
    end 
+1

感谢。有时我认为SQL应该有一个非ANSI比较的特殊操作符。对?像@a =?= @ b,@a @b ... – Nestor 2009-09-30 20:10:03