I want to get relations (or foreign keys) of a Sql Server Table
in my c# code.
How can i do this?
Thank you
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
This will get all the foreign keys that dbo.YourTableName
references:
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');
If you want to get all the foreign keys that reference dbo.YourTableName
, it's only slightly different:
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
You can put this in a stored procedure, parameterize the two-part name you pass into the OBJECT_ID
function, and then call the stored procedure from your C# code.