Skip to Main Content
  • Questions
  • Insert into table A from table B based on specific conditions

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Aryan.

Asked: July 20, 2020 - 11:40 pm UTC

Last updated: July 22, 2020 - 1:50 pm UTC

Version: 11g

Viewed 1000+ times

You Asked

Hi Tom,

I have a question as to how data can be inserted from Table B to Table A based on specific conditions.

For E.g, say Table A has EmpId, DepId, SalFreq, TotPaychecks and
Table B has EmpId, DepId, Freq, Pay

create table A (
  EmpId number(18,0),
  DepId number(10,0),
 SalFreq varchar2(32),
  TotPaychecks number(3,0)
);

create table B (
  EmpId number,
  DepId number,
 Freq varchar2(2),
 Pay number(3)
);

insert into A values(1, 1, 'Monthly',12);
insert into A values(2, '1', 'Biweekly',26);
insert into A values(3, '2', 'Fortnightly',24);

insert into B values(4, '2',null,null);
insert into B values(5, '3', null,null);
insert into B values(6, '3', F,12);





If A.EmpId != B. EmpId AND B.DepId !=null,
Then insert a row in A, B.EmpId, B.DepId, if B.Freq=null then A.SalFreq = Monthly, if B.Pay=null then A.TotPaychecks=12
else insert a row in A, B.EmpId, B.DepId A.SalFreq=B.Freq, A.TotPaychecks=B.Pay

After snapshot of the table.
select * from A;

     EmpId  DepId        SalFreq    TotPayChecks
----------  ----------  ---------   --------------
         1          1                 Monthly        12
         2         1                 Biweekly        26
         3         2                Fortnightly    24
         4         2                Monthly         12
         5         3                Monthly          12
         6         3                Fortnightly     24


Thanks,
Aryan

and Chris said...

I'm unclear how the logic relates the desired output. The principle is the same in any case:

- Select the rows from B where not exists a matching row in A
- Use a case expression to manipulate the freq/pay values as needed.

For example:

select empid, depid,
       case
         when b.freq is null then 'Monthly'
         else b.freq
       end freq,
       case
         when b.pay is null then 12
         else b.pay
       end pay
from   b
where  not exists (
  select * from a 
  where  b.empid = a.empid
);

EMPID    DEPID    FREQ       PAY   
       6        3 F              12 
       4        2 Monthly        12 
       5        3 Monthly        12 


Insert the result of this ( insert .. select ), adjusting the case expressions as needed.

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Aryan, July 22, 2020 - 6:08 pm UTC


More to Explore

SQL

The Oracle documentation contains a complete SQL reference.