本文转自:http://geekswithblogs.net/bbiales/archive/2012/03/15/how-to-nest-transactions-nicely---quotbegin-transactionquot-vs-quotsave.aspx

Do you write stored procedures that might be used by others?  And those others may or may not have already started a transaction?  And your SP does several things, but if any of them fail, you have to undo them all and return with a code indicating it failed?

Well, I have written such code, and it wasn’t working right until I finally figured out how to handle the case when we are already in a transaction, as well as the case where the caller did not start a transaction.  When a problem occurred, my “ROLLBACK TRANSACTION” would roll back not just my nested transaction, but the caller’s transaction as well.  So when I tested the procedure stand-alone, it seemed to work fine, but when others used it, it would cause a problem if it had to rollback.  When something went wrong in my procedure, their entire transaction was rolled back.  This was not appreciated.

Now, I knew one could "nest" transactions, but the technical documentation was very confusing.  And I still have not found the approach below documented anywhere.  So here is a very brief description of how I got it to work, I hope you find this helpful.

My example is a stored procedure that must figure out on its own if the caller has started a transaction or not.  This can be done in SQL Server by checking the @@TRANCOUNT value.  If no BEGIN TRANSACTION has occurred yet, this will have a value of 0.  Any number greater than zero means that a transaction is in progress.  If there is no current transaction, my SP begins a transaction. But if a transaction is already in progress, my SP uses SAVE TRANSACTION and gives it a name.  SAVE TRANSACTION creates a “save point”.  Note that creating a save point has no effect on @@TRANCOUNT.

So my SP starts with something like this:

DECLARE @startingTranCount int
SET @startingTranCount = @@TRANCOUNT IF @startingTranCount > 0
SAVE TRANSACTION mySavePointName
ELSE
BEGIN TRANSACTION
-- …


Then, when ready to commit the changes, you only need to commit if we started the transaction ourselves:

IF @startingTranCount = 0
COMMIT TRANSACTION

And finally, to roll back just your changes so far:

-- Roll back changes...
IF @startingTranCount > 0
ROLLBACK TRANSACTION MySavePointName
ELSE
ROLLBACK TRANSACTION

Here is some code that you can try that will demonstrate how the save points work inside a transaction.

This sample code creates a temporary table, then executes selects and updates, documenting what is going on, then deletes the temporary table.

if running in SQL Management Studio, set Query Results to: Text for best readability of the results.

-- Create a temporary table to test with, we'll drop it at the end.
CREATE TABLE #ATable(
[Column_A] [varchar](5) NULL
) ON [PRIMARY] GO
SET NOCOUNT ON
-- Ensure just one row - delete all rows, add one
DELETE #ATable
-- Insert just one row
INSERT INTO #ATable VALUES('000') SELECT 'Before TRANSACTION starts, value in table is: ' AS Note, * FROM #ATable SELECT @@trancount AS CurrentTrancount
--insert into a values ('abc')
UPDATE #ATable SET Column_A = 'abc'
SELECT 'UPDATED without a TRANSACTION, value in table is: ' AS Note, * FROM #ATable
BEGIN TRANSACTION
SELECT 'BEGIN TRANSACTION, trancount is now ' AS Note, @@TRANCOUNT AS TranCount
UPDATE #ATable SET Column_A = '123'
SELECT 'Row updated inside TRANSACTION, value in table is: ' AS Note, * FROM #ATable
SAVE TRANSACTION MySavepoint
SELECT 'Save point MySavepoint created, transaction count now:' as Note, @@TRANCOUNT AS TranCount
UPDATE #ATable SET Column_A = '456'
SELECT 'Updated after MySavepoint created, value in table is: ' AS Note, * FROM #ATable
SAVE TRANSACTION point2
SELECT 'Save point point2 created, transaction count now:' as Note, @@TRANCOUNT AS TranCount
UPDATE #ATable SET Column_A = '789'
SELECT 'Updated after point2 savepoint created, value in table is: ' AS Note, * FROM #ATable
ROLLBACK TRANSACTION point2
SELECT 'Just rolled back savepoint "point2", value in table is: ' AS Note, * FROM #ATable
ROLLBACK TRANSACTION MySavepoint
SELECT 'Just rolled back savepoint "MySavepoint", value in table is: ' AS Note, * FROM #ATable
SELECT 'Both save points were rolled back, transaction count still:' as Note, @@TRANCOUNT AS TranCount
ROLLBACK TRANSACTION
SELECT 'Just rolled back the entire transaction..., value in table is: ' AS Note, * FROM #ATable DROP TABLE #ATable

[转]How to nest transactions nicely - "begin transaction" vs "save transaction" and SQL Server的更多相关文章

  1. 事务操作(BEGIN/COMMIT/ROLLBACK/SAVE TRANSACTION)

    BEGIN TRANSACTION 标记一个显式本地事务的起始点. BEGIN TRANSACTION 使 @@TRANCOUNT 按 1 递增. BEGIN TRANSACTION 代表一点,由连接 ...

  2. SQL SAVE TRANSACTION

    --创建存储过程 create procedure qiantaoProc @asd nchar(10) as begin begin try begin transaction innerTrans ...

  3. SQL Server does not purge row versioning records even the transaction are committed if there are other open transaction running in the databases with read-committed snapshot enabled .

    This is a by-design behavior. There is only one allocation unit in tempdb that istracking the versio ...

  4. [转]sql server transaction

    本文转自: http://www.2cto.com/database/201208/146734.html sql事务(Transaction)用法介绍及回滚实例   事务(Transaction)是 ...

  5. sql server 学习笔记 (nested transaction 嵌套事务)

    什么时候会用到嵌套事务 ? 为了代码复用,我们会写许多的储蓄过程,而中间如果需要使用到 transaction 难免就会发生嵌套了. sql server 并不直接支持嵌套事务. 但它可以用一些招式来 ...

  6. SQL Server 数据库的维护(三)__事务(transaction)和锁

    --维护数据库-- --事务(transaction)和锁-- --事务(transaction)-- --概述: 事务是指封装了一组T-SQL语句的单个逻辑单元.单元中的所有语句作为一个整体,在满足 ...

  7. [杂]SQL Server 之 Understanding Connection Pooling and Transactions

    A SqlConnection consists of two parts: the public instance that your code interacts with (the outer ...

  8. SQL Server save transaction

    准备: create table Nums(X int); 目的:只向表中插入一行. --------------------------------------------------------- ...

  9. [官网]How to use distributed transactions with SQL Server on Docker

    How to use distributed transactions with SQL Server on Docker https://docs.microsoft.com/en-us/sql/l ...

随机推荐

  1. ASP.Net Core 2.2 MVC入门到基本使用系列 (一)

    本教程会对基本的.Net Core 进行一个大概的且不会太深入的讲解, 在您看完本系列之后, 能基本甚至熟练的使用.Net Core进行Web开发, 感受到.Net Core的魅力. 本教程知识点大体 ...

  2. javascript快速排序的思考

    还记得三个月前,学习过快速排序,示例所讲的python快速排序十分易于理解,然而网上学习的c#的快速排序当时就懵逼的,现在已经全忘了,大概记得个思路 在学习完了一些高级的js方法后,今天用js模拟了p ...

  3. C#检测并安装https站点的数字证书,CefSharp和HttpWebRequest通过会话Cookie实现自动登录访问https站点

    HttpUtil工具类: using System; using System.Collections.Generic; using System.IO; using System.Linq; usi ...

  4. UWP开发---嵌套DataTemplate&模板选择器

    对于Json结构体items不完全一致的情况下,在UWP平台是如何处理数据,并通过不同的模板选择,进行显示呢? 一,嵌套Json分析 1,结构 通过抓取index的API(点击请求API)获取到的js ...

  5. JSOI2010 满汉全席

    题目链接:戳我 一个2-SAT的模板题. (什么是2-SAT呢?就是解决一个情况两种决策的问题,我们根据"选了其中一个点A就必须选一个点B的原则,从A向B连边.最后判断如果在一个强连通分量里 ...

  6. docker 搭建Mysql集群

    docker基本指令: 更新软件包 yum -y update 安装Docker虚拟机(centos 7) yum install -y docker 运行.重启.关闭Docker虚拟机 servic ...

  7. Java程序员的日常—— Spring Boot单元测试

    关于Spring boot 之前没有用Spring的时候是用的MockMvc,做接口层的测试,原理上就是加载applicationContext.xml文件,然后模拟启动各种mybatis\连接池等等 ...

  8. Java CAS ABA问题发生的场景分析

    提到了CAS操作存在问题,就是在CAS之前A变成B又变回A,CAS还是能够设置成功的,什么场景下会出现这个问题呢?查了一些资料,发现在下面的两种情况下会出现ABA问题. 1.A最开始的内存地址是X,然 ...

  9. 向 webview 添加 userScript

    添加前,网页代码如下: <!DOCTYPE html> <html> <!--<script type="text/javascript"> ...

  10. D10——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D10 20180906内容纲要: 1.协程 (1)yield (2)greenlet (3)gevent (4)gevent实现单线程下socket多并发 2. ...