Search code examples
sql-serverdatabasejoinmergerdbms

Merge tables having different columns (SQL Server)


I have 2 tables with details as follows

Table 1

Name | City | Employee_Id
-----------------
Raj  | CA   | A2345
Diya | IL   | A1234
Max  | PL   | A2321
Anna | TX   | A1222
Luke | DC   | A5643

Table 2

Name | City | Employee_Id | Phone | Age
---------------------------------------
Raj  | CA   | A2345       | 4094  | 25
Diya | IL   | A1234       | 4055  | 19
Max  | PL   | A2321       | 4076  | 23

As you can see, Employee_Id is the common column in both the columns. I want to update all the entries present in table 1 into table 2.

Raj, Divya and Max are already present in Table 2. So it should not create a duplicate entry in table 2 and skip those 3 entries whereas Anna and Luke are not present in table 2. so this should be added as a new row.

The SQL should be able to merge these 2 columns and ignore the rows which are already present. The final table 2 must be similar to this.

Table 2

Name | City | Employee_Id | Phone | Age
---------------------------------------
Raj  | CA   | A2345       | 4094  | 25
Diya | IL   | A1234       | 4055  | 19
Max  | PL   | A2321       | 4076  | 23
Anna | TX   | A1222       |       |   
Luke | DC   | A5643       |       |   

Is there a way I could achieve this? I am pretty new to SQL, so any inputs would be of great help. I read about merge and update feature but I guess merge is in Transact-SQL. Also read about joins but could not find a way to crack this.


Solution

  • Demo Setup

    CREATE TABLE Table1
        ([Name] varchar(4), [City] varchar(2), [Employee_Id] varchar(5));
    
    INSERT INTO Table1
        ([Name], [City], [Employee_Id])
    VALUES
        ('Raj', 'FL', 'A2345'),
        ('Diya', 'IL', 'A1234'),
        ('Max', 'PL', 'A2321'),
        ('Anna', 'TX', 'A1222'),
        ('Luke', 'DC', 'A5643');
    
    CREATE TABLE Table2
        ([Name] varchar(4), [City] varchar(2), [Employee_Id] varchar(5), [Phone] int, [Age] int);
    
    INSERT INTO Table2
        ([Name], [City], [Employee_Id], [Phone], [Age])
    VALUES
        ('Raj', 'CA', 'A2345', 4094, 25),
        ('Diya', 'IL', 'A1234', 4055, 19),
        ('Max', 'PL', 'A2321', 4076, 23);
    

    MERGE QUERY

    MERGE Table2 AS target
        USING Table1 AS source 
        ON (target.[Employee_Id] = source.[Employee_Id])
        WHEN MATCHED THEN 
            UPDATE SET [Name] = source.[Name],
                       [City] = source.[City]
    WHEN NOT MATCHED THEN
        INSERT ([Name], [City], [Employee_Id], [Phone], [Age])
        VALUES (source.[Name], source.[City], source.[Employee_Id], NULL, NULL);
    
    SELECT *
    FROM Table2