Share via

Merge 2 SQL DB dissimilar Tables

Mike Kiser 1,536 Reputation points
2021-03-29T01:44:10.09+00:00

Hi!
I have 2 tables that I am trying to merge. The schedule is a little different with each Table. I just tried:

SELECT ControlRec FROM MercerReportTable
UNION ALL
SELECT * FROM MercerReportTableMod;

which produced the following error:
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

Does anyone know how to merge 2 different Tables in schema? I have googled but only see the UNION, UNION ALL etc which is for 2 similar tables.

Thanks so much!
Mike Kiser

Azure SQL Database
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.


1 answer

Sort by: Most helpful
  1. MelissaMa-msft 24,246 Reputation points Moderator
    2021-03-29T01:53:01.027+00:00

    Hi @Mike Kiser ,

    While using UNION, INTERSECT or EXCEPT operator, you have to ensure that they have same numbers of columns from different tables.

    Suppose MercerReportTableMod has the same column ControlRec , you could refer below:

    SELECT ControlRec FROM MercerReportTable  
    UNION ALL  
    SELECT ControlRec FROM MercerReportTableMod;  
    

    Or you could list all columns and define them as NULL or '' as below:

    SELECT ControlRec,NULL col1,NULL col2,NULL col3  FROM MercerReportTable  
    UNION ALL  
    SELECT ControlRec,col1,col2,col3 FROM MercerReportTableMod;  
    

    Or:

    SELECT ControlRec,NULl col1,NULL col2,NULL col3  FROM MercerReportTable  
    UNION ALL  
    SELECT NULL ControlRec,col1,col2,col3 FROM MercerReportTableMod;  
    

    If above are not working,we recommend that you post CREATE TABLE statements for your tables together with INSERT statements with sample data, enough to illustrate all angles of the problem. We also need to see the expected result of the sample.

    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.