How to determine which columns are shared between two tables?

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

    Here is a handy query you can use to list out columns in a table:

    SELECT c.name ColumnName
    FROM sys.columns c INNER JOIN
         sys.tables t ON c.object_id = t.object_id 
    WHERE t.name = 'something'
    

    And here is a JOIN you could use to find common column names:

    SELECT * 
    FROM  (SELECT c.name ColumnName
            FROM sys.columns c INNER JOIN
                 sys.tables t ON c.object_id = t.object_id 
            WHERE t.name = 'table1'
          )t1
    JOIN (SELECT c.name ColumnName
            FROM sys.columns c INNER JOIN
                 sys.tables t ON c.object_id = t.object_id 
            WHERE t.name = 'table2'
         )t2
    ON t1.ColumnName = t2.ColumnName
    

提交回复
热议问题