以下代码将循环无穷大。但是,在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)
可以正常工作。
答案 0 :(得分:5)
如果select
为空,则此@id
不会为#t
分配值:
select top 1 @id = Id from #t
解决问题的一种方法:
set @id = null
select top 1 @id = Id from #t
答案 1 :(得分:2)
试试这个 -
SET NOCOUNT ON;
DECLARE @temp TABLE (Id INT)
INSERT INTO @temp (Id)
VALUES (1),(2)
DECLARE @id INT
WHILE EXISTS(SELECT 1 FROM @temp) BEGIN
SELECT TOP 1 @id = Id
FROM @temp
RAISERROR ('Test error', 16, 10)
DELETE FROM @temp WHERE Id = @id
END
答案 2 :(得分:1)
更改
select top 1 @id = Id from #t
到
select @id = (select top 1 Id from #t)`
是一个简单的解决方案。