如何从多个表中获取公共列

时间:2011-11-05 18:31:39

标签: c# sql sql-server stored-procedures

在我的一个应用程序中,我需要获取表格的常用列。从 NorthWind 数据库中选择我有两个表订单和订单详细信息 ,需要得到那些表的公共列像:OrderID.Is有任何sp或机制或脚本谁可以为我做这个.IF有任何想法PLZ与我分享。如果有任何查询PLZ问,提前谢谢

1 个答案:

答案 0 :(得分:2)

这对我来说找到了同名的列。

select a.column_name 
from information_schema.columns a
join information_schema.columns b on a.column_name = b.column_name and b.table_name = 'table1'
where a.table_name = 'table2'

要获得有关订单的FK信息,请使用:

DECLARE @tab int

SELECT @tab = object_id FROM sys.tables WHERE NAME = 'order'

SELECT t.name as [Table], fkc.constraint_column_id, c.name as [Column] 
FROM sys.foreign_key_columns as fkc
INNER JOIN sys.tables as t on fkc.parent_object_id = t.object_id
INNER JOIN sys.columns as c on fkc.parent_object_id = c.object_id and fkc.parent_column_id = c.column_id
WHERE fkc.referenced_object_id = @tab