このクエリは、現在のデータベースからすべてのインデックス(名前、断片化、およびその他のパラメータ)を選択します。
_select
idx.[name] as [index_name],
sc.[name] as [schema_name],
obj.[name] as [table_name],
ips.[avg_fragmentation_in_percent] as [fragmentation_percent]
from sys.indexes as idx
inner join sys.objects as obj on idx.object_id = obj.object_id
inner join sys.schemas as sc on obj.schema_id = sc.schema_id
cross apply sys.dm_db_index_physical_stats( DB_ID(), idx.object_id, idx.index_id, NULL ,'LIMITED') AS ips
where idx.[name] is not NULL
order by [fragmentation_percent] desc;
_
次に、指定された列を持つすべてのインデックスをすべてのデータベースから選択する必要があります。ステートメントを手動で実行するときに_USE [dbname]
_を使用できますが、カーソルに入れる必要があるため、カーソルに_USE [dbname]
_を書き込むことができません。
ステートメントの...CROSS APPLY sys.dm_db_index_physical_stats( DB_ID(), ...
部分でデータベースの選択を置き換えるにはどうすればよいですか?
1つのクエリですべてのデータベースインデックスを選択する方法を示すために、ヘルプをいただければ幸いです。
このようなもの:
_declare cr_index cursor
for
exec(@dynamicUSE)
select
idx.[name] as [index_name],
sc.[name] as [schema_name],
obj.[name] as [table_name],
ips.[avg_fragmentation_in_percent] as [fragmentation_percent]
from sys.indexes as idx
inner join sys.objects as obj on idx.object_id = obj.object_id
inner join sys.schemas as sc on obj.schema_id = sc.schema_id
cross apply sys.dm_db_index_physical_stats( DB_ID(), idx.object_id, idx.index_id, NULL ,'LIMITED') AS ips
where idx.[name] is not NULL
order by [fragmentation_percent] desc;
_
カーソルで動的SQLを実行して、サーバー上のすべてのデータベースで次のように実行できます。
DECLARE @DB_Name varchar(100)
DECLARE @Command nvarchar(1000)
DECLARE database_cursor CURSOR FOR
SELECT name FROM MASTER.sys.sysdatabases
OPEN database_cursor
FETCH NEXT FROM database_cursor INTO @DB_Name
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @Command = 'USE [' + @DB_Name + ']; select
idx.[name] as [index_name],
sc.[name] as [schema_name],
obj.[name] as [table_name],
ips.[avg_fragmentation_in_percent] as [fragmentation_percent]
from sys.indexes as idx
inner join sys.objects as obj on idx.object_id = obj.object_id
inner join sys.schemas as sc on obj.schema_id = sc.schema_id
cross apply sys.dm_db_index_physical_stats( DB_ID(), idx.object_id, idx.index_id, NULL ,''LIMITED'') AS ips
where idx.[name] is not NULL
order by [fragmentation_percent] desc;'
EXEC sp_executesql @Command
FETCH NEXT FROM database_cursor INTO @DB_Name
END
CLOSE database_cursor
DEALLOCATE database_cursor