BEGIN TRANSACTION
INSERT INTO TABLE2(bb) values('aaaa')
IF (@@error<>0) 
begin
    ROLLBACK TRANSACTION
    return
end
INSERT INTO TABLE1(bb) values('aaaa')
IF (@@error<>0) 
begin
  ROLLBACK TRANSACTION
  return
end
COMMIT TRANSACTION

解决方案 »

  1.   

    1:如上,加上RETURN后不再往下执行即可。
    2:因先ROLLBACK后继续往下执行,到最后COMMIT时实际上没有启动TRANSACTION
      

  2.   

    DECLARE @tl_error int, @t2_error intBEGIN TRAN
    INSERT INTO TABLE1(bb) values('aaaa')
    -- the INSERT statement.
    SELECT @tl_error = @@ERRORINSERT INTO TABLE2(bb) values('aaaa')SELECT @t2_error = @@ERROR
    -- Test the error values.
    IF @tl_error = 0 AND @t2_error = 0
    BEGIN
       -- Success. Commit the transaction.
       PRINT 'success inserted'
       COMMIT TRAN
    END
    ELSE
    BEGIN
       IF @tl_error<> 0 
          PRINT 'An error occurred during insert into table1.'    IF @t2_error <> 0
          PRINT 'An error occurred during insert into table2.'   ROLLBACK TRAN
    END
    GO
      

  3.   

    DECLARE @tl_error int, @t2_error intBEGIN TRAN
    INSERT INTO TABLE1(bb) values('aaaa')
    -- the INSERT statement.
    SELECT @tl_error = @@ERRORINSERT INTO TABLE2(bb) values('aaaa')SELECT @t2_error = @@ERROR
    -- Test the error values.
    IF @tl_error = 0 AND @t2_error = 0
    BEGIN
       -- Success. Commit the transaction.
       PRINT 'success inserted'
       COMMIT TRAN
    END
    ELSE
    BEGIN
       IF @tl_error<> 0 
          PRINT 'An error occurred during insert into table1.'    IF @t2_error <> 0
          PRINT 'An error occurred during insert into table2.'   ROLLBACK TRAN
    END
    GO