Search code examples
sqlt-sqlstored-proceduressystem-stored-procedures

retrieve most recently executed SQL command (T-SQL)


One of my developers working on a trigger-based logging facility in SQL Server 2008 asked me if there was a command to retrieve the most recently executed SQL command within T-SQL. I thought there was a system stored procedure for just such a function, but it's possible I'm thinking of another product from a prior decade... online searches yielded us no results.

Does anyone have information on anything of the sort?


Solution

  • sure try this :

    SELECT
    DMExQryStats.last_execution_time AS [Executed At],
    DMExSQLTxt.text AS [Query]
    FROM
    sys.dm_exec_query_stats AS DMExQryStats
    CROSS APPLY
    sys.dm_exec_sql_text(DMExQryStats.sql_handle) AS DMExSQLTxt
    ORDER BY
    DMExQryStats.last_execution_time DESC
    

    it will returns recently executed queries along with the date and time at which they were executed