使用SQL查询查找外键关系

时间:2011-12-09 04:16:44

标签: sql sql-server sql-server-2008

是否可以通过SQL查询找到外键关系?

数据库在我外部,我无法直接访问它以通过Server Management Studio查看链接。

3 个答案:

答案 0 :(得分:7)

要检索外键列表,您可以运行此查询:

SELECT t.name AS FKTableName
   , fk.name AS NameOfForeignKey
   , pc.name AS FKColumn
   , rt.name AS ReferencedTable
   , c.name AS ReferencedColumn
FROM sys.foreign_key_columns AS fkc
INNER JOIN sys.foreign_keys AS fk ON fkc.constraint_object_id = fk.object_id
INNER JOIN sys.tables AS t ON fkc.parent_object_id = t.object_id
INNER JOIN sys.tables AS rt ON fkc.referenced_object_id = rt.object_id
INNER JOIN sys.columns AS pc ON fkc.parent_object_id = pc.object_id
   AND fkc.parent_column_id = pc.column_id
INNER JOIN sys.columns AS c ON fkc.referenced_object_id = c.object_id
   AND fkc.referenced_column_id = c.column_id

如果您需要有关设置的其他信息,此查询也会变得更加复杂。

答案 1 :(得分:2)

要查找外键,请考虑使用以下系统视图:

sys.sysconstraints
sys.columns
sys.tables

您可以在colid,column_id,object_id上加入这三个视图,以获取有关外键约束的完整信息。

这些视图应该在SQL Server 2005 +

答案 2 :(得分:-2)

不,你不能,

但是你可以手动检查它,在你需要查询每个表并查看每个不同表中存在的列[id]时,这很麻烦。看到它的关系。

此致