Published on

March 12, 2015

Understanding Nested Transactions in SQL Server

SQL Server is a powerful database system that offers a wide range of features and functionalities. One of the concepts that can be confusing for beginners is nested transactions. In this blog post, we will explore the concept of nested transactions and how they work in SQL Server.

Before we dive into the details, let’s first understand what a nested transaction is. A nested transaction is a transaction that is created within another transaction. It allows you to perform a series of operations within a parent transaction, while still maintaining the ability to roll back the entire set of operations if needed.

Let’s take a look at an example to better understand how nested transactions work in SQL Server. We will create a simple script that demonstrates the concept:

USE MASTER;
GO

CREATE DATABASE TransactionsDemo;
GO

USE TransactionsDemo;
GO

CREATE TABLE tbl_SQLAuth (Col1 INT);
GO

SET NOCOUNT ON;
GO

BEGIN TRAN OuterTransaction;
GO

INSERT INTO tbl_SQLAuth VALUES (1);
GO

BEGIN TRAN InnerTransaction;
GO

INSERT INTO tbl_SQLAuth VALUES (2);
GO

ROLLBACK TRAN OuterTransaction;
GO

In this script, we first create a database called “TransactionsDemo” and a table called “tbl_SQLAuth”. We then begin an outer transaction and insert a row into the table. Next, we begin a nested transaction and insert another row into the table. Finally, we roll back the outer transaction.

Now, let’s take a look at the transaction log records using the undocumented command “fn_dblog()”:

SELECT Operation, [Transaction ID], Description
FROM fn_dblog(NULL, NULL);

When we check the transaction log records, we can see that both the rows inserted in the outer and nested transactions have the same transaction ID. This means that SQL Server does not create a new transaction for nested transactions.

If we try to roll back the outer transaction, both the rows will be rolled back using a compensating record in the transaction log. This ensures that the changes made in the nested transaction are also rolled back.

Understanding nested transactions can be a bit challenging, but it is an important concept to grasp when working with SQL Server. By knowing how nested transactions work, you can effectively manage and control the flow of your transactions.

I hope this blog post has helped you gain a better understanding of nested transactions in SQL Server. If you have any questions or have any other topics you would like me to cover, please let me know. Happy learning!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.