How to determine which columns are shared between two tables?

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

    To know if you have similar columns could potentially be trickier than the other solutions suggest. We might think that two columns are the same because they share the same name but in reality when you work in a large database with more than one person creating, removing, and/or changing the data structure inconsistencies can happen.

    The more parameters we check for likeness the more confident we can be that our columns are similar without manual inspection of raw data.

    1. First, I suggest you run a query to understand the parameters of a given column.

    SELECT 
        *
    FROM 
        DATABASENAME.INFORMATION_SCHEMA.COLUMNS
    WHERE 
        TABLE_NAME = N'TABLE1'
    

    This will return several columns of meta data on the columns in the table. Some of the meta data I found interesting for uniqueness included...

    2. In my case I have identified the column attributes of COLUMN_NAME, IS_NULLABLE, AND DATA_TYPE to determine if my columns truly match.

    SELECT 
        DISTINCT A.COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS A
        LEFT join INFORMATION_SCHEMA.COLUMNS B 
            ON A.COLUMN_NAME = B.COLUMN_NAME 
            AND A.DATA_TYPE = B.DATA_TYPE
            AND A.IS_NULLABLE = B.IS_NULLABLE
    WHERE 
        A.TABLE_NAME = N'TABLE1'
        AND B.TABLE_NAME = N'TABLE2'
    

    3. Concept Check... Maybe if when we JOIN using only COLUMN_NAME there are 10 matching columns. Maybe when we JOIN using COLUMN_NAME AND DATA_TYPE there are 7 matching columns. Maybe when we use all three conditions as in the example above there are 4 matching columns. Does it mean you can only JOIN on 4 matching columns...absolutely not. What it does mean is you will need to consider how to craft error handling and casting depending on how you intend to JOIN the tables. Point being is be careful performing JOIN on INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME as your results may be far from intended.

提交回复
热议问题