Published on

April 6, 2011

Understanding Transaction Logs in SQL Server

Have you ever wondered how SQL Server keeps track of transactions and their impact on the transaction log file? In this article, we will explore a Dynamic Management View (DMV) that provides details about the effect of a transaction on the transaction log file.

First, let’s take a look at the DMV script:

SELECT transaction_id,
       DB_NAME(database_id) AS DatabaseName,
       database_transaction_begin_time AS TransactionBegin,
       CASE database_transaction_type
           WHEN 1 THEN 'Read/Write'
           WHEN 2 THEN 'Read only'
           WHEN 3 THEN 'System'
       END AS TransactionType,
       CASE database_transaction_state
           WHEN 1 THEN 'Not Initialized'
           WHEN 3 THEN 'Transaction No Log'
           WHEN 4 THEN 'Transaction with Log'
           WHEN 5 THEN 'Transaction Prepared'
           WHEN 10 THEN 'Committed'
           WHEN 11 THEN 'Rolled Back'
           WHEN 12 THEN 'Committed and Log Generated'
       END AS TransactionState,
       database_transaction_log_record_count AS LogRecordCount,
       database_transaction_log_bytes_used AS LogBytesUsed,
       database_transaction_log_bytes_reserved AS LogBytesReserved
FROM sys.dm_tran_database_transactions
WHERE transaction_id > 1000
	

In the above script, we are querying the sys.dm_tran_database_transactions DMV to retrieve information about transactions that have a transaction ID greater than 1000. These transactions are user transactions.

Let’s test the above query by running the following transaction:

BEGIN TRANSACTION
UPDATE HumanResources.Department
SET ModifiedDate = ModifiedDate + 1
--ROLLBACK
	

Note that if you do not run the ROLLBACK statement, the transaction will not be completed.

When you run the DMV script, it will provide you with the following output:

Transaction IDDatabase NameTransaction Begin TimeTransaction TypeTransaction StateLog Record CountLog Bytes UsedLog Bytes Reserved

From the output, you can clearly see various information about the transaction, such as the transaction start time, transaction type, and the number of bytes used and reserved in the transaction log.

Understanding the impact of transactions on the transaction log file is crucial for database administrators and developers. It helps in monitoring and optimizing the performance of SQL Server databases.

That’s it for this article! We hope you found it helpful in understanding how to retrieve transaction log details using the sys.dm_tran_database_transactions DMV. Stay tuned for more SQL Server tips and tricks!

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.