如何找到所有外键?

时间:2010-06-21 22:22:26

标签: sql-server sql-server-2005 foreign-keys foreign-key-relationship

我想在我的数据库中找到所有引用表,这些表具有指向特定引用表的外键。是否有我可以运行的查询来执行此操作?

不确定问题是否令人困惑。让我知道它是否是,我可以尝试更详细地解释它。

4 个答案:

答案 0 :(得分:2)

以下查询或修改tehreof将在Sql server中执行 您还可以提供目录和架构信息

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'

答案 1 :(得分:2)

前段时间我遇到过类似的问题。这是我使用Sql Server SMO编写的脚本:

    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 :(得分:0)

查看元数据:

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

答案 3 :(得分:0)

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 = '??????'