Saturday, May 15, 2010

SQL optimisation : How to find out the most used T-SQL queries ?

Provided you have the required autorisations to run those SCRIPTS, here are handfull T-SQL query to find out the most used queries within the SQL Server's cache (since the last reboot).

Thank you Christian Robert !
SELECT
      LEFT(tx.text, 50) AS 'Query',
      SUM(qs.total_logical_reads) 'Logical Reads'
FROM
      sys.dm_exec_cached_plans AS cp
      JOIN sys.dm_exec_query_stats AS qs
      ON cp.plan_handle =qs.plan_handle
      CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) AS tx
--WHERE qs.max_logical_reads> 0 And (0. + qs.min_logical_reads) / (0. + qs.max_logical_reads ) > 0.1
GROUP BY LEFT(tx.text, 50)
ORDER BY 2 DESC


Another version by pinaldave :
SELECT TOP 10
    qt.TEXT AS 'SP Name',
    qs.execution_count AS 'Execution Count',
    qs.total_worker_time/qs.execution_count AS 'AvgWorkerTime',
    qs.total_worker_time AS 'TotalWorkerTime',
    qs.total_physical_reads AS 'PhysicalReads',
    qs.creation_time 'CreationTime',
    qs.execution_count/DATEDIFF(Second, qs.creation_time, GETDATE()) AS 'Calls/Second'
FROM
    sys.dm_exec_query_stats AS qs
    CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE
    qt.dbid = (
        SELECT dbid
        FROM sys.sysdatabases
        WHERE name = 'AdventureWorks')
ORDER BY
    qs.total_physical_reads DESC


=================

SET STATISTICS IO ON;

1 comment:

  1. Also varaiant also working on Azure SQL Database
    http://channel9.msdn.com/Events/Build/2014/3-630
    @23 min
    Vincent Thavonekham

    ReplyDelete

Note: Only a member of this blog may post a comment.