Table1:
BrID HQID
------------
Br1 HQ1
HQ1
HQ2
Br2 HQ1
Br3 HQ2
Table2:
ID Name BrID IDt2
------------------------------
11 OthName11 Br1
22 HQName111 HQ1
33 HQName222 HQ2
44 OthName22 Br2
55 OthName33 Br3
I need to UPDATE Table2.IDt2 for each row from Table1 which has HQID value but with Table2.ID connected by Table1.HQID = Table2.BrID
In other words fro the first row .
SELECT HQID FROM Table1 WHERE BrID = 'Br1'
SELECT ID WHERE Table2.BrID = HQID (from previous SELECT)
UPDATE Table2 SET IDt2 = ID(from previous SELECT) WHERE Table2.BrID = 'Br1' (from first SELECT)
This should be the result Table2:
ID Name BrID IDt2
------------------------------
11 OthName11 Br1 22
22 HQName111 HQ1
33 HQName222 HQ2
44 OthName22 Br2 22
55 OthName33 Br3 33
Is it possible to make it in one UPDATE?
How else can I do this?
You just need multiple JOIN
statements:
UPDATE a
SET a.IDT2 = c.ID
FROM Table2 a
JOIN Table1 b
ON a.BRID = b.BRID
JOIN TAble2 c
ON b.HQID = c.BRID
Demo: SQL Fiddle
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments