Skip to content

This Library does not Have a quick way to find foreign key references #23

Description

@Keith1039

Hello,

I was hoping to find a function that finds and returns a table or a list of foreign key relationships (table_name, referenced_column, referenced_table) but unfortunately such a function doesn't exist in this library.

I did some digging and found some SQL Server code that does that (works for Postgres too). The thread for this code can be found here
SELECT
KCU1.CONSTRAINT_SCHEMA AS FK_CONSTRAINT_SCHEMA,
KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME,
KCU1.TABLE_SCHEMA AS FK_TABLE_SCHEMA,
KCU1.TABLE_NAME AS FK_TABLE_NAME,
KCU1.COLUMN_NAME AS FK_COLUMN_NAME,
KCU1.ORDINAL_POSITION AS FK_ORDINAL_POSITION,
KCU2.CONSTRAINT_SCHEMA AS REFERENCED_CONSTRAINT_SCHEMA,
KCU2.CONSTRAINT_NAME AS REFERENCED_CONSTRAINT_NAME,
KCU2.TABLE_SCHEMA AS REFERENCED_TABLE_SCHEMA,
KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME,
KCU2.COLUMN_NAME AS REFERENCED_COLUMN_NAME,
KCU2.ORDINAL_POSITION AS REFERENCED_ORDINAL_POSITION
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC

INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1
ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME

INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2
ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG
AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA
AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME
AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions