我最近遇到了Server中的CASE-THEN-ELSE语句(如果有关系的话,2014年),更准确地说,“简单”和“搜索”案例表达式。到目前为止,我认为这2之间的唯一区别只是格式和/或用两种方式编写案例表达式的习惯,但我想我完全错了:)
CASE表达式有两种格式: 简单案例表达式将表达式与一组简单表达式进行比较,以确定结果。 搜索的案例表达式计算一组布尔表达式以确定结果。
下面是一个例子:
set nocount on
declare @test nvarchar(50) = null
select
@test as [The NULL Value],
case
when @test is null
then null
else 'Not Null???'
end as [As Expected],
case @test
when null
then null
else 'Not Null???'
end as [The Pickle] 结果是:
The NULL Value As Expected The Pickle
-------------------------------------------------- ----------- -----------
NULL NULL Not Null???有人能提供到MSDN文档的链接吗?也许可以用更详细的方式解释这一点吗?)
P.S.:我敢打赌你们中的很多人肯定这两种结果都会产生相同的结果:D
发布于 2016-05-14 11:54:34
一点都不奇怪..。
的“捷径”
case @test
when null
then null
else 'Not Null???'
end as [The Pickle] 将变量/列(此处:@test)与WHEN子句(when null)中的值与常规相等运算符(@test = null)进行比较,使用标准等式运算符(@test = null)比较NULL总是未定义/NULL本身(标准SQL行为),因此不为 true
因此,您将得到这个结果-- Not Null??? --用于列The Pickle。
如果要检查NULL,则必须使用IS NULL,如第一个示例所示.
发布于 2016-05-14 12:19:11
declare @t int =1
--simple case
select
case @t
when 1 then 1 else null end上面的查询扩展到下面的表单。
select
case when @t=1 then 1 else null end因此,带有null的查询将扩展到下面
declare @t int=null
select case @t
when null then null else 'notnull' end被扩展到
select case when @t=null then null else 'notnull' end 它的计算值显然为null。
因此,总之,仅在null情况下,您将无法获得预期的结果,请在下面尝试查看
declare @t int=null
declare @t1 int =1
select
case when @t is null then null else 'notnull' end as 'Searchedcase',
case @t when null then null else 'notnull' end as'simple case',
case when @t1 =1 then 1 else null end as 'Searchedcase for value',
case @t1 when 1 then 1 else null end as'simple case for value'发布于 2016-12-30 17:27:09
https://stackoverflow.com/questions/37226126
复制相似问题