SQL Server 跨数据库事务

 
模拟三个库(同一个实例中),分别是DB1、DB2、DB3
整个事务的业务如下:
1、DB1写入表数据
2、DB2写入表数据
3、DB3调用存储过程写入表数据
4、每次写入表数据间隔模拟抛异常流程,查看数据是否回滚
 
 
代码如下:
 
BEGIN TRY
 
    BEGIN TRAN
        INSERT INTO DB1.dbo.Log
                ( Type, Message, Stack, Created )
        VALUES  ( 0, -- Type - int
                  N'Message', -- Message - nvarchar(100)
                  N'Stack', -- Stack - nvarchar(max)
                  '2010-03-12 05:43:17'  -- Created - datetime
                  )
                  
      --  RAISERROR ('插入第一个库后失败.', -- Message text.
                        --16, -- Severity.
                        --1 -- State.
                     --  );
               
        INSERT INTO DB2.dbo.Agent
                ( Name ,
                  Mobile ,
                  Password ,
                  LocationID ,
                  Address ,
                  Status ,
                  CreateTime
                )
        VALUES  ( N'Name' , -- Name - nvarchar(50)
                  'Mobile' , -- Mobile - varchar(16)
                  'Password' , -- Password - varchar(64)
                  0 , -- LocationID - int
                  N'Address' , -- Address - nvarchar(256)
                  0 , -- Status - int
                  '2015-05-22 05:43:48'  -- CreateTime - datetime
                )          
                
        --RAISERROR ('插入第二个库后失败.', -- Message text.
        --                16, -- Severity.
        --                1 -- State.
        --               );
                       
        EXEC TestDB.dbo.SP_T1   --DB3存储过程
                
        RAISERROR ('插入存储过程后失败.', -- Message text.
                    16, -- Severity.
                    1 -- State.
                   );               
    COMMIT TRAN
END TRY
 
BEGIN CATCH
    IF @@TRANCOUNT > 0---------------判断有没有事务
        BEGIN
            PRINT ERROR_MESSAGE()
            ROLLBACK TRAN----------回滚事务
        END 
END CATCH
 
 





原文地址:https://www.cnblogs.com/gossip/p/4522193.html