以下代码将无限循环。然而,在SSMS中停止查询后,表为空。将 if @id is not null
更改为 if @@rowcount > 0
将获得预期结果。为什么当#t
为空时@id没有得到空值?
select 100 id into #t
l:
declare @id int
select top 1 @id = Id from #t
if @id is not null
begin
print @id
--begin try
raiserror ('Test error', 16, 10)
--end try
--begin catch
--end catch
delete from #t where Id = @id
goto l
end
(1 row(s) affected) 100 Msg 50000, Level 16, State 10, Line 10 Test error (1 row(s) affected) --------- The row was deleted here. 100 Msg 50000, Level 16, State 10, Line 10 Test error (0 row(s) affected) 100 Msg 50000, Level 16, State 10, Line 10 Test error ......
更新:
将 select top 1 @id = Id from #t
更改为 set @id = (select top 1 Id from #t)
效果很好。
最佳答案
如果#t
为空,此选择
不会为@id
分配值:
select top 1 @id = Id from #t
修复它的一种方法:
set @id = null
select top 1 @id = Id from #t
关于sql-server - 为什么是无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17440475/