我想获得一个SQL Server的关系(或外键) Table
在我的C#代码。 我怎样才能做到这一点? 谢谢
Answer 1:
这将让所有的外键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#代码中调用存储过程。
文章来源: Get Relations of a Table