Primary Key ve Foreign Key İlişkisi

Primary Key ve Foreign Key İlişkisi

Diyelim ki veritabanınızda yüzlerce tablo var ve bu yüzlerce tablo birçok farklı şekilde birbiriyle ilişki. Eğer bu ilişkiyi özet bir şekilde görmek isterseniz, aşağıdaki script veritabanınızda Foreign Key olarak belirlediğiniz Primary Key alanları listelemenizi sağlar.

SELECT PKTable = PK.TABLE_NAME

,PKColumn = PT.COLUMN_NAME

,FKTable = FK.TABLE_NAME

,FKColumn = KCU.COLUMN_NAME

,ConstraintName = RC.CONSTRAINT_NAME

FROM   INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC

INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON RC.CONSTRAINT_NAME = FK.CONSTRAINT_NAME

INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON RC.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME

INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU ON RC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME

INNER JOIN (SELECT TC.TABLE_NAME

,KCU2.COLUMN_NAME

FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC

INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2 ON TC.CONSTRAINT_NAME = KCU2.CONSTRAINT_NAME

WHERE   TC.CONSTRAINT_TYPE = ‘PRIMARY KEY’) PT ON PT.TABLE_NAME = PK.TABLE_NAME

ORDER BY PK.TABLE_NAME

 

1998total visits,2visits today

Leave a Reply

Your email address will not be published. Required fields are marked *