【问题标题】:Batchwise Script Execution批量脚本执行
【发布时间】:2013-07-20 19:14:05
【问题描述】:

我有很长的脚本,其中包含创建表、创建模式、插入数据、更新表等。我只能通过批量脚本来执行此操作。我之前运行过它,但每次都会因此而产生一些错误一些对象将出现在数据库中。因此,如果出现问题,需要一些可以处理批处理执行的机制,整个脚本应该回滚。

感谢您的帮助和时间。

--343

【问题讨论】:

    标签: sql sql-server sql-server-2008 tsql ssis


    【解决方案1】:

    试试这个:

    DECLARE @outer_tran int;  
    SELECT @outer_tran = @@TRANCOUNT;
    
    -- find out whether we are inside the outer transaction
    -- if yes - creating save point if no starting own transaction
    IF @outer_tran > 0 SAVE TRAN save_point ELSE BEGIN TRAN;
    
    BEGIN TRY
        -- YOUR CODE HERE
    
        -- if no errors and we have started own transaction - commit it
        IF @outer_tran = 0 COMMIT;
    END TRY
    BEGIN CATCH
        -- if error occurred - rollback whole transaction if it is own
        -- or rollback to save point if we are inside the external transaction
        IF @outer_tran > 0 ROLLBACK TRAN save_point ELSE ROLLBACK;
    
        --and rethrow original exception to see what happens
        DECLARE
            @ErrorMessage nvarchar(max),
            @ErrorSeverity int,
            @ErrorState int;
    
        SELECT
            @ErrorMessage = ERROR_MESSAGE() + ' Line ' + cast(ERROR_LINE() as nvarchar(5)),
            @ErrorSeverity = ERROR_SEVERITY(), 
            @ErrorState = ERROR_STATE();
    
        RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
    END CATCH
    

    【讨论】:

      【解决方案2】:

      虽然我可能没有抓住您问题的所有细微差别,但我相信 XACT_ABORT 会提供您所寻求的功能。只需添加一个

      SET XACT_ABORT ON;
      

      到脚本的开头。

      使用 2005 版 SQL Server,您还可以访问 TSQL 中的 try/catch 块。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多