Viewing oracle's metadata about primary/foreign key constraints

霸气de小男生 提交于 2019-12-23 18:02:28

问题


Which table contains detailed information(For example the table the foreign key is referring to) about the constraints? The tables 'all_cons_columns' , 'all_constraints' contains only the name of the constraints which isn't very helpful. I am currently using dbms_metadata.get_ddl() but it doesn't work on all the databases.

Thanks.


回答1:


It is all in there: the column R_CONSTRAINT_NAME in ALL_CONSTRAINTS contains the name of the referenced PK/UK constraint for a foreign key. You can then look up that constraint to get the TABLE_NAME of the reference table.

When looking at ALL_CONS_COLUMNS, the POSITION of the column in the foreign key will match the POSITION of the column in the primary/unique key.




回答2:


This statement lists tables, constraint names, and foreign key table names:

select c.table_name,c.constraint_name,  --c.r_constraint_name, 
  cc.table_name
from all_constraints c
inner join all_constraints cc on c.r_constraint_name = cc.constraint_name



回答3:


In order to retrieve the foreign key and generate a script to create these, you can use the following query:

SELECT 
   'ALTER TABLE ' || a.table_name || ' ADD CONSTRAINT ' || a.constraint_name 
   || ' FOREIGN KEY (' || a.column_name || ') REFERENCES ' || jcol.table_name 
   || ' (' || jcol.column_name || ');' as commandforeign
FROM
   (SELECT 
       uc.table_name, uc.constraint_name, uc.r_constraint_name, col.column_name
    FROM 
       USER_CONSTRAINTS uc, USER_CONS_COLUMNS col
    WHERE 
       uc.constraint_type='R' and uc.constraint_name=col.constraint_name) a
 INNER JOIN 
    USER_CONS_COLUMNS jcol
 ON 
    a.r_constraint_name=jcol.constraint_name;



回答4:


Have a look at: Reverse Engineering a Data Model. Based on this I did a Python program that dumps Oracle db schema to text. There is PRIMARY_KEYS_INFO_SQL and FOREIGN_KEYS_INFO_SQL that do what you are interested in.



来源:https://stackoverflow.com/questions/3210743/viewing-oracles-metadata-about-primary-foreign-key-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!