SQL Server性能优化的一些常用脚本,适用于SQL Server 2008,更高的版本某些系统表的字段有所不同,建议参考MSDN。
- 死锁相关
/****************************************
1. 查询当前DB的锁分配情况
Phoenix.Feng 2012-12-01
****************************************/
SELECT request_session_id, resource_type, request_status, request_mode, resource_description, OBJECT_NAME(p.object_id) as OBJECT_NAME, p.index_id
FROM sys.dm_tran_locks t left join sys.partitions p ON t.resource_associated_entity_id = p.hobt_id
ORDER BY request_session_id, resource_type /****************************************
2. 查询当前数据库实例的死锁日志
Phoenix.Feng 2012-12-01
****************************************/
DECLARE @data xml =
CONVERT
(
xml,
(
SELECT TOP (1)
dxst.target_data
FROM sys.dm_xe_sessions AS dxs
JOIN sys.dm_xe_session_targets AS dxst ON
dxst.event_session_address = dxs.[address]
WHERE
dxs.name = N'system_health'
AND dxst.target_name = N'ring_buffer'
)
)
SELECT XEventData.XEvent.value('(data/value)[1]', 'varchar(max)') AS Record
FROM @data.nodes ('./RingBufferTarget/event[@name eq "xml_deadlock_report"]') AS XEventData (XEvent)
WHERE XEventData.XEvent.value('@name', 'varchar(max)') = 'xml_deadlock_report'; /****************************************
3. 查询当前DB的阻塞情况1
Phoenix.Feng 2012-12-01
****************************************/
SELECT
blocked_query.session_id AS blocked_session_id,
blocking_query.session_id AS blocking_session_id,
blocking_sql_text.text AS blocking_sql_text,
blocked_sql_text.text AS blocked_sql_text,
waits.wait_type AS blocking_resource,
blocked_query.command AS blocked_command,
blocking_query.command AS blocking_command,
blocked_query.wait_type AS blocked_wait_type,
blocked_query.wait_time AS blocked_wait_time,
blocking_query.total_elapsed_time AS blocking_elapsed_time, GETDATE()
FROM sys.dm_exec_requests blocked_query JOIN sys.dm_exec_requests blocking_query ON blocked_query.blocking_session_id = blocking_query.session_id
CROSS APPLY
(SELECT * FROM sys.dm_exec_sql_text(blocking_query.sql_handle)) blocking_sql_text
CROSS APPLY (SELECT * FROM sys.dm_exec_sql_text(blocked_query.sql_handle)) blocked_sql_text JOIN sys.dm_os_waiting_tasks waits ON
waits.session_id = blocking_query.session_id /****************************************
3. 查询当前DB的阻塞情况2
Phoenix.Feng 2013-04-08
****************************************/
SELECT request_session_id, resource_type, request_status,
request_mode, resource_description,
(CASE resource_type WHEN 'OBJECT' THEN OBJECT_NAME(t.resource_associated_entity_id)
ELSE OBJECT_NAME(p.object_id) END) OBJECT_NAME,
p.index_id
FROM sys.dm_tran_locks t left join sys.partitions p
ON t.resource_associated_entity_id = p.hobt_id
ORDER BY request_session_id, resource_type /****************************************
4. 查询键锁锁定的键
Phoenix.Feng 2012-12-01
****************************************/
SELECT *, %%lockres%% AS [key] FROM friend.FriendInteractions WITH (index = PK_FriendInteractions) WHERE %%lockres%% IN('(1d4222ef989f)') /****************************************
5. 查询对象的架构名和对象名
Phoenix.Feng 2012-12-01
****************************************/
SELECT SCHEMA_NAME(schema_id) [schema_name], OBJECT_NAME(object_id) [object_name] from sys.objects where object_id = 924582382
- 索引相关
--1. 丢失的索引
SELECT OBJECT_NAME(object_id) object_name, mid.equality_columns, mid.included_columns, mid.inequality_columns, avg_user_impact
FROM sys.dm_db_missing_index_group_stats AS migs
INNER JOIN sys.dm_db_missing_index_groups AS mig
ON (migs.group_handle = mig.index_group_handle)
INNER JOIN sys.dm_db_missing_index_details AS mid
ON (mig.index_handle = mid.index_handle)
WHERE database_id = 9 and migs.group_handle in(SELECT top 10000 group_handle
FROM sys.dm_db_missing_index_group_stats
ORDER BY avg_total_user_cost * avg_user_impact * (user_seeks + user_scans)DESC); --2. 丢失的索引(建议脚本)
PRINT 'Missing Indexes: '
PRINT 'The "improvement_measure" column is an indicator of the (estimated) improvement that might '
PRINT 'be seen if the index was created. This is a unitless number, and has meaning only relative '
PRINT 'the same number for other indexes. The measure is a combination of the avg_total_user_cost, '
PRINT 'avg_user_impact, user_seeks, and user_scans columns in sys.dm_db_missing_index_group_stats.'
PRINT ''
PRINT '-- Missing Indexes --'
SELECT CONVERT (VARCHAR, getdate(), 126) AS runtime,
mig.index_group_handle, mid.index_handle,
CONVERT (decimal(28,1), migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans)) AS improvement_measure,
'CREATE INDEX missing_index_' + CONVERT (varchar, mig.index_group_handle) + '_' + CONVERT (varchar, mid.index_handle)
+ ' ON ' + mid.statement
+ ' (' + ISNULL (mid.equality_columns,'')
+ CASE WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL THEN ',' ELSE '' END + ISNULL (mid.inequality_columns, '')
+ ')'
+ ISNULL (' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement,
migs.*, mid.database_id, mid.[object_id]
FROM sys.dm_db_missing_index_groups mig
INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
WHERE CONVERT (decimal (28,1), migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans)) > 10 and database_id = 9
ORDER BY migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) DESC
PRINT ''
GO --3. 索引碎片
SELECT database_id, object_id, index_id, index_type_desc, alloc_unit_type_desc, avg_fragmentation_in_percent, fragment_count, avg_fragment_size_in_pages, page_count FROM sys.dm_db_index_physical_stats (9, NULL, NULL, NULL, NULL) WHERE avg_fragmentation_in_percent > 10 ORDER BY avg_fragmentation_in_percent
DESC --4. 未使用过的索引
SELECT SCHEMA_NAME(t.schema_id) 'schema', i.type_desc, object_name(i.object_id) tableName, i.Name indexName
FROM sys.indexes i join ProjectA_GameDB_Internal.sys.tables t ON(i.object_id = t.object_id)
WHERE i.index_id NOT IN (SELECT s.index_id FROM sys.dm_db_index_usage_stats s WHERE s.object_id = i.object_id and
i.index_id = s.index_id and database_id = DB_ID('ProjectA_GameDB_Internal'))
ORDER BY object_name(i.object_id) ASC --5. 不合理的索引
SELECT OBJECT_NAME(A.object_id) object_name, B.name, ((select name from sys.columns where object_id = A.object_id and column_id = (select TOP 1 index_column_id from sys.index_columns where object_id = A.object_id and index_id = B.index_id))) AS column_name, b.index_id, B.type_desc, user_seeks, user_scans, user_lookups, user_updates FROM sys.dm_db_index_usage_stats A JOIN sys.indexes B ON(A.object_id = b.object_id AND A.index_id = B.index_id)
--JOIN SYS.index_columns C ON(B.object_id = C.object_id AND B.index_id = C.index_id)
WHERE A.object_id in(SELECT object_id FROM sys.objects WHERE TYPE = 'U')
and user_seeks = 0
ORDER BY A.user_seeks
- 监控相关
/****************************************
1. 按 CPU 平均占用率排序,查询 SQL 语句。
Phoenix.Feng 2013-03-20
****************************************/
WITH Result AS(
SELECT
(SELECT dbid FROM sys.dm_exec_sql_text(sql_handle)) AS [DB_ID],
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
) SELECT [Avg CPU Time] / 1000, * FROM Result WHERE [DB_ID] = 312 ORDER BY [Avg CPU Time] DESC /****************************************
2. 显示一些可能占用大量 CPU 使用率的运算符(例如 ‘%Hash Match%’、‘%Sort%’)以找出可疑对象。
Phoenix.Feng 2013-03-20
****************************************/
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%' /****************************************
3. 查询以查看 CPU、计划程序内存和缓冲池信息。
Phoenix.Feng 2013-03-20
****************************************/
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 /****************************************
5. 查询可用于查找可生成最多 I/O 的前五个请求。
Phoenix.Feng 2013-03-20
****************************************/
SELECT TOP 5
(total_logical_reads / execution_count) AS avg_logical_reads,
(total_logical_writes / execution_count) AS avg_logical_writes,
(total_physical_reads / execution_count) AS avg_phys_reads,
Execution_count, statement_start_offset AS stmt_start_offset,
sql_handle,
plan_handle
FROM sys.dm_exec_query_stats
ORDER BY (total_logical_reads + total_logical_writes) Desc /****************************************
6. 查询以查看 CPU、计划程序内存和缓冲池信息。
Phoenix.Feng 2013-03-20
****************************************/
--Memory columns of sys.dm_os_sys_info
SELECT
--Amount of physical memory on server
physical_memory_in_bytes
--Amount of physical memory available to the process in user mode
--Should be 2GB unless /3GB used
,virtual_memory_in_bytes
--Committed physical memory in buffer pool
--Does not include MemToLeave memory area
,bpool_committed AS 'Number of 8KB buffers in buffer pool'
, bpool_commit_target AS 'Number of 8KB buffers needed by the buffer pool'
,CASE
WHEN bpool_commit_target > bpool_committed THEN 'Extra memory needed
from OS for Buffer Pool'
WHEN bpool_commit_target < bpool_committed THEN 'Memory may be
released from Buffer Pool to OS'
END AS 'Status of Dynamic Memory' , bpool_visible AS 'Number of 8KB Buffers in Buffer Pool that are directly
accessible in the processes VAS.' /* When AWE is not used. When memory target reached, the value will be the
same as bpool_committed
When AWE is used on 32-bit. This value represents the size of the AWE
mapping window used to
access physical memory allocated by the buffer pool. Since the size of the
AWE mapping window
is bound by the process VAS the value of this column will be smaller than
the value of bpool_committed.
If the value of this column becomes too low, you may receive out of memory
errors.
*/
FROM sys.dm_os_sys_info
- 清除索引碎片
CREATE PROCEDURE [system].[up_ClearIndexFrag]
AS
SET NOCOUNT ON;
DECLARE @objectid int;
DECLARE @indexid int;
DECLARE @partitioncount bigint;
DECLARE @schemaname nvarchar(130);
DECLARE @objectname nvarchar(130);
DECLARE @indexname nvarchar(130);
DECLARE @partitionnum bigint;
DECLARE @partitions bigint;
DECLARE @frag float;
DECLARE @command nvarchar(4000);
SELECT
object_id AS objectid,
index_id AS indexid,
partition_number AS partitionnum,
avg_fragmentation_in_percent AS frag
INTO #work_to_do
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED')
WHERE avg_fragmentation_in_percent > 40.0 AND index_id > 0 AND page_count > 10; DECLARE partitions CURSOR FOR SELECT * FROM #work_to_do; OPEN partitions; WHILE (1=1)
BEGIN;
FETCH NEXT
FROM partitions
INTO @objectid, @indexid, @partitionnum, @frag;
IF @@FETCH_STATUS < 0 BREAK;
SELECT @objectname = QUOTENAME(o.name), @schemaname = QUOTENAME(s.name)
FROM sys.objects AS o
JOIN sys.schemas as s ON s.schema_id = o.schema_id
WHERE o.object_id = @objectid;
SELECT @indexname = QUOTENAME(name)
FROM sys.indexes
WHERE object_id = @objectid AND index_id = @indexid;
SELECT @partitioncount = count (*)
FROM sys.partitions
WHERE object_id = @objectid AND index_id = @indexid;
IF @frag >= 30.0
SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @objectname + N' REBUILD';
IF @partitioncount > 1
SET @command = @command + N' PARTITION=' + CAST(@partitionnum AS nvarchar(10));
EXEC (@command);
PRINT N'Executed: ' + @command;
END CLOSE partitions;
DEALLOCATE partitions;
DROP TABLE #work_to_do;
GO