SQL Server – How to Find Time of an Insertion

datetimesql server

I am using:

SELECT top 10 *
FROM sys.fn_dblog(NULL,NULL)
WHERE Operation IN ('LOP_INSERT_ROWS') AND AllocUnitName = 'dbo.HeartBeat'

This return some rows, but I cannot tell which column contains a date and time.

I want to know WHEN the record was inserted. The inserted record contains a TIMESTAMP provided by the user BUT I want to see if the user is actually inserting the record at the time given by TIMESTAMP

Best Answer

You can find INSERT time using fn_dblog() function looking at [Begin Time] column of the corresponding begin transaction (with INSERT name) in the result set.

The tricky thing here is that the column AllocUnitName of this row (LOP_BEGIN_XACT) is NULL, while [Begin Time] is NULL for rows corrensponding to LOP_INSERT_ROWS where AllocUnitNamecan be found.

So you should use the fact that the transaction is the same, and once you individuated the rows of interest using your query that filters for 'LOP_INSERT_ROWS', you should use [Transaction ID] to find the time:

select  [Begin Time]
from sys.fn_dblog(NULL,NULL)
where [Transaction ID] = '0000:cb5f3b8a' -- put here the [Transaction ID] found using your query
and Operation = 'LOP_BEGIN_XACT';

Here is the picture illustrating what I'm talking about:

enter image description here