Check out the below script to find out the Foreign Key information like Name of the Foreign Key , Name of the Table which has foreign Key and List of columns in that Foreign Key definition. In addition to this the foreign key which is referencing the Primary Key and Primary key table or Parent table.
SELECT
TC.CONSTRAINT_NAME AS FOREIGN_KEY_CONSTRAINT_NAME,
TC.TABLE_NAME AS FOREIGN_KEY_TABLE_NAME,
KCU.COLUMN_NAME,
ORDINAL_POSITION AS COLUMN_POSITION,
RC.UNIQUE_CONSTRAINT_NAME AS PARENT_PRIMARY_KEY_NAME,
TC_PK.TABLE_NAME AS PARENT_TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU,
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC,
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC_PK
WHERE TC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME
AND TC.TABLE_NAME = KCU.TABLE_NAME
AND TC.CONSTRAINT_TYPE = 'FOREIGN KEY'
AND RC.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
AND RC.UNIQUE_CONSTRAINT_NAME = TC_PK.CONSTRAINT_NAME
Saturday, March 28, 2009
Foreign Key and Primary Key in SQL Server
Labels:
SQL Server Tips,
Vijaya Kadiyala
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment