null无法按预期工作的情况

时间:2011-08-03 15:06:51

标签: sql-server tsql sql-server-2008

考虑这个非常简短的T-SQL代码,它使用案例

对可空列进行测试
declare @t table(data varchar(10) null)
insert into @t values('something')
insert into @t values(null)

select data, 
    case data when null
        then 'missing'
        else 'not missing'
    end as test
from @t

我得到的输出是:

data        test
---------   -----------
something   not missing
NULL        not missing

然而我所期待的是

data        test
---------   -----------
something   not missing
NULL        missing

关于对此可空值的测试,我错过了什么

5 个答案:

答案 0 :(得分:39)

你想要这样的东西:


select data,      
case when data is null         
then 'missing'         
else 'not missing'     
end as test from @t 

答案 1 :(得分:2)

大小写可能不适用于null。使用coalesce或isnull。

declare @t table(data varchar(10) null)
insert into @t values('something')
insert into @t values(null)

select data, 
case coalesce(data, 'missing')
    when 'missing' then 'missing'
    else 'not missing'
end as test
from @t

答案 2 :(得分:1)

declare @t table(data varchar(10) null)
insert into @t values('something')
insert into @t values(null)
select data,     
case  when data  is null     
 then 'missing'        else 'not missing' 
  end as test from @t

这将给出预期的答案。

答案 3 :(得分:1)

应该如下所示

select data,
(case when data is null then 'missing' else 'not missing' end) as test from @t

答案 4 :(得分:0)

意识到这是一个旧帖子,但我遇到了这个线程,因为我最近遇到了同样的问题。我以前成功地使用了以下语法(正如上面有些人指出的那样):

case [sourcecolumn] when NULL then ...<alternative output>...

示例:

    , CASE LOWER(EmailAddr)
        WHEN NULL THEN NULL
        WHEN '' THEN NULL
        WHEN 'no email address' THEN NULL -- several mixed case variations
        -- Source email address may also contain carriage returns!
        -- REPLACE(REPLACE(@str, CHAR(13), ''), CHAR(10), '')
        -- Retain original email address, but switch it to all lower case and remove any whitespaces/CR/LF chars.
        ELSE LOWER(REPLACE(REPLACE(REPLACE(EmailAddr, ' ', ''), CHAR(10), ''), CHAR(13), ''))
    END

但最近这并没有给出预期/想要的结果(不确定是否是由于源列类型,它只是一个 Varchar)。

但是,我发现以下语法对我有用:

case When [sourcecolumn] IS Null Then ...<alternative output>...

请注意,如果您有一组要检查的条件(不仅仅是 Null),那么您必须将 [sourcecolumn] 添加到每个条件测试行中。

重新设计的示例:

    , CASE
        WHEN LOWER(EmailAddr) IS NULL THEN NULL
        WHEN LOWER(EmailAddr) = '' THEN NULL
        WHEN LOWER(EmailAddr) = '#N/A' THEN NULL
        WHEN LOWER(EmailAddr) = 'no email address' THEN NULL -- several mixed case variations
        -- Retain original email address, but switch it to all lower case and remove any possible whitespaces/CR/LF chars.
        ELSE LOWER(REPLACE(REPLACE(REPLACE(EmailAddr, ' ', ''), CHAR(10), ''), CHAR(13), ''))
    END