Today morning, one of my colleague came to my desk with an interesting question. “Is there any way to read SQL T-Log file?” I did not have idea about it I searched on google and I found an un-documented functions which is used to read T-Log file. Using this function, we can get list of all transaction performed on database. Function name is fn_dblog() (Formally known as DBCC command).

The fn_dblog() will accept two parameters:
  1. Starting log sequence number (LSN). We can specify null, it will return everything from start of log.
  2. Ending log sequence number (LSN). We can specify null, it will return everything to end of the log.

Demo Code:

01.Create Database SampleDatabase
03.use SampleDatabase
05.Create Table Inventory
07.    ID Int identity (1,1),
08.    ProductName varchar(100),
09.    Quantity int
11.Insert into Inventory(ProductName,Quantity) values ('Soap',10),('Tooth Paste',20)

I have created new database named “SampleDatabase”. Then I created new table called “Inventory” and insert some values in table.

Now I want to get all the transaction (Insert, Update, Delete, create Table) performed by on database. So, I can run below query.

01.SELECT [Current LSN]
02.      ,[Operation]
03.      ,[Transaction ID]
04.      ,AllocUnitName
05.      ,[Transaction Name]
06.      ,[Transaction SID] 
07.      , SUSER_SNAME([Transaction SID]) AS DBUserName
08.      ,[Begin Time
09.      ,[Lock Information]
10.FROM fn_dblog(NULL, NULL)
11.WHERE SUSER_SNAME([Transaction SID]) = 'Nisarg-PC/Nisarg'
12.AND   [Transaction Name] in ('CREATE TABLE','Insert','Delete')

In above code, you can see I used the fn_dblog function in the “FROM” clause. I also used the “WHERE” predicate to return only transaction log rows that involved a CREATE TABLE, INSERT and/or DELETE transaction created by database user Nisarg-PC\Nisarg.

This function is undocumented and you should use it with caution.