UPDATE FROM workaround in Oracle

In table update operations, in many cases it is necessary to reference data other than the table to be updated in the expression. Like sql server provides the from clause of update, you can connect the table to be updated with other data sources. Although only one table can be updated, by connecting the table to be updated with other data sources, other data other than the table to be updated can be referenced in the update expression.
E.g:

UPDATE Table2
SET Table2.ColB = Table2.ColB + Table1.ColB
FROM Table2
INNER JOIN Table1
ON (Table2.ColA = Table1.ColA);

The actual update operation is performed on the table to be updated, not on the new result set formed by the from clause.

Oracle does not have update from syntax, and the same function can be achieved by two writing methods:
1: Subquery UPDATE A SET A.NAME=(SELECT B.NAME FROM B WHERE B.ID=A.ID), this query depends on the specific situation See if the workaround is as follows
(1) Single column
UPDATE A

SET A.NAME=(SELECT B.NAME FROM B WHERE B.ID=A.ID)

WHERE A.ID IN (SELECT ID FROM B);

(2)多列
UPDATE order_rollup

SET(qty,price)=(SELECT SUM(qty),SUM(price) FROM order_lines WHERE customer_id='KOHL' )

WHERE cust_id='KOHL' AND order_period=TO_DATE('01-Oct-2000')

2:利用视图来做
UPDATE (SELECT A.NAME ANAME,B.NAME BNAME FROM A,B WHERE A.ID=B.ID)
SET ANAME=BNAME;

E.g:

UPDATE tablea a
SET a.fieldforupdate = (SELECT b.fieldsource FROM tableb b WHERE a.keyfield = b.keyfield)
WHERE EXISTS (SELECT b.fieldsource FROM tableb b WHERE a.keyfield = b.keyfield)

There are three things to note:

    1. For a given value of a.keyfield, the value of SELECT b.fieldsource FROM tableb b WHERE a.keyfield = b.keyfield can only be a unique value, not multiple values.
    2. In the vast majority of cases, the last where EXISTS clause is important, otherwise you will get wrong results.
    3. Restrictions on view updates:
      If the view is based on a join of multiple tables, then the user's ability to update (update) view records will be limited. A view's base table cannot be updated unless the update involves only one table and the view column contains the entire primary key of the updated table.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324766960&siteId=291194637