获取表的关系

时间:2012-06-22 17:38:12

标签: c# sql-server ado.net foreign-keys

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

1 个答案:

答案 0 :(得分: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#代码调用存储过程。