Sql 删除空值时的大小写逻辑

Sql 删除空值时的大小写逻辑,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,这是我的第一篇文章,我试图对此问题进行彻底搜索,因此,如果它已在其他地方发布多次,请接受我的道歉,但我想知道是否有人在尝试从结果集中删除空值时遇到以下问题: case Occurrence when NULL then '0' else occurrence end as Occurrence, case Aggregate when NULL then '0' else Aggregate end as Aggregate, 这对我的空值没有任

这是我的第一篇文章,我试图对此问题进行彻底搜索,因此,如果它已在其他地方发布多次,请接受我的道歉,但我想知道是否有人在尝试从结果集中删除空值时遇到以下问题:

case Occurrence
    when NULL then '0'
    else occurrence
    end as Occurrence,
case Aggregate
    when NULL then '0'
    else Aggregate
    end as Aggregate,
这对我的空值没有任何影响;然而,这确实起到了作用:

case 
    when occurrence is NULL then '0'
    else occurrence
    end as Occurrence,
case 
    when aggregate is NULL then '0'
    else Aggregate
    end as Aggregate
有人知道为什么会这样吗?我正在使用SQLServer2012

我也不是很精通编程,只有不到一年的SQL经验


谢谢

您应该使用ISNULL()或COALESCE()系统函数来处理null

差不多

SELECT ISNULL(Occurrence , 0) AS Occurrence
      ,ISNULL(Aggregate  , 0) AS Aggregate
FROM Table

在案例陈述中它不起作用的原因

case Occurrence
    when NULL then '0'
    else occurrence
    end as Occurrence,
因为它把它解释为

CASE
WHEN Occurrence = NULL THEN 0
    ELSE Occurrence 
END
在sql server中使用
is Null
is NOT Null
检查Null,如果您使用的是Null like=,或您使用的是:

简单CASE表达式通过将第一个表达式与每个WHEN子句中的表达式进行等效性比较来进行操作。如果这些表达式等效,则将返回THEN子句中的表达式

只允许进行相等性检查

其执行方式如下:

case 
   when occurence = NULL then '0'
   else occurrence
end as Occurrence
然后表达式
occurrence=NULL
返回NULL并被视为False

第二,您的案例使用搜索的案例,具有完整的条件,并且工作正常:

case 
  when occurrence IS NULL then '0'
  else occurrence
end as Occurrence,
所以你的问题是关于column is NULL和column=NULL的区别

select 1 where null =null
select 1 where null is null
您的语句看起来像null等于null

select case when null is null then 1 else 0 end

select case null when null then 1 else 0 end
在您的情况下,使用ISNULL,这将为您提供之后的结果

SELECT ISNULL(null,1)

另外,COALESCE只是CASE的语法糖,在某些情况下是不确定的,而ISNULL和full CASE是真的,但COALESCE能够有两个以上的输入,在某些情况下,coalesce是比isnull更好的选择。是的,更多的输入和基于优先级的类型确定不像第一个表达式上的isnull。人们不知道这一点,一遍又一遍地问同样的问题。非常感谢!我认为最有助于我理解这一点的是:“在sql server中使用is Null或is NOT Null来检查Null,如果您使用任何其他具有Null like=、或@lad2025的运算符,则表示歉意,如果您一直看到此问题,我将向您致歉。不过,我非常感谢你的帮助。非常感谢!!事实上,我确实不明白只有IS NULL和IS NOT NULL才是处理NULL的工作。不用担心,这会让每个人:)非常感激。事实上,我基本上说的是accurrence=NULL,现在知道使用除IS或IS之外的任何其他NULL操作符都能让我真正理解。
select 1 where null =null
select 1 where null is null
select case when null is null then 1 else 0 end

select case null when null then 1 else 0 end
SELECT ISNULL(null,1)