Is it possible to list all foreign keys in a database?

后端 未结 4 927
一个人的身影
一个人的身影 2021-01-30 12:41

How do I list all FK\'s in a sqlserver database?

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 12:58

    Theoretically, this is hard. The relational model allows any field to relate to any other field. Which ones are actually used is defined by all possible SELECT statements that could be used.

    Practically, it depends on how many tables have the FK definitions included. If someone bothered to carefully define all FK references -- and the SELECT statements stick to these rules -- you can query them.

    However, since a SELECT statement can join on anything, there's no guarantee that you have all FK's unless you also have all SELECT statements.


    Edit.

    See http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/11/26/viewing-all-foreign-key-constraints-in-sql-server.aspx

    SELECT f.name AS ForeignKey, 
       OBJECT_NAME(f.parent_object_id) AS TableName, 
       COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName, 
       OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName, 
       COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName 
    FROM sys.foreign_keys AS f 
    INNER JOIN sys.foreign_key_columns AS fc 
       ON f.OBJECT_ID = fc.constraint_object_id
    

    Might work for you.

提交回复
热议问题