Why is this an endless loop?

The following code will be infinite. However, after the request was completed in SSMS, the table was empty. Changing if @id is not null to if @@rowcount > 0 will produce the expected result. Why didn't @id get a null value when #t empty?

 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 50,000, Level 16, State 10, Line 10
 Test error

 (1 row (s) affected) --------- The row was deleted here.
 100
 Msg 50,000, Level 16, State 10, Line 10
 Test error

 (0 row (s) affected)
 100
 Msg 50,000, Level 16, State 10, Line 10
 Test error

 ......

Update:
Change select top 1 @id = Id from #t to set @id = (select top 1 Id from #t) fine.

+4
source share
3 answers

This select will not assign @id if #t empty:

 select top 1 @id = Id from #t 

One way to fix this:

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

Try this option -

 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
source

Edit

 select top 1 @id = Id from #t 

to

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

is a simple solution.

+1
source

Source: https://habr.com/ru/post/1489405/


All Articles