得到一个表的关系 [英] Get Relations of a Table
本文介绍了得到一个表的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获得一个SQL Server 表格
的关系(或外键),在我的C#code。
我怎样才能做到这一点?
谢谢
I want to get relations (or foreign keys) of a Sql Server Table
in my c# code.
How can i do this?
Thank you
推荐答案
这将让所有的外键的 dbo.YourTableName
引用:
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');
如果你想获得所有引用 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
您可以把这个存储过程中,参数传递到 OBJECT_ID
函数的两部分名称,然后在C#$ C $调用存储过程℃。
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.
这篇关于得到一个表的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文