在Oracle SQL中,如何查找哪些表引用特定列(即将其作为外键)?

时间:2015-06-10 16:32:20

标签: sql oracle

我正在研究这个问题 - How can I find which tables reference a given table in Oracle SQL Developer?

它显示了一些代码来查找哪些表引用了指定的表:

elect table_name, constraint_name, status, owner
from all_constraints
where r_owner = :r_owner
and constraint_type = 'R'
and r_constraint_name in
 (
   select constraint_name from all_constraints
   where constraint_type in ('P', 'U')
   and table_name = :r_table_name
   and owner = :r_owner
 )
order by table_name, constraint_name

所以我试图定制代码以获取引用特定列的表(这里是PREPARER_ID);这是我到目前为止所尝试的:

select column_name, constraint_name, status, owner
from all_constraints
where r_owner = :r_owner
and constraint_type = 'R'
and r_constraint_name in
 (
   select constraint_name from all_constraints
   where constraint_type in ('P', 'U')
   and column_name = :r_column_name
   and owner = :r_owner
 )
ORDER BY column_name, constraint_name

这给了我一个错误:

ORA-00904: "COLUMN_NAME": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:
Error at Line: 103 Column: 8

1 个答案:

答案 0 :(得分:2)

要根据您需要查看the all_cons_columns view以及all_constraints的列进行查询。这不必使用子查询,而是遵循您的模式:

select ac.table_name, acc.column_name, ac.constraint_name, ac.status, ac.owner
from all_constraints ac
join all_cons_columns acc
on acc.owner = ac.owner
and acc.constraint_name = ac.constraint_name
and acc.table_name = ac.table_name
where ac.r_owner = :r_owner
and ac.constraint_type = 'R'
and ac.r_constraint_name in
 (
   select ac2.constraint_name
   from all_constraints ac2
   join all_cons_columns acc2
   on acc2.owner = ac2.owner
   and acc2.constraint_name = ac2.constraint_name
   and acc2.table_name = ac2.table_name
   where ac2.constraint_type in ('P', 'U')
   and acc2.column_name = :r_column_name
   and ac2.owner = :r_owner
 )
ORDER BY ac.table_name, acc.column_name, acc.constraint_name;

进行样本设置:

create table parent_table (preparer_id number primary key);
create table child_table (some_col number references parent_table(preparer_id));

并绑定设置:

var r_column_name varchar2(30);
var r_owner varchar2(30);

begin
  :r_column_name := 'PREPARER_ID';
  :r_owner := user;
end;
/

得到:

TABLE_NAME           COLUMN_NAME          CONSTRAINT_NAME      STATUS   OWNER    
-------------------- -------------------- -------------------- -------- ----------
CHILD_TABLE          SOME_COL             SYS_C00101337        ENABLED  MY_SCHEMA