Blog Pages

A script to check the usage of table in the DB

declare @TableName nvarchar(100)
select @TableName = 'TableName'

----------------------------------------------------------
-- get data about the table using sp_help:
----------------------------------------------------------
declare @query nvarchar(100)
SET @query = 'sp_help ''dbo.' + @TableName + ''''
exec (@query)

----------------------------------------------------------
-- table triggers:
----------------------------------------------------------
select name as triggerName, OBJECT_NAME(parent_object_id) from sys.objects 
where type = 'TR' and SCHEMA_NAME(schema_id) = 'dbo'
and OBJECT_NAME(parent_object_id) = @TableName
order by name

----------------------------------------------------------
-- foreign keys constraints from other tables to @TableName :
----------------------------------------------------------
select  object_name(f.constraint_object_id) as NameofConstraint,
SCHEMA_NAME(o.schema_id) AS SchemaName,
object_name(f.parent_object_id) AS TableName,
type_desc AS ConstraintType
from sys.foreign_key_columns f
inner join sys.objects o on o.object_id = f.constraint_object_id  
and SCHEMA_NAME(o.schema_id) = 'dbo'
where object_name(f.referenced_object_id) = @TableName
order by object_name(f.constraint_object_id)

----------------------------------------------------------
-- get dependencies
----------------------------------------------------------
select distinct sd.id, so.name, so.Type, sd.depid, so_dep.name, so_dep.Type
from  sys.sysdepends sd
inner join sys.objects so on so.object_id = sd.id 
and SCHEMA_NAME(so.schema_id) = 'dbo'
inner join sys.objects so_dep on so_dep.object_id = sd.depid 
where so_dep.name = @TableName
order by so.name

----------------------------------------------------------
--select * from table
----------------------------------------------------------
SET @query = 'select * from dbo.' + @TableName
exec (@query)

No comments:

Post a Comment