SQL SERVER – Get Latest SQL Query for Sessions – DMV

In recent SQL Training I was asked, how can one figure out what was the last SQL Statement executed in sessions.

The query for this is very simple. It uses two DMVs and created following quick script for the same.

SELECT session_id, TEXT
FROM
sys.dm_exec_connections
CROSS APPLY sys.dm_exec_sql_text(most_recent_sql_handle) AS ST

While working with DMVs if you ever find any DMV has column with name sql_handle you can right away join that DMV with another DMV sys.dm_exec_sql_text and can get the text of the SQL statement.

Reference: Pinal Dave (https://blog.sqlauthority.com)

,
Previous Post
SQLAuthority News – Microsoft SQL Server 2005/2008 Query Optimization and Performance Tuning Training
Next Post
SQLAuthority News – Wireless Router Security and Attached Devices – Complex Password

Related Posts

6 Comments. Leave new

  • Sushil Nepal
    May 5, 2010 7:03 pm

    Thanks for the short and nice reminder. I think there is typo in the blog. sys.dm_exec_sql_text is DMF and not the DMV.

    Reply
  • Kuldeep Mathur
    May 31, 2010 12:30 pm

    ya it is gr8 and this w’ll help me alot,thanks 4 giving such as gr8 article.

    Reply

Leave a Reply

Menu