Query a Table's Foreign Key relationships

后端 未结 9 1833
旧时难觅i
旧时难觅i 2020-12-03 01:40

For a given table \'foo\', I need a query to generate a set of tables that have foreign keys that point to foo. I\'m using Oracle 10G.

相关标签:
9条回答
  • 2020-12-03 02:00

    Here's how to take Mike's query one step further to get the column names from the constraint names:

    select * from user_cons_columns
    where constraint_name in (
      select constraint_name 
      from all_constraints
      where constraint_type='R'
      and r_constraint_name in 
        (select constraint_name
        from all_constraints
        where constraint_type in ('P','U')
        and table_name='<your table name here>'));
    
    0 讨论(0)
  • 2020-12-03 02:10

    link to Oracle Database Online Documentation

    You may want to explore the Data Dictionary views. They have the prefixes:

    • User
    • All
    • DBA

    sample:

    select * from dictionary where table_name like 'ALL%' 
    

    Continuing Mike's example, you may want to generate scripts to enable/disable the constraints. I only modified the 'select' in the first row.

    select  'alter table ' || TABLE_NAME || ' disable constraint ' || CONSTRAINT_NAME || ';'
    from all_constraints
    where constraint_type='R'
    and r_constraint_name in 
      (select constraint_name
      from all_constraints
      where constraint_type in ('P','U')
      and table_name='<your table here>');
    
    0 讨论(0)
  • 2020-12-03 02:10
    select distinct table_name, constraint_name, column_name, r_table_name, position, constraint_type 
    from (
        SELECT uc.table_name, 
        uc.constraint_name, 
        cols.column_name, 
        (select table_name from user_constraints where constraint_name = uc.r_constraint_name) 
            r_table_name,
        (select column_name from user_cons_columns where constraint_name = uc.r_constraint_name and position = cols.position) 
            r_column_name,
        cols.position,
        uc.constraint_type
        FROM user_constraints uc
        inner join user_cons_columns cols on uc.constraint_name = cols.constraint_name 
        where constraint_type != 'C'
    ) 
    start with table_name = '&&tableName' and column_name = '&&columnName'  
    connect by nocycle 
    prior table_name = r_table_name 
    and prior column_name = r_column_name;   
    
    0 讨论(0)
提交回复
热议问题