存储过程和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
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2015-08-11 git日志的查看与修改
2015-08-11 git reset到之前的某一个commit或者恢复之前删除的某一个分支