我正在编写一个脚本来快速检查给定数据库中的索引。我想我的脚本写得不错,但是为了删除重复的行,我已经完成了很多SUM
功能,但我不确定这是否正确:
SELECT OBJECT_NAME(i.object_id) AS 'Table Name'
, COALESCE(i.name, '') AS 'Index Name'
, i.type_desc AS 'Index Type'
, i.is_primary_key AS 'Primary Key'
, i.is_disabled AS 'Index Disabled'
, ROUND(CONVERT(FLOAT,SUM(user_seeks)) / (CONVERT(FLOAT,ISNULL(NULLIF(SUM(user_scans),0),1))),2) AS 'Seeks Per Scan'
, ROUND((CONVERT(FLOAT,SUM(user_seeks) +SUM(user_scans) + SUM(user_lookups))) / (CONVERT(FLOAT,ISNULL(NULLIF(SUM(user_updates),0),1))),2) AS 'Reads Per Write'
, (SUM(user_seeks) + SUM(user_scans) + SUM(user_lookups)) AS 'Reads'
, SUM(user_updates) AS 'Writes'
, SUM(user_seeks) AS 'Seeks'
, SUM(user_scans) AS 'Scan'
, ROUND(AVG(ps.avg_fragmentation_in_percent),2) AS 'Avg Fragmentation %'
, NULLIF((SUM(leaf_insert_count) + SUM(leaf_update_count) + SUM(leaf_delete_count)),0) / NULLIF(SUM(leaf_allocation_count),0) AS 'Leaf Page Splits Per Write'
, NULLIF((SUM(nonleaf_insert_count) + SUM(nonleaf_update_count) + SUM(nonleaf_delete_count)),0) / NULLIF(SUM(nonleaf_allocation_count),0) AS 'Non-Leaf Page Splits Per Write'
, CAST (100.0 * SUM(row_lock_wait_count) / (1 + SUM(row_lock_count)) AS NUMERIC(15,2)) AS 'Block %'
, SUM(row_lock_wait_in_ms) AS 'Row Lock Wait (ms)'
, CAST(1.0 * SUM(row_lock_wait_in_ms) / (1 + SUM(row_lock_wait_count)) AS NUMERIC(15,2)) AS 'Average Row Lock Wait'
FROM sys.indexes i
LEFT JOIN sys.objects o ON o.object_id = i.object_id
LEFT JOIN sys.dm_db_index_operational_stats(NULL, NULL, NULL, NULL) s ON o.object_id = s.object_id AND i.index_id = s.index_id
LEFT JOIN sys.dm_db_index_usage_stats u ON s.object_id = u.object_id AND u.index_id = s.index_id
LEFT JOIN sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS ps ON u.index_id = ps.index_id AND u.object_id = ps.object_id
WHERE OBJECTPROPERTY(o.object_id,'IsUserTable') = 1
AND NOT OBJECT_NAME(i.object_id) = 'sysdiagrams' -- exclude sysdiagrams
--AND i.is_primary_key = 0
GROUP BY OBJECT_NAME(i.object_id), COALESCE(i.name, ''),i.type_desc,i.is_primary_key,i.is_disabled
ORDER BY OBJECT_NAME(i.object_id), COALESCE(i.name, '')
这个可以吗?还是SUM
行不好?
此外,是否有您认为有助于查找未使用/需要重新编制索引等的索引的任何信息
为什么不直接使用其中一种免费提供的脚本呢?sqlfool.com上发布的版本的当前有效版本。