我们如何在SQL Server中选择不常用的列

时间:2014-11-20 06:08:12

标签: sql sql-server sql-server-2008 sql-server-2012

我想从两个表中选择所有列,让我们说表A和表B,其中A的列名不等于B的列名。我试图找到一个解决方案,但我找到的是如何获得常见的列。

select A.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS A
join INFORMATION_SCHEMA.COLUMNS B
on A.COLUMN_NAME = B.COLUMN_NAME
where A.TABLE_NAME = 'table1'
and B.TABLE_NAME = 'table2'

我不希望所有这些列都出现,其名称很常见,但是希望所有其他列的名称不相同。

2 个答案:

答案 0 :(得分:1)

在where子句中使用相关的not exists来获取Table2中Table2中不存在的列。

select A.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS as A
where A.TABLE_NAME = 'Table1' and
      not exists (
                 select *
                 from INFORMATION_SCHEMA.COLUMNS as B
                 where A.COLUMN_NAME = B.COLUMN_NAME and
                       B.TABLE_NAME = 'Table2'
                 )

要从两个表中获取列,您可以使用上述查询两次,并将结果与​​union all合并。

select A.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS as A
where A.TABLE_NAME = 'Table1' and
      not exists (
                  select *
                  from INFORMATION_SCHEMA.COLUMNS as B
                  where A.COLUMN_NAME = B.COLUMN_NAME and
                        B.TABLE_NAME = 'Table2'
                     )
union all
select A.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS as A
where A.TABLE_NAME = 'Table2' and
      not exists (
                  select *
                  from INFORMATION_SCHEMA.COLUMNS as B
                  where A.COLUMN_NAME = B.COLUMN_NAME and
                        B.TABLE_NAME = 'Table1'
                     )

或者您可以将exceptunion all一起使用。

select COLUMN_NAME
from (
     select COLUMN_NAME
     from INFORMATION_SCHEMA.COLUMNS
     where TABLE_NAME = 'Table1'
     except
     select COLUMN_NAME
     from INFORMATION_SCHEMA.COLUMNS as A
     where TABLE_NAME = 'Table2'
     ) as C
union all
select COLUMN_NAME
from (
     select COLUMN_NAME
     from INFORMATION_SCHEMA.COLUMNS
     where TABLE_NAME = 'Table2'
     except
     select COLUMN_NAME
     from INFORMATION_SCHEMA.COLUMNS as A
     where TABLE_NAME = 'Table1'
     ) as C

答案 1 :(得分:1)

;WITH A AS(
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'table1'
),
B AS(
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'table2'
)
SELECT A.COLUMN_NAME FROM A
LEFT OUTER JOIN B
ON A.COLUMN_NAME = B.COLUMN_NAME
WHERE B.COLUMN_NAME IS NULL
UNION ALL
SELECT B.COLUMN_NAME FROM A
RIGHT OUTER JOIN B
ON A.COLUMN_NAME = B.COLUMN_NAME
WHERE A.COLUMN_NAME IS NULL