Labels

Monday, January 28, 2013

SQL Query to get Constraint Information


SELECT ISNULL(c.constraint_name, '') ConstraintName
 ,ISNULL(cfk.table_name, '') FK_Table_name
 ,ISNULL(kcu.column_name, '') FK_Column_name
 ,ISNULL(cpk.table_name, '') PK_Table_name
 ,ISNULL(pkt.column_name, '') PK_COlumn_name
FROM information_schema.REFERENTIAL_CONSTRAINTS c
INNER JOIN information_schema.TABLE_CONSTRAINTS cpk ON c.unique_constraint_name = cpk.constraint_name
INNER JOIN information_schema.TABLE_CONSTRAINTS cfk ON c.constraint_name = cfk.constraint_name
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON c.constraint_name = kcu.constraint_name
INNER JOIN (
 SELECT tci.table_name
  ,kcui.column_name
 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tci
 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcui ON tci.constraint_name = kcui.constraint_name
 WHERE tci.CONSTRAINT_TYPE = 'PRIMARY KEY'
 ) PKT ON PKT.TABLE_NAME = CPK.TABLE_NAME
GROUP BY c.constraint_name
 ,cfk.table_name
 ,kcu.column_name
 ,cpk.table_name
 ,pkt.column_name
HAVING count(pkt.column_name) = 1
--and cfk.table_name = 'pf_child'
ORDER BY 1
 ,2
 ,3
 ,4

No comments:

Post a Comment