Is it possible to update self referencing parent id with Update From query.
Tables I have
Acc
AccID Name ParentAccID AccNumber
01 A Null A001
02 B Null A002
03 C Null A003
04 D Null A004
05 E Null A005
AccRef
AccNumber MasterAcc Name
A001 A001 A
A002 B
A003 A002 C
A004 A005 D
A005 A009 E
the way it should be joined is with AccNumber and then need to updat AccID in ParentAccID based on MasterAcc of that Acc. Only for existing AccNumber and if AccNumber and MasterAcc is not same (sorry if its big confusing)
Result table should look like
Acc
AccID Name ParentAccID AccNumber
01 A Null A001
02 B Null A002
03 C 02 A003
04 D 05 A004
05 E Null A005
Thanks
Try this,
DECLARE @Acc Table (AccID varchar(10),Name varchar(200),ParentAccID varchar(200), AccNumber varchar(200))
Insert into @Acc Values
('01','A',Null,'A001'),
('02','B',Null,'A002'),
('03','C',Null,'A003'),
('04','D',Null,'A004'),
('05','E',Null,'A005')
DECLARE @AccRef Table (AccNumber varchar(10),MasterAcc varchar(200),Name varchar(200))
Insert into @AccRef Values
('A001','A001','A'),
('A002',Null,'B'),
('A003','A002','C'),
('A004','A005','D'),
('A005','A009','E')
Update A set ParentAccID = M.AccID From @Acc A
Inner Join @AccRef R on R.AccNumber = A.AccNumber and R.AccNumber <> R.MasterAcc
Inner Join @Acc M on M.AccNumber = R.MasterAcc
Hope this is what you are looking for.
Finally,
Select * from @Acc
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.