Question

I would like to know the last 1008 queries run in my systems and with this intent I have put this query together:

-- get the last 1008 queries run
SELECT top 1008
execquery.last_execution_time AS [Date Time], 
Database_Name=DB_NAME (execsql.dbid),
execsql.text AS [Script] 
FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
ORDER BY execquery.last_execution_time DESC

and this is currently giving me the following result in one of my servers:

enter image description here

Looking at the picture, it seems that the same piece of code appear several times, within the same millisecond.

I modified the script and added a group by, however, the cost to run this query became too expensive.

-- get the last 1008 queries run
SELECT top 1008
execquery.last_execution_time AS [Date Time], 
Database_Name=DB_NAME (execsql.dbid),
execsql.text AS [Script] 
FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
GROUP BY execquery.last_execution_time, execsql.dbid,execsql.text
ORDER BY execquery.last_execution_time DESC

What could be a way to prevent the dupplicates to show up and at the same time not to kill my server when I try to run it?

Was it helpful?

Solution

You're getting multiple queries from within the same stored procedure but because you're just looking at execsql.text you're getting the whole body of the procedure. If you want to know the individual queries you need to extract those. (The solution is definitely not to try to group by the entire procedure body.) Try this query:

SELECT TOP (1008)
  execquery.last_execution_time AS [Date Time], 
  Database_Name = DB_NAME (execsql.dbid),
  [Script] = SUBSTRING(execsql.text, (execquery.statement_start_offset/2) + 1,
    (( CASE execquery.statement_end_offset
        WHEN -1 THEN DATALENGTH(execsql.text)
        ELSE execquery.statement_end_offset END 
            - execquery.statement_start_offset)/2) + 2)
FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
ORDER BY execquery.last_execution_time DESC;
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top