Sql-server – Get the last statement execution date on an MSSQL Database

logsql servertransaction-log

In an MSSQL Database, I am trying to know when was the last statement executed for that database.

So, is there any log that I can use to see the required activity records (could be the Transaction Log, but I am not sure how to get dates from it)?

Best Answer

You will want to use the sys.dm_exec_query_stats dmv. If you simply want to see the last statement that was executed, this should get you started (note: you need to execute this in the context of your database e.g. by using the USE <db_name> command):

SELECT
deqs.creation_time
,   deqs.last_execution_time
,   dest.text
,   SUBSTRING(dest.text, 
        (deqs.statement_start_offset/2) + 1,
            ((CASE statement_end_offset 
                WHEN -1 
                    THEN DATALENGTH(dest.text)
                ELSE deqs.statement_end_offset
                END 
                    - (deqs.statement_start_offset/2) + 1)))
AS statement_text
, deqp.query_plan
FROM 
sys.dm_exec_query_stats AS deqs
CROSS APPLY 
sys.dm_exec_sql_text(deqs.sql_handle) AS dest
CROSS APPLY 
sys.dm_exec_query_plan(deqs.plan_handle) AS deqp
WHERE deqs.last_execution_time = (SELECT MAX(last_execution_time)
                                FROM sys.dm_exec_query_stats)