SQL Server优化相关的工具脚本
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
SQL Server优化相关的工具脚本的更多相关文章
- SQL Server 优化器特性导致的内存授予相关BUG
我们有时会遇到一些坑,要不填平,要不绕过.这里为大家介绍一个相关SQL Server优化器方面的特性导致内存授予的相关BUG,及相关解决方式,也顺便回答下邹建同学的相关疑问. 问题描述 一个简单的查询 ...
- 安装 SQL Server 2008 和管理工具 SQL Server 2008 management studio 及相关问题解决
Sql Server 2008 问题小总结 http://www.lihengyu.com/blog/4877.html 安装 SQL Server 2008 和管理工具 SQL Server 200 ...
- SQL server经典电子书、工具和视频教程汇总
SQL server经典电子书.工具和视频教程汇总 SQL server经典电子书.工具和视频教程汇总 SQL Server是高校计算机专业的一门必修课程,同时众多企业采用SQL Server作为数据 ...
- [SQL Server优化]善用系统监视器,确定系统瓶颈
原文:[SQL Server优化]善用系统监视器,确定系统瓶颈 来自: http://hi.baidu.com/solorez/blog/item/f82038fa0e71b78d9e51468c.h ...
- 深入SQL Server优化【推荐】
深入sql server优化,MSSQL优化,T-SQL优化,查询优化 十步优化SQL Server 中的数据访问故事开篇:你和你的团队经过不懈努力,终于使网站成功上线,刚开始时,注册用户较少,网站性 ...
- SQL Server优化的方法
SQL Server优化的方法<一> 查询速度慢的原因很多,常见如下几种: 1.没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) 2.I/O吞吐量小,形成了 ...
- sql的优化相关问题
这篇文章写的真心不错,值得仔细拜读,所以将其转载过来了. 一. 分析阶段 一 般来说,在系统分析阶段往往有太多需要关注的地方,系统各种功能性.可用性.可靠性.安全性需求往往吸引 ...
- 【SQL Server 优化性能的几个方面】(转)
转自:http://blog.csdn.net/feixianxxx/article/details/5524819 SQL Server 优化性能的几个方面 (一).数据库的设计 可以参看最 ...
- SQL Server优化技巧——如何避免查询条件OR引起的性能问题
之前写过一篇博客"SQL SERVER中关于OR会导致索引扫描或全表扫描的浅析",里面介绍了OR可能会引起全表扫描或索引扫描的各种案例,以及如何优化查询条件中含有OR的SQL语句的 ...
随机推荐
- sublime 配置g++
资料来源: http://blog.csdn.net/leonsc/article/details/5853614 http://www.cnblogs.com/zhenglichina/archiv ...
- [Firefly引擎][学习笔记二][已完结]卡牌游戏开发模型的设计
源地址:http://bbs.9miao.com/thread-44603-1-1.html 在此补充一下Socket的验证机制:socket登陆验证.会采用session会话超时的机制做心跳接口验证 ...
- 【BZOJ 1038】 1038: [ZJOI2008]瞭望塔
1038: [ZJOI2008]瞭望塔 Description 致力于建设全国示范和谐小村庄的H村村长dadzhi,决定在村中建立一个瞭望塔,以此加强村中的治安.我们将H村抽象为一维的轮廓.如下图所示 ...
- Qt:无标题栏无边框程序的拖动和改变大小
From: http://blog.csdn.net/kfbyj/article/details/9284923 最近做项目遇到的问题,总结下. 有时候我们觉得系统的标题栏和按钮太丑太呆板,想做自己的 ...
- 186. Reverse Words in a String II
题目: Given an input string, reverse the string word by word. A word is defined as a sequence of non-s ...
- Android 进程保活招式大全
目前市面上的应用,貌似除了微信和手Q都会比较担心被用户或者系统(厂商)杀死问题.本文对 Android 进程拉活进行一个总结. Android 进程拉活包括两个层面: A. 提供进程优先级,降低进程被 ...
- strcpy函数的C/C++实现
2013-07-05 14:07:49 本函数给出了几种strcpy与strncpy的实现,有ugly implementation,也有good implementation.并参考标准库中的imp ...
- Android开发之极光推送基本步骤
[转]:http://wyong.blog.51cto.com/1115465/1402842 两天在研究推送的问题,后来确定了用极光推送,本人将整个过程整理一下: 1.到极光官网注册账号:https ...
- 使用SAE部署Flask,使用非SAE flask版本和第三方依赖包的方法
目前SAE的Flask的版本为0.7,但是我从学习开始的flask版本就已经是0.10了,而且一些扩展都是使用的0.10以后的from flask.ext.特性进行引入的.所以需要修改SAE的环境. ...
- Oracle Length 和 Lengthb 函数说明 .(用来判断记录值里是否有中文内容)
一.官网的说明 http://download.oracle.com/docs/cd/E11882_01/server.112/e26088/functions088.htm#SQLRF00658 P ...