Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update multiple tables with single query

Tags:

sql

sql-server

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

like image 354
Dardar Avatar asked Jun 18 '15 12:06

Dardar


People also ask

Can we update multiple tables in single query?

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.

How can I update multiple tables in a single query in SQL?

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.

Can multiple tables be updated using update command?

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.


2 Answers

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);
like image 84
Gordon Linoff Avatar answered Nov 14 '22 00:11

Gordon Linoff


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
like image 40
Simone Avatar answered Nov 13 '22 23:11

Simone