Question

I am trying to create a select statement, which allows me to get an overview over all of my foreign keys. It should look like this:

Table 1  | FK_Value  | Table 2 | FK_Value

I have figured out there must be a way with the "user_constraints" table but i need some help.

Was it helpful?

Solution

I think you need this:

SELECT a.table_name, a.column_name, a.constraint_name, c.owner, 
       -- referenced pk
       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 c.constraint_type = 'R'
   AND a.table_name = :TableName

Source: stackoverflow.com/questions/1729996/list-of-foreign-keys-and-the-tables-they-reference

OTHER TIPS

This worked for me in SQL2008 (don't have 2005)

To get list of referring table and column names...

select t.name as TableWithForeignKey, fk.constraint_column_id as FK_PartNo , c.name as ForeignKeyColumn 
from sys.foreign_key_columns as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where fk.referenced_object_id = (select object_id from sys.tables where name = 'TableOthersForeignKeyInto')
order by TableWithForeignKey, FK_PartNo
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top