2011-05-20 103 views
0

我試圖從表中刪除大量行,並避免在同一時間使事務日誌過大。似乎互聯網上的大多數人推薦使用BEGIN TRAN/COMMIT TRAN語句。我並不是真正的SQL專家,所以我只是試圖將僞碼轉換爲ms sql(SQL Server 2005)。這裏是代碼:關鍵字「開始」附近的語法不正確

set rowcount 1000 
while (1=1) 
BEGIN 
    with MonthEndDates as (
     select max(Rundate) MonthEnd 
     from table3 
     group by convert(varchar(6), RunDate, 112)) 
    begin transaction T1 
    delete from table1 where 
    table2id in 
    (select table2id from table2 where 
    table3id in 
    (select table3id from table3 
    where RunDate < getdate()-30 
    and RunDate not in (select MonthEnd from MonthEndDates))) 
    commit transaction T1 
    if @@rowcount = 0 
    break 
END 
set rowcount 0 

我是否正確地做這件事?如果是的話,爲什麼我得到這個錯誤:關鍵字'開始'附近的語法不正確。我也試着刪除事務的標籤,但它沒有幫助

正如我說我不是在SQL所以任何幫助,將不勝感激良好

感謝

+2

的'開始交易T1'會需要在「WITH」之前進行並以分號結束。 – 2011-05-20 16:19:37

+0

感謝馬丁的這樣一個qucik迴應。它的工作現在! – Student 2011-05-20 16:28:19

回答

1
set rowcount 1000 
while (1=1) 
BEGIN 
    begin transaction T1 

    --The CTE goes with the DELETE 
    ;with MonthEndDates as (
     select max(Rundate) MonthEnd 
     from table3 
     group by convert(varchar(6), RunDate, 112)) 
     delete from table1 where 
    table2id in 
    (select table2id from table2 where 
    table3id in 
    (select table3id from table3 
    where RunDate < getdate()-30 
    and RunDate not in (select MonthEnd from MonthEndDates))); 

    commit transaction T1 
    if @@rowcount = 0 
    break 
END 
set rowcount 0 
相關問題