I want to get relations (or foreign keys) of a Sql Server Table
in my c# code.
How can i do this?
Thank you
Asked
Active
Viewed 1,271 times
2

Navid Farhadi
- 3,397
- 2
- 28
- 34
-
1follow this link [how-to-get-the-table-a-foreign-key-refers-to][1] [1]: http://stackoverflow.com/questions/458913/how-to-get-the-table-a-foreign-key-refers-to – KF2 Jun 22 '12 at 17:47
1 Answers
3
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.

Aaron Bertrand
- 272,866
- 37
- 466
- 490