How to determine which columns are shared between two tables?

后端 未结 8 1196
时光取名叫无心
时光取名叫无心 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:03
    select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'Table1'
    
    intersect
    
    select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'Table2'
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题