首页 > 解决方案 > 有没有一种简单的方法来比较 SQL Server 中两个表之间的列名?

问题描述

我正在使用 SQL Server 中的两个非常广泛、非常相似的表。一个表中存在 5-10 列,但另一个表中不存在。有没有一种简单的方法可以找出一个表中存在哪些列但另一个表中不存在哪些列?

标签: sqlsql-server

解决方案


使用information_schema.columns. 这是一种带有 a 的方法full outer join

select c1.column_name, c2.column_name
from (select c.*
      from information_schema.columns
      where table_name = @table1 and table_schema = @schema1
     ) c1 full outer join
     (select c.*
      from information_schema.columns
      where table_name = @table2 and table_schema = @schema2
     ) c2
     on c1.column_name = c2.column_name
where c1.column_name is null or c2.column_name is null

推荐阅读