以下代碼將循環無窮大。但是,在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)
工作正常。
+1 - 爲了好的答案。 – Devart
很容易假設'#t'爲空時'@ id'將會爲空。 – ca9163d9