How to determine which columns are shared between two tables?

后端 未结 8 1361
时光取名叫无心
时光取名叫无心 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:00

    Use the INFORMATION_SCHEMA.COLUMNS like this:

    IF OBJECT_ID('Table1') IS NOT NULL DROP TABLE Table1
    IF OBJECT_ID('Table2') IS NOT NULL DROP TABLE Table2
    GO
    CREATE TABLE Table1 (
        a INT
      , b INT
      , c INT
      , d INT
      , e INT
      , f INT
    )
    
    CREATE TABLE Table2 (
        c INT
      , d INT
      , e INT
      , f INT
      , g INT
      , h INT
      , i INT
    )
    
    GO
    
    SELECT t1.COLUMN_NAME 
    FROM        INFORMATION_SCHEMA.COLUMNS AS t1 
    INNER JOIN  INFORMATION_SCHEMA.COLUMNS AS t2 ON t1.COLUMN_NAME = t2.COLUMN_NAME 
    WHERE t1.TABLE_NAME = 'Table1' AND t2.TABLE_NAME = 'Table2'
    

    -- OUTPUT

    COLUMN_NAME
    c
    d
    e
    f
    

提交回复
热议问题