I'm trying to delete rows from a table variable one by one every loop in my stored procedure but there are times that it keeps looping and cannot delete the record. The record is there even when I tried to PRINT the value. I dont get any errors when my delete statement is executed.
Are there instances that delete from the Table Variable is delayed that is causing the loop to not end?
Here is my code:
--DECLARATIONS
declare @temp_table table
(
rid int identity(1,1),
Account_Code varchar(255),
PRIMARY KEY (rid)
)
declare @row_count int = 0
declare @current_id int
-----------------------------
delete from @temp_table
insert into @temp_table
select distinct a.Account_Code from MyTable a
set @row_count =(select COUNT(*) from @temp_table)
print 'TABLE ROWS COUNT:'+ cast(@row_count as varchar(100))
while(@row_count <> 0)
begin
set @current_id = (select top 1 rid from @temp_table)
print 'Current ID in Process:'+cast(@current_id as varchar(100))
/*
Some Processes Here.....
*/
delete from @temp_table where rid = @current_id
set @row_count =(select COUNT(*) from @temp_table)
print 'TABLE ROWS COUNT:'+ cast(@row_count as varchar(max))
end
This is what I get from printing The Values:
TABLE ROWS COUNT:21
Current ID in Process: 10403
TABLE ROWS COUNT:20
Current ID in Process: 10404
TABLE ROWS COUNT:19
Current ID in Process: 10405
TABLE ROWS COUNT:18
Current ID in Process: 10406
Current ID in Process: 10406
Current ID in Process: 10406
Current ID in Process: 10406
Current ID in Process: 10406
The script then loops at 10406.
NOTE: I already used the @temp_table for other process before this part of the script that is why rid value is now at 10400 and up