Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question.

Asked: February 20, 2017 - 11:31 am UTC

Last updated: February 22, 2017 - 1:24 am UTC

Version: 11.2

Viewed 1000+ times

You Asked

Hi Chris/Connor,
Please have a look at below scenario -

Table
-----
tb_temp_0001

Columns
-------
order_id number -- PK
cust_fname
cust_lname
dob
address_1
address_2
address_3
debit_amnt
credit_amnt


Table
-----
tb_app_0001

Columns
-------
order_id number -- PK
cust_fname
cust_lname
dob
address_1
address_2
address_3
debit_amnt
credit_amnt

tb_app_fields
-------------
order_id
fields_chaged
modified_by
modified_on


data from load table i.e. tb_temp_0001 is loaded into actual table tb_app_0001.
I need to populate table tb_app_fields by comparing load table and application table
e.g.

For each row in tb_temp_0001 -
compare it with application table tb_app_0001 (tb_temp_0001.order_id = tb_app_0001.order_id)
Out of 8 columns, lets say only 4 columns(dob,address_1,address_2,address_3) we are going to update by comparing each column
e.g. if tb_temp_0001.dob != tb_app_0001.dob then update tb_app_0001.dob
if tb_temp_0001.address_1 != tb_app_0001.address_1 then update tb_app_0001.address_1
..

based on above comparision I need to populate table tb_app_fields like
order_id fields_chaged modified_by modified_on
-------- ------------- ----------- -----------
100001 dob,address_1,address_2,address_3 user 1 sysdate


Can you please suggest any better approach to do this to avoid if then else..

and Connor said...

merge into TB_APP a
  using ( select * from TB_TEMP ) t
   on (  a.PK_COL1  = t.PK_COL1
     and a.PK_COL2  = t.PK_COL2  -- ie, primary key columns
     and ...
     )
  when matched then
  update set
    a.COL1 = t.COL1,
    a.COL2 = t.COL2,
    ...
    a.FIELDS_MODIFIED = 
        decode(a.COL1,t.COL1,'','col1,')||
        decode(a.COL1,t.COL2,'','col2,')||
        decode(a.COL1,t.COL3,'','col3,')||
        decode(a.COL1,t.COL4,'','col4,')
       ...
  where   decode(t.COL1,a.COL1,1,0) = 0
     or   decode(t.COL2,a.COL2,1,0) = 0
     or   decode(t.COL3,a.COL3,1,0) = 0
     or   decode(t.COL4,a.COL4,1,0) = 0
     or   decode(t.COL5,a.COL5,1,0) = 0
     ...
     
     


Rating

  (1 rating)

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

Comments

Perfect!! Just what I needed!!

A reader, February 21, 2017 - 5:11 pm UTC

Thanks a lot Connor!!
Connor McDonald
February 22, 2017 - 1:24 am UTC

Glad we could help