查找多个表之间的公共列

Finding common columns between multiple tables

我有数百个表格,每个表格包含 400 多列。 我想找到这些表之间的公共列的名称。 我该怎么做。我在网上找到了一个有效的代码,但只适用于较少数量的表格。 当我 运行 在我的案例中查询时,我收到以下错误--> 'The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.'

这里是查询:

insert into temp_table 
  select column_name from information_schema.columns where table_name = 'test_datajuly17' 
  intersect select column_name from information_schema.columns where table_name = 'test_datajuly20' 
  intersect select column_name from information_schema.columns where table_name = 'test_datajuly21'

如有任何帮助,我们将不胜感激。 谢谢

您可以执行如下操作。

如果您知道要与之比较的 table,请将 table 名称放入临时 table (@TEMPTABLE),然后执行以下操作

DECLARE @TEMPTABLE AS TABLE
(
    TableName VARCHAR(32)
)

INSERT INTo @TEMPTABLE
VALUES
('spt_fallback_dev'), --test names
('spt_values')



SELECT fulllist.*
FROM INFORMATION_SCHEMA.COLUMNS fulllist
INNER JOIN @TEMPTABLE baseCmp on baseCmp.TableName = fulllist.TABLE_NAME
INNER JOIN
    ( SELECT COLUMN_NAME
      FROM INFORMATION_SCHEMA.COLUMNS isc
      INNER JOIN @TEMPTABLE tt on tt.TableName = isc.TABLE_NAME
      GROUP BY COLUMN_NAME
      HAVING COUNT(*) > 1) temp on temp.COLUMN_NAME = fulllist.COLUMN_NAME
ORDER BY COLUMN_NAME

然后你可以对结果做各种事情(比如旋转它等)

下面的查询做的事情完全一样。所以你不需要内部和外部查询。

SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS isc
  INNER JOIN @TEMPTABLE tt on tt.TableName = isc.TABLE_NAME
  GROUP BY COLUMN_NAME
  HAVING COUNT(*) > 1
  ORDER BY COLUMN_NAME