Thursday, June 02, 2011

Collect every index from DB to compare

if(OBJECT_ID('tempdb..#tmp')>1)
drop table #tmp
create table #tmp (index_name nvarchar(256), index_description nvarchar(500), index_keys nvarchar(500), included_columns nvarchar(1000),filter_definition nvarchar(256))
if(OBJECT_ID('tempdb..#tmp2')>1)
drop table #tmp2
create table #tmp2 (dbname nvarchar(256), tablename nvarchar(256), index_name nvarchar(256), index_description nvarchar(500), index_keys nvarchar(500), included_columns nvarchar(1000),filter_definition nvarchar(256))

declare @tablename nvarchar(256), @sql nvarchar(4000)
declare tmp_cur cursor for
select name from sys.tables where schema_id = 1

open tmp_cur
Fetch next from tmp_cur into @tablename

while @@fetch_status = 0
begin
print @tablename
set @sql = 'insert into #tmp (index_name , index_description , index_keys , included_columns )
exec sp_helpindex2 '''+@tablename+'''

insert into #tmp2 (dbname , tablename, index_name , index_description , index_keys , included_columns )
select db_name(), '''+@tablename+''' , index_name , index_description , index_keys , included_columns from #tmp

truncate table #tmp
'
print @sql
exec sp_executesql @sql

Fetch next from tmp_cur into @tablename
print '---'
end

close tmp_cur
deallocate tmp_cur

drop table __tmp_all_indexes

select *
into __tmp_all_indexes
from #tmp2

1 comment:

Cognac Critics and Cognac Tasting said...

---to create index and drop index
select
'create '+(case when index_description like 'clustered%' then 'clustered' else '' end)+' index ['+index_name+'] on ['+dbname+'].[dbo].['+tablename+'] ('+index_keys+') '+(case when included_columns is not null then 'includes ('+included_columns+')' else '' end) as createindex
,'drop index ['+index_name+'] on ['+dbname+'].[dbo].['+tablename+']' as dropindex
,*
from #tmp2
order by tablename