我试图在存储过程中的每个循环中从表变量中删除行,但有时它会一直循环并且无法删除记录。即使我尝试打印该值,该记录仍然存在。执行删除语句时,我没有收到任何错误。
是否存在从表变量中删除的实例延迟导致循环不结束?
这是我的代码:
--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
这是我从打印价值观中得到的:
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
然后脚本在 10406 处循环。
注意:在这部分脚本之前,我已经将@temp_table 用于其他进程,这就是为什么 rid 值现在为 10400 及以上的原因