2013-07-03 53 views
4

以下代碼將循環無窮大。但是,在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 #tset @id = (select top 1 Id from #t)工作正常。

回答

5

如果#t爲空,這select不會賦值給@id

select top 1 @id = Id from #t 

一種方法來解決它:

set @id = null 
select top 1 @id = Id from #t 
+0

+1 - 爲了好的答案。 – Devart

+0

很容易假設'#t'爲空時'@ id'將會爲空。 – ca9163d9

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 
1

變化

select top 1 @id = Id from #t 

select @id = (select top 1 Id from #t)` 

是一個簡單的辦法。