如何比较不同数据库中不同表的两列?

How do I compare two columns from different tables in different databases?

假设我在 Database_1 中有 Table_1,有 25 列 并说我在 Database_2 中有 19 列的 Table_2 我想比较 Table_1Table_2 中的列,并输出存在于 Table_1 但不存在于 Table_2

中的列

我试过了

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME='Table_1'
EXCEPT
SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME='Table_2'

问题是:如果我在 Database_1 它只在 Table_1 和 return 空列表中找到 Table_2 的变量,如果我在 [=28] =] 它只在 Table_2 和 return 的 Table_1 的空列表中找到变量。如果说我在 Master,它 return 是 Table_1 和 Table_2 的空列表。如何从一个数据库中正确定位每个 table 及其变量?

您可以通过以 database.schema.object 的形式完全限定对象名称,从任何数据库 context 访问任何数据库对象.

使用 SQL 服务器你最好使用 sys 模式,它(如果性能很重要)比使用 information_schema 架构。

所以你可以做到

select name
from database_1.sys.columns
where object_id=object_id(N'database_1.sys.table_1')
except
select name
from database_2.sys.columns
where object_id=object_id(N'database_2.sys.table_2')