我有一张带外键的表。如何判断FK是哪个表的主键?那里有大约200张桌子,而且我不知道如何找到这些信息的来源/连接位置。
答案 0 :(得分:2)
这应该有所帮助。只需在您要查询的数据库中运行它:
SELECT f.NAME AS ForeignKey
,SCHEMA_NAME(f.SCHEMA_ID) SchemaName
,OBJECT_NAME(f.parent_object_id) AS TableName
,COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName
,SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName
,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
INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id
GO
基本上,第一列是FK,后面是FK架构和对象。以下是PK列名称,其架构和对象。
答案 1 :(得分:2)
使用此..
SELECT fk.name,
Object_name(fk.parent_object_id) [Parent table],
c1.name [Parent column]
FROM sys.foreign_keys fk
INNER JOIN sys.foreign_key_columns fkc
ON fkc.constraint_object_id = fk.object_id
INNER JOIN sys.columns c1
ON fkc.parent_column_id = c1.column_id
AND fkc.parent_object_id = c1.object_id
INNER JOIN sys.columns c2
ON fkc.referenced_column_id = c2.column_id
AND fkc.referenced_object_id = c2.object_id
WHERE Object_name(fk.referenced_object_id) = 'Tablename' -- Replace with your tablename
AND c2.name = 'Columname' -- Replace with your columname
或者只是使用
sp_help Tablename or [Alt]+F1
答案 2 :(得分:1)
NoDisplayName或Kris G.的任何一个答案都应该有效,但如果你想在SSMS中更容易记住,只需右键单击外键并选择脚本为>创建到>新窗口。
然后,您将获得一个可用于(重新)创建FK的脚本,并且您将能够通过阅读脚本来查看它在哪个表中引用的列。