I have this business table
ref_ID name parent_id
-----------------------------
ABC-0001 Amb NULL
PQR-899 boss NULL
tgv-632 pick NULL
I want to update parent_id
which is stored in another table parent_customer
.
parent_customer
table lists a hierarchy of data in which when both ref_id
and parent_id
are the same means it's the parent of the entire hierarchy.
For example:
4 PQR-899 PQR-899 this is ultimate parent of hierarchy
parent_customer
ID ref_id parent_id
---------------------------
1 ABC-0001 opr-656
2 opr-656 ttK-668
3 ttK-668 ttK-668
4 PQR-899 PQR-899
5 kkk-565 AJY-567
6 AJY-567 UXO-989
7 UXO-989 tgv-632
8 tgv-632 mnb-784
9 mnb-784 qwe-525
10 qwe-525 qwe-525
match_table_CM
:
id main_id
--------------
1 opr-656
2 PQR-899
3 tgv-632
4 mnb-784
You have to first match business table ref_id
with parent_customer
's ref_id
, and get the parent_id
and check if that parent id is in match_table_CM
( main_id
), then update it with business table parent_id
. Otherwise find the next parent check with main table. If all not found update it with last parent id.
For example: let's take ABC-0001
from business table, its parent_id
is NULL; check with parent_customer
table's ref_id
column, find the 1st record with parent_id = opr-656
, then check with if that id exists in table match_table_CM
( 1 opr-656
) - yes - then update business table ( parent_id
) other wise check the next parent_customer hierarchy match parent_id ttK-668 check with match_table ... till you reach the top.(Exit when 1st match found and move to next id from business table )
You can write your update like following.
update t
set t.parent_id = pc.parent_id
from [yourtble] t
inner join parent_customer pc on pc.ref_id = t.ref_id
where exists
(
select 1
from match_table_cm
where main_id= pc.parent_id )
Please try below one. It will be helpful to you.
UPDATE bus
SET bus.parent_id = pc.ID
FROM tbl_buss bus
inner join parent_customer pc on pc.ref_id = bus.ref_id
inner join match_table_CM mt on mt.main_id = pc.parent_id
Thanks, Amit Prajapati
Try this...
UPDATE bt
SET bt.parent_id = pc.parent_id
FROM businesstable bt
INNER JOIN parent_customer pc ON pc.ref_id = bt.ref_id
INNER JOIN match_table_cm mt ON mt.main_id = pc.parent_id
Output
+------------+------+------------+
| ref_ID | name | parent_id |
+------------+------+------------+
| ABC-0001 | Amb | opr-656 |
| PQR-899 | boss | PQR-899 |
| tgv-632 | pick | mnb-784 |
+------------+------+------------+
Online Demo: http://rextester.com/FAENX59383
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.