question:

if the nested transaction encountered an exception, then rollbacked. How about the outer transaction?

Lets demo this using below code.

create procedure sp1

BEGIN 

BEGIN TRANSACTION
...
exec sp2 COMMIT
END

Now, if SP 2 - rolls back for whatever reason, does SP 1 - commit or rollback or throw exception?

Answer:

The outer transaction will be rollbacked as well.

There are no autonomous transactions in SQL Server. You may see @@TRANCOUNT increase beyond 1, but a rollback affects the whole thing.

Outer proc:

CREATE PROCEDURE dbo.sp1
@trip BIT
AS
BEGIN
SET NOCOUNT ON; BEGIN TRANSACTION; PRINT @@TRANCOUNT; BEGIN TRY
EXEC dbo.sp2 @trip = @trip;
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE();
END CATCH PRINT @@TRANCOUNT; IF @@TRANCOUNT > 0
COMMIT TRANSACTION; PRINT @@TRANCOUNT;
END
GO

Inner proc:

CREATE PROCEDURE dbo.sp2
@trip BIT
AS
BEGIN
SET NOCOUNT ON; BEGIN TRANSACTION; PRINT @@TRANCOUNT; IF @trip = 1
BEGIN
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END
ELSE
BEGIN
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
END PRINT @@TRANCOUNT;
END
GO

So now let's call it and let everything commit:

EXEC dbo.sp1 @trip = 0;

Results:

1
2
1
1
0

Now let's call it and roll back the inner procedure:

EXEC dbo.sp1 @trip = 1;

Results:

1
2
0 <-- notice that a rollback here rolled back both

Transaction count after EXECUTE indicates a mismatching number of BEGIN and
COMMIT statements. Previous count = 1, current count = 0.

0
0

Explicit transactions can be nested. This is primarily intended to support transactions in stored procedures that can be called either from a process already in a transaction or from processes that have no active transaction.

The following example shows the intended use of nested transactions. The procedure TransProc enforces its transaction regardless of the transaction mode of any process that executes it. If TransProc is called when a transaction is active, the nested transaction in TransProc is largely ignored, and its INSERT statements are committed or rolled back based on the final action taken for the outer transaction. If TransProc is executed by a process that does not have an outstanding transaction, the COMMIT TRANSACTION at the end of the procedure effectively commits the INSERT statements.

 
 
SET QUOTED_IDENTIFIER OFF;
GO
SET NOCOUNT OFF;
GO
USE AdventureWorks2008R2;
GO
CREATE TABLE TestTrans(Cola INT PRIMARY KEY,
Colb CHAR(3) NOT NULL);
GO
CREATE PROCEDURE TransProc @PriKey INT, @CharCol CHAR(3) AS
BEGIN TRANSACTION InProc
INSERT INTO TestTrans VALUES (@PriKey, @CharCol)
INSERT INTO TestTrans VALUES (@PriKey + 1, @CharCol)
COMMIT TRANSACTION InProc;
GO
/* Start a transaction and execute TransProc. */
BEGIN TRANSACTION OutOfProc;
GO
EXEC TransProc 1, 'aaa';
GO
/* Roll back the outer transaction, this will
roll back TransProc's nested transaction. */
ROLLBACK TRANSACTION OutOfProc;
GO
EXECUTE TransProc 3,'bbb';
GO
/* The following SELECT statement shows only rows 3 and 4 are
still in the table. This indicates that the commit
of the inner transaction from the first EXECUTE statement of
TransProc was overridden by the subsequent rollback. */
SELECT * FROM TestTrans;
GO

Committing inner transactions is ignored by the SQL Server Database Engine. The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction. If the outer transaction is committed, the inner nested transactions are also committed. If the outer transaction is rolled back, then all inner transactions are also rolled back, regardless of whether or not the inner transactions were individually committed.

Each call to COMMIT TRANSACTION or COMMIT WORK applies to the last executed BEGIN TRANSACTION. If the BEGIN TRANSACTION statements are nested, then a COMMIT statement applies only to the last nested transaction, which is the innermost transaction. Even if a COMMIT TRANSACTION transaction_namestatement within a nested transaction refers to the transaction name of the outer transaction, the commit applies only to the innermost transaction.

It is not legal for the transaction_name parameter of a ROLLBACK TRANSACTION statement to refer to the inner transactions of a set of named nested transactions. transaction_name can refer only to the transaction name of the outermost transaction. If a ROLLBACK TRANSACTION transaction_name statement using the name of the outer transaction is executed at any level of a set of nested transactions, all of the nested transactions are rolled back. If a ROLLBACK WORK or ROLLBACK TRANSACTION statement without a transaction_name parameter is executed at any level of a set of nested transaction, it rolls back all of the nested transactions, including the outermost transaction.

The @@TRANCOUNT function records the current transaction nesting level. Each BEGIN TRANSACTION statement increments @@TRANCOUNT by one. Each COMMIT TRANSACTION or COMMIT WORK statement decrements @@TRANCOUNT by one. A ROLLBACK WORK or a ROLLBACK TRANSACTION statement that does not have a transaction name rolls back all nested transactions and decrements @@TRANCOUNT to 0. A ROLLBACK TRANSACTION that uses the transaction name of the outermost transaction in a set of nested transactions rolls back all of the nested transactions and decrements @@TRANCOUNT to 0. When you are unsure if you are already in a transaction, SELECT @@TRANCOUNT to determine if it is 1 or more. If @@TRANCOUNT is 0, you are not in a transaction.

Reference
 
整理自
http://technet.microsoft.com/en-us/library/ms189336%28v=sql.105%29.aspx
http://stackoverflow.com/questions/9692734/sql-server-nested-transactions-in-a-stored-procedure/9692880#9692880

Nested transactions in stored procedure of SQLServer的更多相关文章

  1. java当中JDBC当中请给出一个sql server的stored procedure例子

    3.sql server的stored procedure例子: import java.sql.*;public class StoredProc0 {public static void main ...

  2. SQL Server 在多个数据库中创建同一个存储过程(Create Same Stored Procedure in All Databases)

    一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 遇到的问题(Problems) 实现代码(SQL Codes) 方法一:拼接SQL: 方法二: ...

  3. Stored Procedure 里的 WITH RECOMPILE 到底是干麻的?

    在 SQL Server 创建或修改「存储过程(stored procedure)」时,可加上 WITH RECOMPILE 选项,但多数文档或书籍都写得语焉不详,或只解释为「每次执行此存储过程时,都 ...

  4. [转]Dynamic SQL & Stored Procedure Usage in T-SQL

    转自:http://www.sqlusa.com/bestpractices/training/scripts/dynamicsql/ Dynamic SQL & Stored Procedu ...

  5. [原] XAF How to bind a stored procedure to a ListView in XAF

    First, I suggest that you review the following topic to learn how to show a custom set of objects in ...

  6. Retrieving Out Params From a Stored Procedure With Python

    http://www.rodneyoliver.com/blog/2013/08/08/retrieving-out-params-from-a-stored-procedure-with-pytho ...

  7. Modify a Stored Procedure using SQL Server Management Studio

    In Object Explorer, connect to an instance of Database Engine and then expand that instance. Expand  ...

  8. Difference between Stored Procedure and Function in SQL Server

    Stored Procedures are pre-compile objects which are compiled for first time and its compiled format ...

  9. Oracle Stored Procedure demo

    1.how to find invalid status stored procedure and recompile them? SELECT OBJECT_NAME , status FROM u ...

随机推荐

  1. Struts1与Struts2的12点区别

    Struts1与Struts2的12点区别  1) 在Action实现类方面的对比:Struts 1要求Action类继承一个抽象基类:Struts 1的一个具体问题是使用抽象类编程而不是接口.Str ...

  2. java截取图片部分尺寸

    package util; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; i ...

  3. NSJSONSerialization介绍

      ios5中apple增加了解析JSON的api——NSJSONSerialization.网上已经有人做过测试,NSJSONSerialization在效率上完胜SBJSON.TouchJSON. ...

  4. thinkphp模型没继承model报的错

    Call to undefined method RoleModel::query() 错误位置 FILE: H:\www\tpsmarty\shop\Lib\Model\RoleModel.clas ...

  5. 活跃天数计算用户等级模仿QQ的升级方式

    QQ等级的算法:设当前等级为N,达到当前等级最少需要的活跃天数为D,当前活跃天数为Dc,升级剩余天数为Dr,则: 从而推出: 好了,引述完成,懒得写字了,贴出代码: 复制内容到剪贴板 代码: < ...

  6. thinkphp四种url访问方式详解

    本文实例分析了thinkphp的四种url访问方式.分享给大家供大家参考.具体分析如下: 一.什么是MVC thinkphp的MVC模式非常灵活,即使只有三个中和一个也可以运行. M -Model 编 ...

  7. Asp.net 服务器Application,Session,Cookie,ViewState和Cache区别

    2.8 Context 的使用Context 对象包含与当前页面相关的信息,提供对整个上下文的访问,包括请求.响应.以及上文中的Session 和Application 等信息.可以使用此对象在网页之 ...

  8. RedirectResult,RedirectToRoute

    RedirectResult:运行重新导向到其他网址,在RedirectResult的内部,基本上还是以Response.Redirect方法响应HTTP 302暂时导向. eg: public Ac ...

  9. Delphi深度探索-CodeSite应用指南

    Delphi深度探索-CodeSite应用指南 Delphi虽然为我们提供极其强大的调试功能,查找Bug仍然是一项艰巨的工作,通常我们写代码和调试代码的所消耗的时间是大致相同的,甚至有可能更多.为了减 ...

  10. php + ajax + html 简单跨域问题

    XMLHttpRequest cannot load http://localhost:8080/abc/index.php. No 'Access-Control-Allow-Origin' hea ...