Pages

Monday, November 2, 2009

Find Dependencies

Find all procs/functions/views dependent on a particular table

SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'

Find all foreign keys on a table

SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.object_id = fc.constraint_object_id
where OBJECT_NAME(f.parent_object_id) in ('tablename')

Find all tables with a particular column

SELECT name FROM sysobjects WHERE id IN ( SELECT id FROM syscolumns WHERE name = 'columnname' )

Find indexes on a table

SELECT object_name(i.object_id) as objectName,i.[name] as indexName,
object_name(i.index_id) as IndexId
FROM sys.indexes i
where i.[name] like 'IX%'
and object_name(i.object_id) in ('tablename')
GROUP BY i.object_id, i.index_id, i.[name]



Will give you a list of all the child tables that are using a column from this table
SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.object_id = fc.constraint_object_id
where OBJECT_NAME (f.referenced_object_id) = ''


Will give you a list of all foreign keys are that are present on this table
SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.object_id = fc.constraint_object_id
where OBJECT_NAME(f.parent_object_id) = ''

No comments:

Post a Comment