How to determine which columns are shared between two tables?

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

    You can find data like this in the INFORMATION_SCHEMA tables. Technically those are more standardized than the sys views. (See this question.)

    Here's a query you could use:

    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'
    

    If you need to specify the schema to avoid name collisions, add A.TABLE_SCHEMA = 'dbo' etc to the where clause.

提交回复
热议问题