Get Relations of a Table

2019-05-26 00:38发布

问题:

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.