为什么它是一个无限循环?

时间:2013-07-03 05:39:12

标签: sql-server sql-server-2008 tsql

以下代码将循环无穷大。但是,在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)可以正常工作。

3 个答案:

答案 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)` 

是一个简单的解决方案。