How to find all foreign keys?

I would like to find all the referenced tables in my db that have a foreign key that points to a specific table with links. Is there a query that I can run for this?

Not sure if the question is confusing. Let me know if this is the case, and I can try to explain it in more detail.

+3
source share
4 answers

The following request or modification tehreof will execute - on the Sql server you can also specify the directory and information about the scheme

select tab1.TABLE_NAME from 
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS as ref inner join
INFORMATION_SCHEMA.TABLE_CONSTRAINTS as prim
on ref.UNIQUE_CONSTRAINT_NAME=prim.CONSTRAINT_NAME
and ref.UNIQUE_CONSTRAINT_CATALOG=prim.CONSTRAINT_CATALOG
and ref.UNIQUE_CONSTRAINT_SCHEMA=prim.CONSTRAINT_SCHEMA
--and prim.CONSTRAINT_TYPE in('PRIMARY KEY','UNIQUE')
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS tab1 on
ref.CONSTRAINT_NAME=tab1.CONSTRAINT_NAME
and ref.CONSTRAINT_CATALOG=tab1.CONSTRAINT_CATALOG
and ref.CONSTRAINT_SCHEMA=tab1.CONSTRAINT_SCHEMA
where prim.TABLE_NAME='YourTablename'
+2
source

I had a similar problem a while ago. Here is the script I wrote using the Sql SMO server:

    public static string GetForeignKeyScript()
    {
        SqlConnection conn = new System.Data.SqlClient.SqlConnection("SOME_CONNECTION_STRING");
        Server server = new Server(new ServerConnection(conn));
        Database db = server.Databases["SOME_DATABASE"];
        Table Roles = db.Tables["SOME_TABLE"];

        var sb = new StringBuilder();

        foreach (Table table in db.Tables)
            foreach (ForeignKey fk in table.ForeignKeys)
                    foreach (string s in fk.Script())
                        sb.AppendLine(s);

        return sb.ToString();
    }

, .

, , ( , , , )

+2

Take a look at the metadata:

SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
SELECT * FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
0
source
SELECT  DISTINCT
             ParentSchema.name      ParentSchema
            ,ParentTable.name       ParentTable
            ,ChildSchema.name       ChildSchema
            ,ChildTable.name        ChildTable
    FROM sys.foreign_keys       Foreign_Keys
    JOIN sys.objects            ParentTable     ON  Foreign_Keys.parent_object_id       =   ParentTable.object_id
    JOIN sys.schemas            ParentSchema    ON  ParentTable.schema_id               =   ParentSchema.schema_id
    JOIN sys.objects            ChildTable      ON  Foreign_Keys.referenced_object_id   =   ChildTable.object_id
    JOIN sys.schemas            ChildSchema     ON  ChildTable.schema_id                =   ChildSchema.schema_id
    WHERE ParentSchema.name = '??????'
      AND ParentTable.name = '??????'
0
source

Source: https://habr.com/ru/post/1751102/


All Articles