I have 2 tables that I need to update:
Table A consists of: ID, personName, Date, status
Table B consist of: PersonID, Date, status
For every row in A there can be multiple rows in B with the same personID
I need to "loop" over all results from A that the status=2 and update the date and status to 1.
Also, for every row in A that status=2 I need to update all the rows in B that has the same personID (i.e, A.ID==B.PersonID) – I need to update date and status to 1 as well.
So basically, if I was to do this programmatically (or algorithmically) its's something like that:
Foreach(var itemA in A)
If (itemA.status = 2)
itemA.status to 1
itemA.date = GetDate()
foreach(var itemB in B)
if(itemB.PersonID == itemA.ID && itemB.status != 2 )
Change itemB.status to 1
Change itemB.date = GetDate()
i know how to update all the rows in B using the following sql statement:
UPDATE
B
SET
status = 1,
date = GETDATE()
FROM
B
INNER JOIN
A
ON
B.PersonID = A.ID
the problem is that i don't know how to also update table A since there can't be multiple tables in an update statement
thanks for any help
1 Answer. It's not possible to update multiple tables in one statement, however, you can use the transaction to make sure that two UPDATE statements must be treated atomically. You can also batch them to avoid a round trip like this.
Syntax: BEGIN TRANSACTION; UPDATE TABLE_1 SET TABLE_1. TABLE_1_COLUMN = VALUE_1 FROM TABLE_1 T1, TABLE_2 T2 WHERE T1.ID = T2.ID AND T1.ID = ID_VALUE_1; UPDATE TABLE_2 SET TABLE_2.
The short answer to that is no. While you can enter multiple tables in the from clause of an update statement, you can only specify a single table after the update keyword.
Here is an example using the output
clause:
declare @ids table (id int);
update table1
set status = 1
output inserted.id into @ids
where status = 2;
update table2
set status = 1,
date = getdate()
where personid in (select id from @ids);
Put everything inside a transaction and commit if succeeds
DECLARE @err int
BEGIN TRANSACTION
UPDATE B
SET status = 1, date = GETDATE()
FROM B INNER JOIN A ON B.PersonID = A.ID
WHERE A.status = 2
SET @err = @@ERROR
IF @err = 0
BEGIN
UPDATE A
SET status = 1,
date = GETDATE()
WHERE status = 2
SET @err = @@ERROR
END
IF @err = 0
COMMIT
ELSE ROLLBACK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With