Script to find unused tables on a server
/*This Script is used to list all the Unused tables on a Server. The script does not work for the sql 2000 Server*/
declare
@sql varchar(2000),
@DatabaseName varchar(100)
/* LOOP THROUGH THE SERVERS*/
If Object_ID('tempdb..#unusedTables') is not null
drop table #unusedTables
create table #unusedTables(DatabaseName varchar(100), Object_Id int, TableName varchar(100))
/*CURSES THROUGH ALL THE DATABASES ON THE SERVER */
declare Database_list cursor for
select
name
from
sys.databases
where
name not in ('master','msdb','modeL','tempdb')
open Database_list
fetch next from Database_list into @DatabaseName
while @@fetch_status = 0
begin
/* THIS PART GETS THE LIST OF TABLES IN A PARTICULAR DATABASE*/
set @sql = 'select
'''',
Object_ID,
Name
from
[' + @DatabaseName + '].sys.tables
where
object_ID not in (SELECT
distinct S.object_ID
FROM
[' + @DatabaseName + '].sys.dm_db_index_usage_stats S
inner join
[' + @DatabaseName + '].sys.tables T
on T.object_id = S.object_ID)'
insert into #unusedTables
exec (@sql)
Update #unusedTables
set DatabaseName = @DatabaseName
where DatabaseName = ''
fetch next from Database_list into @DatabaseName
end
select * from #unusedTables
close Database_list
deallocate Database_list
declare
@sql varchar(2000),
@DatabaseName varchar(100)
/* LOOP THROUGH THE SERVERS*/
If Object_ID('tempdb..#unusedTables') is not null
drop table #unusedTables
create table #unusedTables(DatabaseName varchar(100), Object_Id int, TableName varchar(100))
/*CURSES THROUGH ALL THE DATABASES ON THE SERVER */
declare Database_list cursor for
select
name
from
sys.databases
where
name not in ('master','msdb','modeL','tempdb')
open Database_list
fetch next from Database_list into @DatabaseName
while @@fetch_status = 0
begin
/* THIS PART GETS THE LIST OF TABLES IN A PARTICULAR DATABASE*/
set @sql = 'select
'''',
Object_ID,
Name
from
[' + @DatabaseName + '].sys.tables
where
object_ID not in (SELECT
distinct S.object_ID
FROM
[' + @DatabaseName + '].sys.dm_db_index_usage_stats S
inner join
[' + @DatabaseName + '].sys.tables T
on T.object_id = S.object_ID)'
insert into #unusedTables
exec (@sql)
Update #unusedTables
set DatabaseName = @DatabaseName
where DatabaseName = ''
fetch next from Database_list into @DatabaseName
end
select * from #unusedTables
close Database_list
deallocate Database_list
Comments
Post a Comment