ROLLBACK TRANSACTION请求在sql server中没有相应的BEGIN TRANSACTION错误

时间:2012-05-24 18:44:53

标签: sql transactions

我收到错误“ROLLBACK TRANSACTION请求没有相应的BEGIN TRANSACTION”。如果任何delete语句的行计数为零,我试图回滚事务。以下是我的代码。我究竟做错了什么?请帮忙

alter procedure delete_staff(@staffID varchar(10))
as
declare @tempvar varchar(50), @staffName varchar(50), @jobTitle varchar(50), @dept varchar(50)
begin transaction trans1
        declare @rc1 int
        declare @rc2 int
        declare @rc3 int
        select @tempvar = left(@staffID,1) from Staff
        delete from staff where staffID = @staffID
        set @rc1=@@rowcount
        delete from Login where userID = @staffID 
        set @rc2=@@rowcount
        begin
        if(@tempvar='S')
                begin
                delete from Specialist where specialistID = @staffID    
                set @rc3=@@rowcount
                end
        else if(@tempvar='H')
                begin
                delete from Helpdesk_Operator where helpdesk_OperatorID = @staffID
                set @rc3=@@rowcount
                end
        commit transaction trans1
        end
        if(@rc1=0 or @rc2=0 or @rc3=0)
        begin
        rollback transaction trans1
        end

4 个答案:

答案 0 :(得分:5)

如果您提交了该事务,则无法进行回滚。做其中一个:

if(@rc1=0 or @rc2=0 or @rc3=0)
begin
  rollback transaction trans1
end else begin
  commit transaction trans1
end

答案 1 :(得分:4)

您在回滚的if语句之前有commit transaction trans1。在您检查计数之前,将始终提交交易。

答案 2 :(得分:1)

我相信commit transaction trans1总是受到打击,因此您将无法从该点回滚。

答案 3 :(得分:1)

如果您的事务在实际进入commit语句之前已经提交,则会发生这种情况。 您可以在“COMMIT TRANSACTION”声明之前提供“If(@@ TRANCOUNT> 0)”条件。

例如:

 BEGIN TRANSACTION
  SELECT 0--Statements To Excecute
  ROLLBACK
  IF(@@TRANCOUNT>0)
  COMMIT TRANSACTION

OR

  BEGIN TRY
  BEGIN TRANSACTION
  SELECT 0 --Statements To Excecute     
  COMMIT TRANSACTION
  END TRY
  BEGIN CATCH
  IF(@@TRANCOUNT>0)
  ROLLBACK
  END CATCH