Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle Update statement with an Inner Join

I am trying to write a simple update statement with an inner join, but the way I would do this in SQL server does not seem to be working in ORACLE. Here is the Update:

UPDATE D
SET D.USER_ID = C.USER_ID
FROM D INNER JOIN C 
ON D.MGR_CD = C.MGR_CD WHERE D.USER_ID IS NULL;

It seems like the error I am getting is on the FROM. Can someone explain to meet what the cause of this is and how to work around it?

like image 926
esastincy Avatar asked Oct 05 '11 16:10

esastincy


People also ask

Can we use inner join in UPDATE statement in Oracle?

The answer is pretty straightforward: in Oracle this syntax of UPDATE statement with a JOIN is not supported.

How use inner join in UPDATE statement?

SQL UPDATE JOIN could be used to update one table using another table and join condition. UPDATE tablename INNER JOIN tablename ON tablename. columnname = tablename.

Can I use join in UPDATE statement?

The most easiest and common way is to use join clause in the update statement and use multiple tables in the update statement. Here we can see that using join clause in update statement. We have merged two tables by the use of join clause.

How do you UPDATE data when joining two tables?

To UPDATE a table by joining multiple tables in SQL, let's create the two tables 'order' and 'order_detail. ' We can update the data of a table using conditions of other joined tables. It is possible to join two or more tables in an UPDATE query.


1 Answers

In Oracle, you can't use a from clause in an update statement that way. Any of the following should work.

UPDATE d
SET    d.user_id   =
          (SELECT c.user_id
           FROM   c
           WHERE  d.mgr_cd = c.mgr_cd)
WHERE  d.user_id IS NULL;

UPDATE (SELECT d.user_id AS d_user_id, c.user_id AS c_user_id
        FROM   d INNER JOIN c ON d.mgr_cd = c.mgr_cd
        WHERE  d.user_id IS NULL)
SET    d_user_id   = c_user_id;

UPDATE (SELECT d.user_id AS d_user_id, c.user_id AS c_user_id
        FROM   d INNER JOIN c ON d.mgr_cd = c.mgr_cd)
SET    d_user_id   = c_user_id
WHERE  d_user_id IS NULL;

However, my preference is to use MERGE in this scenario:

MERGE INTO d
USING      c
ON         (d.mgr_cd = c.mgr_cd)
WHEN MATCHED THEN
    UPDATE SET d.user_id = c.user_id
        WHERE      d.user_id IS NULL;
like image 135
Allan Avatar answered Oct 12 '22 13:10

Allan