How to determine which columns are shared between two tables?

后端 未结 8 1201
时光取名叫无心
时光取名叫无心 2021-02-01 09:10

Very new to SQL Sever here... I understand the concept of joining tables, etc. but what is the easiest way to determine which columns are shared?

Say for instance we ha

8条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 10:02

    IF OBJECT_ID('tempdb..#Table1') IS NOT NULL DROP TABLE #Table1
    IF OBJECT_ID('tempdb..#Table2') IS NOT NULL DROP TABLE #Table2
    
    
    SELECT      COLUMN_NAME AS 'ColumnName'
                ,TABLE_NAME AS  'TableName'
    INTO        #Table1
    FROM        INFORMATION_SCHEMA.COLUMNS
    WHERE       TABLE_NAME = 'TABLE_NAME1'
    ORDER BY    TableName
                ,ColumnName;
    
    SELECT      COLUMN_NAME AS 'ColumnName'
                ,TABLE_NAME AS  'TableName'
    INTO        #Table2
    FROM        INFORMATION_SCHEMA.COLUMNS
    WHERE       TABLE_NAME = 'TABLE_NAME2'
    ORDER BY    TableName
                ,ColumnName;
    
    SELECT #Table1.ColumnName
    FROM #Table1
    JOIN #Table2 ON #Table1.ColumnName = #Table2.ColumnName
    

提交回复
热议问题