简体   繁体   中英

SQL “ANSI_NULLS OFF” comparison

I want to check if @a is different from @b in the "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 '@a=@b ?' --RETURNS 'diff'

but without using "set ansi_nulls off". I came up with the following, but it's quite verbose:

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

is there a shorter way of doing this? Thanks, Nestor

sticking to your logic, and not using ISNULL or COALESCE, try this:

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

this is better though:

select
  case 
     when @a=@b OR COALESCE(@a,@b) is null then 'equal'
     else 'diff'
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM