2

我试图在存储过程中的每个循环中从表变量中删除行,但有时它会一直循环并且无法删除记录。即使我尝试打印该值,该记录仍然存在。执行删除语句时,我没有收到任何错误。

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

这是我的代码:

    --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 及以上的原因

4

2 回答 2

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 导致循环不“前进”。

于 2012-10-10T09:50:28.267 回答
0

我的错。我已经找到了导致无限循环的原因。在我从表变量中删除 @current_id 之前,我有这段代码

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

我的 CATCH 块中的 continue 跳过了 delete 语句。

于 2012-10-12T06:07:22.000 回答