2012-10-10 51 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。