2013-07-20 234 views
2

我有很长的脚本,其中包含创建表,创建模式,插入数据,更新表等我必须做到这一点只在脚本批处理wise.I之前运行它,但它创建每次有一些错误由于这个对象会出现在数据库中。所以需要一些可以处理批处理执行的机制,如果出现问题,整个脚本应该被回滚。批处理脚本执行

赞赏的帮助和时间。

--343

回答

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 
1

虽然我可能没有引起你的问题的所有细节,我相信XACT_ABORT将提供你所寻求的功能。只需添加一个

SET XACT_ABORT ON; 

到您的脚本的开始。

随着SQL Server 2005的发布,您还可以访问TSQL中的try/catch块。