Saturday, March 01, 2008

Get the Last Run Query in SQL Server 2005

Have you ever run an update or delete query by mistake and you need to roll back or at least want to know the last run query to fix the problem? The following SQL statement can help in that.

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC
This will retrieve the last run queries with its execution time.