[英]Get foreign key field from primary key in another table that linked to many table
My database is designed in SQL Server & I want get output in asp.net, LINQ, C# 我的数据库是在SQL Server中设计的,我想在asp.net,LINQ,C#中获得输出
I have 2 tables linked to 1 table (1:1) 我有2个表链接到1个表(1:1)
My question is can I get a primary key linked to which table? 我的问题是可以获取链接到哪个表的主键吗?
For example: 例如:
What is the best way to know ID
in tbl_Document
linked to which table? 知道链接到哪个表的tbl_Document
ID
的最佳方法是什么?
I can add record in tbl_Document
as 'whichTable' and write the name of table in every column, and every time I want to search set "if" and check 'WhichTable'. 我可以在tbl_Document
中将记录添加为“ whichTable”,并在每列中以及每次我要搜索集合“ if”并检查“ WhichTable”时写表的名称。
Is there a better way to do that? 有更好的方法吗?
Thanks, and sorry for my bad English :) 谢谢,对不起我的英语不好:)
By default, you can get only all tables that have foreign key constraints to the parent table: 默认情况下,您只能获取对父表具有外键约束的所有表:
select object_name(f.referenced_object_id) pk_table, c1.name pk_column_name,
object_name(f.parent_object_id) fk_table, c2.name fk_column_name
from
sys.foreign_keys f
join sys.columns c1 on c1.object_id = f.referenced_object_id
join sys.columns c2 on c2.object_id = f.parent_object_id
join sys.foreign_key_columns k
on (k.constraint_object_id = f.object_id
and c2.column_id = k.parent_column_id
and c1.column_id = k.referenced_column_id )
where object_name(f.referenced_object_id) ='tbl_Document'
There is no such additional information regarding every particular row in parent table. 没有有关父表中每个特定行的此类附加信息。 It would be a duplicate information (since you can figure out it by searching in every child table). 这将是重复的信息(因为您可以通过在每个子表中进行搜索来找出它)。 Thus, as you mentioned you can store child table name in the additional column and then as an option, construct sql dynamically to query child row. 因此,如前所述,您可以将子表名称存储在附加列中,然后作为一种选择,动态构造sql以查询子行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.