2009-09-30 75 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