关键字'begin'附近的语法不正确

时间:2011-05-20 16:12:57

标签: sql sql-server sql-server-2005

我正在尝试从表中删除大量行,并避免同时使交易日志过大。似乎互联网上的大多数人都建议使用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

我是否正确行事?如果是,为什么我收到此错误:关键字'begin'附近的语法不正确。我也尝试删除交易标签,但它没有帮助

正如我所说,我在SQL方面不擅长,所以任何帮助都会受到赞赏

由于

1 个答案:

答案 0 :(得分: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
相关问题