2

我想Table在我的 c# 代码中获取 Sql Server 的关系(或外键)。我怎样才能做到这一点?谢谢

4

1 回答 1

3

这将获得所有dbo.YourTableName引用的外键:

SELECT 
    FK = OBJECT_NAME(pt.constraint_object_id),
    Referencing_col = pc.name, 
    Referenced_col = rc.name
FROM sys.foreign_key_columns AS pt
INNER JOIN sys.columns AS pc
ON pt.parent_object_id = pc.[object_id]
AND pt.parent_column_id = pc.column_id
INNER JOIN sys.columns AS rc
ON pt.referenced_column_id = rc.column_id
AND pt.referenced_object_id = rc.[object_id]
WHERE pt.parent_object_id = OBJECT_ID('dbo.YourTableName');

如果你想获取所有引用的外键dbo.YourTableName,它只是略有不同:

SELECT 
    -- add these two columns:
    [Schema] = OBJECT_SCHEMA_NAME(pt.parent_object_id),
    [Table] = OBJECT_NAME(pt.parent_object_id),
    FK = OBJECT_NAME(pt.constraint_object_id),
    Referencing_col = pc.name, 
    Referenced_col = rc.name
FROM sys.foreign_key_columns AS pt
INNER JOIN sys.columns AS pc
ON pt.parent_object_id = pc.[object_id]
AND pt.parent_column_id = pc.column_id
INNER JOIN sys.columns AS rc
ON pt.referenced_column_id = rc.column_id
AND pt.referenced_object_id = rc.[object_id]
WHERE pt.referenced_object_id = OBJECT_ID('dbo.YourTableName');
---------^^^^^^^^^^ change this

你可以把它放在一个存储过程中,参数化你传递给函数的由两部分组成的名称OBJECT_ID,然后从你的 C# 代码中调用这个存储过程。

于 2012-06-22T18:05:49.237 回答