如何在sql server中提交和回滚事务?

时间:2010-10-14 17:36:10

标签: sql-server-2008 transactions

我有一个巨大的脚本,用于从一台服务器创建表和移植数据。所以这个剧本基本上有 -

  1. 为表创建语句。
  2. 插入以将数据移植到这些新创建的表中。
  3. 为存储过程创建语句。
  4. 所以我有这个代码,但它基本上不起作用@@ ERROR总是为零我认为..

    BEGIN TRANSACTION
    --CREATES
    --INSERTS
    --STORED PROCEDURES CREATES
        -- ON ERROR ROLLBACK ELSE COMMIT THE TRANSACTION
        IF @@ERROR != 0
            BEGIN
    
                PRINT @@ERROR
                          PRINT 'ERROR IN SCRIPT'
                ROLLBACK TRANSACTION
                RETURN
            END
        ELSE
        BEGIN
            COMMIT TRANSACTION
            PRINT 'COMMITTED SUCCESSFULLY'
        END
        GO
    

    任何人都可以帮我写一个事务,基本上会回滚错误并提交,如果一切都很好..我可以在某处使用RaiseError ..

3 个答案:

答案 0 :(得分:26)

请勿使用@@ERROR,而是使用BEGIN TRY/BEGIN CATCH。有关示例程序,请参阅此文章:Exception handling and nested transactions

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

答案 1 :(得分:2)

根据http://msdn.microsoft.com/en-us/library/ms188790.aspx

@@ ERROR:返回上次执行的Transact-SQL语句的错误号。

您必须在每个语句之后检查才能执行回滚并返回。

提交可以在最后。

HTH

答案 2 :(得分:0)

避免直接引用' @@ ERROR'。 这是一个可以丢失的轻浮小事。

Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ......