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 (http://blog.SQLAuthority.com)

About these ads

6 thoughts on “SQL SERVER – Get Latest SQL Query for Sessions – DMV

  1. 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.

  2. Pingback: SQLAuthority News – Monthly Roundup of Best SQL Posts Journey to SQL Authority with Pinal Dave

  3. Pingback: SQL SERVER – Weekly Series – Memory Lane – #028 | SQL Server Journey with SQL Authority

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s