Oracle:获取所有约束/列(主键和外键)

时间:2016-05-04 08:55:16

标签: sql oracle metadata

此SQL查询:

SELECT a.table_name, a.column_name, a.constraint_name, c.owner, 
c.r_owner, c_pk.table_name r_table_name, c_pk.constraint_name r_pk
FROM all_cons_columns a
JOIN all_constraints c ON a.owner = c.owner
AND a.constraint_name = c.constraint_name
JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
AND c.r_constraint_name = c_pk.constraint_name
WHERE a.owner = 'BRANCH_DEV'
AND a.table_name IN ( 'table1','table2' );

返回所有者BRANCH_DEV和表/列名称的约束。但是,我还需要在“密钥表”(原始表)中获取列的名称。

1 个答案:

答案 0 :(得分:5)

将约束列视图加入到pk约束视图中:

SELECT a.table_name
     , a.column_name
     , a.constraint_name
     , c.owner
     , c.r_owner
     , c_pk.table_name      r_table_name
     , c_pk.constraint_name r_pk
     , cc_pk.column_name    r_column_name
  FROM all_cons_columns a
  JOIN all_constraints  c       ON (a.owner                 = c.owner                   AND a.constraint_name   = c.constraint_name     )
  JOIN all_constraints  c_pk    ON (c.r_owner               = c_pk.owner                AND c.r_constraint_name = c_pk.constraint_name  )
  JOIN all_cons_columns cc_pk   on (cc_pk.constraint_name   = c_pk.constraint_name      AND cc_pk.owner         = c_pk.owner            )
 WHERE a.owner = 'BRANCH_DEV'
   AND a.table_name IN ( 'table1','table2' )
     ;