Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update with two tables?

Tags:

sql

sql-server

I am trying to update table A with data from table B. I thought I could do something like:

 UPDATE A  SET A.name = B.name  WHERE A.id = B.id 

but alas, this does not work.

Anyone have an idea of how I can do this?

like image 439
Md Nasir Uddin Avatar asked Jul 01 '09 10:07

Md Nasir Uddin


People also ask

Can we update two tables at once?

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. and T1.id = '011008';

Is it possible to update two tables in SQL?

In SQL, there is a requirement of a single query/statement to simultaneously perform 2 tasks at the same time. For instance, updating 2 different tables together in a single query/statement. This involves the use of the BEGIN TRANSACTION clause and the COMMIT clause.

Can you update data in two base tables of a view with a single update statement?

Updating a View The UPDATE statement can only reference columns from one base table. This means it's not possible to update multiple tables at once using a single UPDATE statement.


1 Answers

Your query does not work because you have no FROM clause that specifies the tables you are aliasing via A/B.

Please try using the following:

UPDATE A     SET A.NAME = B.NAME FROM TableNameA A, TableNameB B WHERE A.ID = B.ID 

Personally I prefer to use more explicit join syntax for clarity i.e.

UPDATE A     SET A.NAME = B.NAME FROM TableNameA A     INNER JOIN TableName B ON          A.ID = B.ID 
like image 143
John Sansom Avatar answered Sep 29 '22 09:09

John Sansom