How to determine which columns are shared between two tables?

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

    This could well indicate a fundamental design issue but to find column names shared by both tables a couple of options would be

    SELECT name 
    FROM sys.columns 
    WHERE object_id IN (object_id('dbo.Table1'),
                        object_id('dbo.Table2'))
    GROUP BY name
    HAVING COUNT(*) = 2
    

    Or

    SELECT name 
    FROM sys.columns 
    WHERE object_id = object_id('dbo.Table1')
    INTERSECT
    SELECT name 
    FROM sys.columns 
    WHERE object_id = object_id('dbo.Table2')
    

提交回复
热议问题