【问题标题】:Delete from table variable MS SQL从表变量 MS SQL 中删除
【发布时间】:2012-10-10 09:44:40
【问题描述】:

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

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

这是我的代码:

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

【问题讨论】:

    标签: sql loops table-variable


    【解决方案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 导致循环不“前进”。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-20
        • 2018-06-10
        • 2017-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多