Thursday, April 03, 2008

Vadivel's blog: How to find out recently run queries in SQL Server 2005?

A realtime view of your SQL Server 2005 queries.

How to find out recently run queries in SQL Server 2005?

Prior to SQL Server 2005 if we want to find out the list of recently run queries we need to depend on SQL Profiler.
Now in SQL Server 2005 the life has become more easier(!). With the help of of an Dynamic Management Views (DMV) and a table valued function we can list the required result.
Points to note:
1. sys.dm_exec_query_stats -- This DMV returns aggregate performance statistics for cached query plans. The view contains one row per query statement within the cached plan, and the lifetime of the rows are tied to the plan itself. When a plan is removed from the cache, the corresponding rows are eliminated from this view.
2. sys.dm_exec_sql_text -- This table valued function returns the text of the SQL batch that is identified by the specified sql_handle
Solution:
Select
dmStats.last_execution_time as 'Last Executed Time',
dmText.text as 'Executed Query'
from
sys.dm_exec_query_stats as dmStats
Cross apply
sys.dm_exec_sql_text(dmStats.sql_handle) as dmText
Order By
dmStats.last_execution_time desc

Vadivel's blog: How to find out recently run queries in SQL Server 2005?

No comments: