Select 个名称不在另一个 table 中的列

Select columns whose name is not present in another table

有没有办法只 select 名称不在另一个 table 上的列?例如

Table A                         Column B
ID  | Name   | Address          Address
-----------------------
1   | Daniel | dummy

在这个例子中,我的 select 语句应该是这样的:

select ID, Name from Column A

我看到有人在谈论动态 SQL 但我找不到合适的例子来解决我的问题,非常感谢任何帮助。

Select WHERE 子句中的另一个 table。

SELECT ID, NAME
FROM ColumnA
WHERE NAME NOT IN (SELECT NAME FROM COLUMNB)

这是您使用动态 SQL:

执行此操作的方式的一个版本
declare @cols varchar(max);
set @cols = NULL;

select @cols = coalesce(@cols + ', ' + column_name, column_name)
from information_schema.columns ca 
where ca.table_name = 'A' and
      ca.column_name not in (select cb.column_name
                             from information_schema.columns cb
                             where cb.table_name = 'B'
                            );

declare @sql varchar(max);
set @sql = 'select [cols] from A';
set @sql = replace(@sql, '[cols]', @cols);

exec sp_executesql @sql;

这有点简化,以显示如何起诉 information_schema 表格。它适用于许多情况,但不是最通用的:

  • 它不考虑架构名称。
  • 它假定所有名称都是简单的 ASCII。
  • 它不转义列名(假设不需要转义名称)。