Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

Query to find foreign key relationship and name of the constraints for each table in the database

$
0
0
Sometimes we need to find all foreign key on a table so that we can analyze the relation of a table and can find the solution accordingly. It is very difficult to see it manually, by using the following query we can find all foreign key relationships on the particular table.


SELECT
K_Table=FK.TABLE_NAME,
FK_Column=CU.COLUMN_NAME,
PK_Table=PK.TABLE_NAME,
PK_Column=PT.COLUMN_NAME,
Constraint_Name=C.CONSTRAINT_NAME
FROMINFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTSC
INNERJOININFORMATION_SCHEMA.TABLE_CONSTRAINTSFKONC.CONSTRAINT_NAME=FK.CONSTRAINT_NAME
INNERJOININFORMATION_SCHEMA.TABLE_CONSTRAINTSPKONC.UNIQUE_CONSTRAINT_NAME=PK.CONSTRAINT_NAME
INNERJOININFORMATION_SCHEMA.KEY_COLUMN_USAGECUONC.CONSTRAINT_NAME=CU.CONSTRAINT_NAME
INNERJOIN(
SELECTi1.TABLE_NAME,i2.COLUMN_NAME
FROMINFORMATION_SCHEMA.TABLE_CONSTRAINTSi1
INNERJOININFORMATION_SCHEMA.KEY_COLUMN_USAGEi2ONi1.CONSTRAINT_NAME=i2.CONSTRAINT_NAME
WHEREi1.CONSTRAINT_TYPE='PRIMARY KEY'
)PTONPT.TABLE_NAME=PK.TABLE_NAME
WHEREPK.TABLE_NAME='<YourTableName>'


This article is referred from SQLAuthority to know more please click here MORE

Viewing all articles
Browse latest Browse all 265

Trending Articles