查看数据库资源被占情况(锁)

/*
==================== 资源占用锁 ===============
如果发现某个资源频繁的发生被占用的情况(放置锁)
更新锁过多的发生
1.是否有很多数据被频繁的修改
2.是否缺少合适的索引
3.是否索引碎片过大

-- 查看锁的类型
SELECT * FROM master.dbo.spt_values WHERE [type] = 'L';
*/

 

USE test -- 要观察的数据库
go

SELECT
 request_session_id AS sp_id,
  COALESCE(s.name + '.' + o.name + ISNULL('.' + i.name,'') COLLATE Chinese_PRC_CI_AS,s2.name + '.' + o2.name,db.name) AS [object_name],
 -- COALESCE()函数,返回参数列表中第一个非空的值
 l.resource_type AS [类型],
 request_mode AS [锁模式], -- S:共享锁;U:更新锁;X:独占锁;I:意向锁;Sch-:架构锁
 request_status AS [状态]
FROM sys.dm_tran_locks l
LEFT JOIN sys.partitions p
ON l.resource_associated_entity_id = p.hobt_id
LEFT JOIN sys.indexes i
ON p.[object_id] = i.[object_id]
AND p.index_id = i.index_id
LEFT JOIN sys.objects o
ON p.[object_id] = o.[object_id]
LEFT JOIN sys.schemas s
ON o.[schema_id] = s.[schema_id]
LEFT JOIN sys.objects o2
ON l.resource_associated_entity_id = o2.[object_id]
LEFT JOIN sys.schemas s2
ON o2.[schema_id] = s2.[schema_id]
LEFT JOIN sys.databases db
ON l.resource_database_id = db.database_id
WHERE resource_database_id = DB_ID() -- 当前数据库
ORDER BY sp_id, [object_name], CASE l.resource_type WHEN 'database' THEN 1 WHEN 'object' THEN 2 WHEN 'page' THEN 3 WHEN 'key' THEN 4 ELSE 5 END;

 

/* ============= 查看指定表的索引使用情况 =============
是否需要重新创建索引或组织索引

DECLARE @DBName VARCHAR(50),@TableName VARCHAR(100);
SET @DBName = 'bsv100';-- 数据库
SET @TableName = 'dbo.T_Order';--  表

SELECT object_name(ps.[object_id]) AS [表]
,ix.[Name] AS [索引名称]
,ps.index_type_desc AS [索引类型]
,ps.avg_fragmentation_in_percent AS [碎片率] -- 该值越小越好
,ps.avg_fragment_size_in_pages AS [碎片占用页面数] -- 平均多少个page就有一个碎片,该值 越大越好
,'ALTER INDEX ' + ix.[name] + ' ON dbo.' + object_name(ps.[object_id]) + ' REORGANIZE;' AS [组织索引]
FROM sys.dm_db_index_physical_stats(db_id(@DBName),object_id(@TableName),null,null,null) AS ps
INNER JOIN sys.indexes  AS ix
ON ps.[object_id] = ix.[object_id] AND ps.index_id=ix.index_id;

===================================================================*/

 

/* ====================== 缓存周期 ======================
正常情况下,被缓存在内存的数据在300秒内没有被使用过就会被交换出去;
如果低于这个值时就表明你需要优化程序或者加内存了。
如果高于这个值,说明被缓存的数据越多,所以数据的提取就越快。
在新服务器上线后,你应该每隔一个星期记录下这个值,以及时预知情况。

SELECT cntr_value AS [数据缓存时间(秒)]
FROM master.dbo.sysperfinfo
WHERE [object_name] = 'SQLServer:Buffer Manager'
AND counter_name = 'Page life expectancy';
-- 74067  21453 40891   ->5798 ->5149
-- 2013-09-04 ======== 39059

==============================================*/

posted @ 2013-09-18 15:28  超缘  阅读(1000)  评论(0编辑  收藏  举报