Microsoft SQL Server 2005 提供了一些工具來監控數據庫。方法之一是動態管理視圖。動態管理視圖 (DMV) 和動態管理函數 (DMF) 返回的服務器狀態信息可用於監控服務器實例的運行狀況、診斷問題和優化性能。
常規服務器動態管理對象包括:
dm_db_*:數據庫和數據庫對象
dm_exec_*:執行用戶代碼和關聯的連接
dm_os_*:內存、鎖定和時間安排
dm_tran_*:事務和隔離
dm_io_*:網絡和磁盤的輸入/輸出
此部分介紹為監控 SQL Server 運行狀況而針對這些動態管理視圖和函數運行的一些常用查詢。
摘錄部分精彩SQL如下:
下面的查詢顯示 CPU 平均占用率最高的前 50 個 SQL 語句。
SELECT TOP 50
total_worker_time/execution_count AS [Avg CPU Time],
(SELECT SUBSTRING(text,statement_start_offset/2,(CASE WHEN statement_end_offset = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE statement_end_offset end -statement_start_offset)/2) FROM sys.dm_exec_sql_text(sql_handle)) AS query_text, *
FROM sys.dm_exec_query_stats
ORDER BY [Avg CPU Time] DESC
SELECT TOP 50
total_worker_time/execution_count AS [Avg CPU Time],
(SELECT SUBSTRING(text,statement_start_offset/2,(CASE WHEN statement_end_offset = -1 then LEN(CONVERT(nvarchar(max), text)) * 2 ELSE statement_end_offset end -statement_start_offset)/2) FROM sys.dm_exec_sql_text(sql_handle)) AS query_text, *
FROM sys.dm_exec_query_stats
ORDER BY [Avg CPU Time] DESC
下面的查詢顯示一些可能占用大量 CPU 使用率的運算符(例如 ‘%Hash Match%’、‘%Sort%’)以找出可疑對象。
select *
from
sys.dm_exec_cached_plans
cross apply sys.dm_exec_query_plan(plan_handle)
where
cast (query_plan as nvarchar ( max )) like ' %Sort% '
or cast (query_plan as nvarchar ( max )) like ' %Hash Match% '
select *
from
sys.dm_exec_cached_plans
cross apply sys.dm_exec_query_plan(plan_handle)
where
cast (query_plan as nvarchar ( max )) like ' %Sort% '
or cast (query_plan as nvarchar ( max )) like ' %Hash Match% '
運行下面的 DMV 查詢以查看 CPU、計劃程序內存和緩沖池信息。
select
cpu_count,
hyperthread_ratio,
scheduler_count,
physical_memory_in_bytes / 1024 / 1024 as physical_memory_mb,
virtual_memory_in_bytes / 1024 / 1024 as virtual_memory_mb,
bpool_committed * 8 / 1024 as bpool_committed_mb,
bpool_commit_target * 8 / 1024 as bpool_target_mb,
bpool_visible * 8 / 1024 as bpool_visible_mb
from sys.dm_os_sys_info
select
cpu_count,
hyperthread_ratio,
scheduler_count,
physical_memory_in_bytes / 1024 / 1024 as physical_memory_mb,
virtual_memory_in_bytes / 1024 / 1024 as virtual_memory_mb,
bpool_committed * 8 / 1024 as bpool_committed_mb,
bpool_commit_target * 8 / 1024 as bpool_target_mb,
bpool_visible * 8 / 1024 as bpool_visible_mb
from sys.dm_os_sys_info
select top 25
sql_text. text ,
sql_handle,
plan_generation_num,
execution_count,
dbid,
objectid
from sys.dm_exec_query_stats a
cross apply sys.dm_exec_sql_text(sql_handle) as sql_text
where plan_generation_num > 1
order by plan_generation_num desc
select top 25
sql_text. text ,
sql_handle,
plan_generation_num,
execution_count,
dbid,
objectid
from sys.dm_exec_query_stats a
cross apply sys.dm_exec_sql_text(sql_handle) as sql_text
where plan_generation_num > 1
order by plan_generation_num desc