J Doe
J Doe

Reputation: 359

Combining two tables using MERGE

I am trying to combine two tables vertically

table A

ID   Salary                        
A        50                              
B       100

table B

ID   Salary
C        50
D       200

I am trying get a table that looks like

ID   Salary
A        50                     
B       100
C        50
D       200

I am using this:

merge into table_a a using (
  select id, salary from table B
) b
on (a.id = b.id);

This is not working.

Upvotes: 0

Views: 4290

Answers (3)

Ebrahim Salehi
Ebrahim Salehi

Reputation: 21

I implement some steps here, you can follow each of them

Step 1 : I create 2 tables “table_a” and “table_b”

create table table_a(ID varchar2(10),salary number(10));

create table table_b(ID varchar2(10),salary number(10));

Step 2: fill them with data:

insert into table_a(id,salary) values ('A',50);
insert into table_a(id,salary) values ('B',100);

insert into table_b(id,salary) values ('C',50);
insert into table_b(id,salary) values ('D',200);

Step 3: the merge statement here, Be careful you have to use statement “when matched then“

merge into table_a a
using table_b b
on (a.id = b.id)
when matched then
  update set a.salary = b.salary
when not matched then
  insert (id, salary) values (b.id, b.salary);

Upvotes: 0

XING
XING

Reputation: 9886

Your Merge syntax is not correct. See below. Read more about Merge Here

MERGE INTO Table_a a
     USING (SELECT Id, Salary FROM TABLE B) b
ON a.id = b.id
when not matched then
insert 
(id,salary) 
values
(b.id,b.salary);

Upvotes: 2

Ayaz
Ayaz

Reputation: 2131

Use Union or union all

SELECT Id, Salary FROM TableA

UNION

SELECT Id, Salary FROM TableB

Upvotes: 0

Related Questions