match the columns in with 2 tables

Shambhu Rai 1,406 Reputation points
2023-03-13T09:16:13.13+00:00

HI Expert,

I am comparing 2 tables in with all column match and un match

i.e.

create table Table1(col1 int,col2 int,col3 int,col4 int)

create table Table2(col1 int,col2 int,col3 int,col4 int)

insert into Table1 (2,3,4,5)

insert into Table1 (6,7,8,9)

insert into Table2 (2,3,4,5)

insert into Table2 (6,5,8,9)

expected output1 Matched

User's image

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,760 questions
0 comments No comments
{count} votes

Accepted answer
  1. PercyTang-MSFT 12,426 Reputation points Microsoft Vendor
    2023-03-13T09:29:21.9066667+00:00

    Hi @Shambhu Rai

    Matched:

    ;with T1 as(
      select * from table1
      INTERSECT 
      select * from table2)
    select * from T1
    union all 
    select * from T1;
    

    Output:

    User's image

    Un Matched:

    ;with T1 as(
      select * from table1
      except 
      select * from table2
    ),T2 as(
      select * from table2
      except 
      select * from table1)
    select * from T1
    union all
    select * from T2;
    

    Output:

    User's image

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".

    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

0 additional answers

Sort by: Most helpful