I came a situation during some analysis where i had to figure
out all dependency of a column across database. This also required when we do
some changes on table columns and wanted to know the impact of such changes.
One way is that we can use SYSCOMMENTS table. It is a table which contains entries for each views, rules,
default, trigger, CHECK constraint, DEFAULT constraint, and stored procedure.
The column TEXT in the syscomments table contains the actual code for all these
objects, and knowing it you can write a code to check the dependencies. I am explaining different approach.
/* Table Name for
which we need to find the dependency of columns.*/
Declare @TableName
varchar(max)='tblSupplierRequestOrder'
/* Column name for
which we need to find the dependnecy in a database*/
Declare @ColumnName
varchar(max)='OrderDate'
select
OBJECT_NAME(k.parent_object_id) as parentTableName
, c1.name as parentColumn
, OBJECT_NAME(k.referenced_object_id)
as referencedTableName
, c2.name as referencedColumn
from
sys.foreign_keys k
inner
join sys.foreign_key_columns
f
on f.parent_object_id = k.parent_object_id
inner
join sys.columns c1
on c1.column_id = f.parent_column_id
and
c1.object_id = k.parent_object_id
inner
join sys.columns c2
on c2.column_id = f.referenced_column_id
and
c2.object_id = k.referenced_object_id
where
c2.name = @ColumnName
and
OBJECT_NAME(k.referenced_object_id)
=@TableName
No comments:
Post a Comment