存储过程和transaction

How to rollback a transaction in a stored procedure?

BEGIN TRANSACTION;

BEGIN TRY
    -- Some code
    COMMIT TRANSACTION;
END TRY
BEGIN CATCH

    ROLLBACK TRANSACTION;
END CATCH;

 

 

执行的存储过程需要transaction的话,在调用的时候传入

BEGIN TRANSACTION
DECLARE @usedrecords XML;
SET @usedrecords = N'<Record ID="388" />';
EXEC dbo.pd_trn_Transaction @UsedRecords

 

如果有事务锁定了数据库,那么可以直接rollback

ROLLBACK TRAN

 

 

在执行存储过程的的时候,错误提示

You attempted to acquire a transactional application lock without an active transaction.

 DECLARE @res INT;
        EXEC @res = sp_getapplock @Resource = 'TransactionCheckLock' ,
                                  @LockMode = 'Exclusive' ,
                                  @LockOwner = 'Transaction' ,
                                  @LockTimeout = 10000 ,
                                  @DbPrincipal = 'public';
        IF @res NOT IN ( 0, 1 )
            BEGIN
                RETURN -2;
            END;

存储过程内部,要求TransactionCheckLock,所以在外部调用的时候,必须加上begin transaction

 

sql try/catch rollback/commit - preventing erroneous commit after rollback

I always thought this was one of the better articles on the subject.

It includes the following example that I think makes it clear and includes the frequently overlooked @@trancount which is needed for reliable nested transactions

PRINT 'BEFORE TRY'
BEGIN TRY
    BEGIN TRAN
     PRINT 'First Statement in the TRY block'
     INSERT INTO dbo.Account(AccountId, Name , Balance) VALUES(1, 'Account1',  10000)
     UPDATE dbo.Account SET Balance = Balance + CAST('TEN THOUSAND' AS MONEY) WHERE AccountId = 1
     INSERT INTO dbo.Account(AccountId, Name , Balance) VALUES(2, 'Account2',  20000)
     PRINT 'Last Statement in the TRY block'
    COMMIT TRAN
END TRY
BEGIN CATCH
    PRINT 'In CATCH Block'
    IF(@@TRANCOUNT > 0)
        ROLLBACK TRAN;

    THROW; -- raise error to the client
END CATCH
PRINT 'After END CATCH'
SELECT * FROM dbo.Account WITH(NOLOCK)
GO

 

 

 

 

 

查询没有处理的Transaction

https://stackoverflow.com/questions/3978227/how-to-kill-or-rollback-active-transaction

SELECT * FROM sys.dm_tran_session_transactions 

You can't kill/rollback a transaction from another session without killing the owner session.

I think, allowing to kill/rollback a transaction from another user's session means many design and security rule violations because it requires entering another user session (in the context of the current sql server engine design). That's probably why it is not implemented.

关于如何kill session

https://docs.microsoft.com/en-us/sql/t-sql/language-elements/kill-transact-sql?view=sql-server-2017

 

posted @ 2017-08-11 19:01  ChuckLu  阅读(965)  评论(0编辑  收藏  举报