我一直在开发一个查询来使用DMV获取索引碎片信息。
但是,查询提供的结果比预期的要多。我相信问题在于加入。
有什么想法吗?
select distinct '['+DB_NAME(database_id)+']' as DatabaseName,
'['+DB_NAME(database_id)+'].['+sch.name+'].['
+ OBJECT_NAME(ips.object_id)+']' as TableName,
i.name as IndexName,
ips.index_type_desc as IndexType,
avg_fragmentation_in_percent as avg_fragmentation,
SUM(row_count) as Rows
FROM
sys.indexes i INNER JOIN
sys.dm_db_index_physical_stats(NULL,NULL,NULL,NULL,'LIMITED') ips ON
i.object_id = ips.object_id INNER JOIN
sys.tables tbl ON tbl.object_id = ips.object_id INNER JOIN
sys.schemas sch ON sch.schema_id = tbl.schema_id INNER JOIN
sys.dm_db_partition_stats ps ON ps.object_id = ips.object_id
WHERE
avg_fragmentation_in_percent <> 0.0 AND ips.database_id = 6
AND OBJECT_NAME(ips.object_id) not like '%sys%'
GROUP BY database_id, sch.name, ips.object_id, avg_fragmentation_in_percent,
i.name, ips.index_type_desc
ORDER BY avg_fragmentation_in_percent desc
答案 0 :(得分:5)
我认为您需要在针对sys.dm_db_partition_stats
和sys.indexes
的联接中使用index_id。
最好使用sys.dm_db_index_physical_stats
的第一个参数来过滤db而不是where子句ips.database_id = 6
。
我不理解distinct
,group by
或sum(row_count)
条款。
这是一个查询,您可以尝试查看它是否符合您的要求。
select
db_name(ips.database_id) as DataBaseName,
object_name(ips.object_id) as ObjectName,
sch.name as SchemaName,
ind.name as IndexName,
ips.index_type_desc,
ps.row_count
from sys.dm_db_index_physical_stats(6,NULL,NULL,NULL,'LIMITED') as ips
inner join sys.tables as tbl
on ips.object_id = tbl.object_id
inner join sys.schemas as sch
on tbl.schema_id = sch.schema_id
inner join sys.indexes as ind
on ips.index_id = ind.index_id and
ips.object_id = ind.object_id
inner join sys.dm_db_partition_stats as ps
on ps.object_id = ips.object_id and
ps.index_id = ips.index_id and
ps.partition_number = ips.partition_number