--option 1SELECT PK.TABLE_NAME,PK.CONSTRAINT_NAME ,FK.CONSTRAINT_NAME FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PKINNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FKON PK.CONSTRAINT_NAME=FK.UNIQUE_CONSTRAINT_NAME---option 2SELECT f.name AS ForeignKey,SCHEMA_NAME(f.SCHEMA_ID) SchemaName,OBJECT_NAME(f.parent_object_id) AS TableName,COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName,SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName,OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnNameFROM
sys.foreign_keys AS fINNER JOIN sys.foreign_key_columns AS fcINNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_idON f.OBJECT_ID = fc.constraint_object_id--OPTION 3SELECT t.name AS [Table],c.name AS [Column]FROM
SYS.TABLES tINNER JOIN SYS.SYSCOLUMNS c ONc.id = t.object_id-- Join on foreign key columnsLEFT JOIN SYS.FOREIGN_KEY_COLUMNS fkc ON(fkc.parent_object_id = t.object_idAND c.colid = fkc.parent_column_id)OR (fkc.referenced_object_id = t.object_idAND c.colid = fkc.referenced_column_id)-- Join on primary key columnsLEFT JOIN SYS.INDEXES i ONi.object_id = t.object_id
and i.is_primary_key = 1LEFT JOIN SYS.INDEX_COLUMNS ic ONic.object_id = t.object_id
AND ic.index_id = i.index_idAND ic.column_id = c.colidWHEREt
.is_ms_shipped = 0AND (c.name LIKE '%ID' OR c.name LIKE '%Code')AND(fkc.constraint_object_id IS NULL -- Not part of a foreign keyAND ic.object_id IS NULL -- Not part of a primary key)
No comments:
Post a Comment