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)












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.
[...] SQL SERVER – Get Latest SQL Query for Sessions – DMV SQL SERVER – Find Most Expensive Queries Using DMV SQL SERVER – List All the DMV and DMF on Server [...]
ya it is gr8 and this w’ll help me alot,thanks 4 giving such as gr8 article.
[…] Get Latest SQL Query for Sessions – DMV A straight to script blog which is my favorite as well. […]
Hi pinal,
thanks for such info its valueble
Hi pinal,
could u please explain about the use of cross apply