從網路找到改良的,直接查不用開Sql Profiler
加入可指定資料庫的改良
SELECT TOP 100 execution_count, total_worker_time, last_worker_time, max_worker_time, min_worker_time, CONVERT(INT, att.value) AS dbid, DB_NAME(CONVERT(INT, att.value)) as dbname ,SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,((CASE statement_end_offset WHEN -1 THEN DATALENGTH(st.text)ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) as statement_text
FROM sys.dm_exec_query_stats as qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as st
CROSS APPLY sys.dm_exec_plan_attributes(qs.plan_handle) att
WHERE att.attribute='dbid' and DB_NAME(CONVERT(INT, att.value)) = 'P9'
ORDER BY execution_count DESC
以執行次數排序,可檢查爆量的Sql
Where statement_start_offset =0 測起來可以篩掉系統的Query,如:AspNet_SqlCache
SELECT TOP 10 execution_count, total_worker_time, last_worker_time, max_worker_time, min_worker_time, SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,((CASE statement_end_offset WHEN -1 THEN DATALENGTH(st.text)ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) as statement_text
FROM sys.dm_exec_query_stats as qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as st
WHERE statement_start_offset = 0
ORDER BY execution_count DESC
以總執行時間排序,檢查寫耗時的Sql
SELECT TOP 10 total_worker_time, last_worker_time, max_worker_time, min_worker_time, SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,((CASE statement_end_offset WHEN -1 THEN DATALENGTH(st.text)ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) as statement_text
FROM sys.dm_exec_query_stats as qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as st
ORDER BY max_worker_time DESC
結果如下