【发布时间】:2017-07-28 07:14:04
【问题描述】:
我对以下 2 个 SQL 有疑问:
declare @i1 bit, @b1 bit
declare @i2 bit, @b2 bit
declare @t table (Seq int)
insert into @t values (1)
-- verify data
select case when (select count(1) from @t n2 where 1 = 2) > 0 then 1 else 0 end
-- result 0
select @i1 = 1, @b1 = case when @i1 = 1 or ((select count(1) from @t n2 where 1 = 2) > 0) then 1 else 0 end from @t n where n.Seq = 1
select @i1, @b1
-- result 1, 0
select @i2 = 1, @b2 = case when @i2 = 1 or (0 > 0) then 1 else 0 end from @t n where n.Seq = 1
select @i2, @b2
-- result 1, 1
在执行之前,我认为case部分应该是null = 1 or (0 > 0),它会返回0。
但是现在,我想知道为什么第二个 SQL 会返回 1
【问题讨论】:
-
变量的顺序。检查demo。当您拥有
select @b2 = case when @i2 = 1 or (0 > 0) then 1 else 0 end ,@i2 = 1时,您将获得 1,0 -
我更感兴趣的是这两者的区别:
select @i1 = 1, @b1 = (case when @i1 = 1 or ((select count(1) from @t n2 where 1 = 2) > 0) then 1 else 0 end) from @t n where n.Seq = 1 select @i1, @b1 -- result 1, 0 select @i1 = 1, @b1 = (case when @i1 = 1 then 1 else 0 end) from @t n where n.Seq = 1 select @i1, @b1 -
The order of evaluation isn’t defined,所以我猜 SQL Server 只是通过添加子查询选择了一个不同的。
-
Dirty Secrets of the CASE Expression -
CASE will not always short circuit部分 + 到 ms 连接的链接。
标签: sql sql-server tsql