2012-10-10 52 views
2

我想从我的存储过程中的每个循环逐个删除一个表变量中的行,但有些时候它会保持循环并且无法删除记录。即使当我尝试打印该值时,该记录仍然存在。当我的delete语句执行时,我没有得到任何错误。从表变量中删除MS SQL

是否存在从Table变量中删除导致循环未结束的延迟的实例?

这里是我的代码:

--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以上

回答

1

我不能评论这个,但我相信你已经掩盖了一些重要的内容。

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..... 
*/ 

if ... condition ... 
    begin 
    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 
end -- while loop 

必须有像上述情况,否则短goto语句,它不能跳过print 'TABLE...。条件是FALSE导致循环不“前进”。

0

我的不好。我已经找到了造成无限循环的原因。 我有这样的代码之前,我从我的表变量

BEGIN TRY 
    /* 
     calculations... 
    */ 
END TRY 
BEGIN CATCH 
    continue; 
    print 'ERROR' 
END CATCH; 

在我赶继续块跳过delete语句删除@current_id。