Update the data of another table using the data of one table in Oracle

Source: Internet
Author: User

Oracle has the following two tables: update the val value of the row with the same id value in Table tab1 and that in Table tab2 to the val value in table 2.
Select * from tab1;


Select * from tab2

The most common mistake is: update tab1 set val = (select val from tab2 where tab1.id = tab2.id );
The updated result is: select * from tab1, which has rows in tab1. If no corresponding row exists in tab2, the value is updated to null.

Corrected to: update tab1 set val = (select val from tab2 where tab1.id = tab2.id)
Where exists (select 1 from tab2 where tab1.id = tab2.id)
However, if multiple entries in tab2 correspond to one entry in tab1, an error occurs.
The best way is to use merge Syntax:
  1. MergeIntoTab1
  2. Using tab2
  3. On(Tab1.id = tab2.id)
  4. WhenMatchedThen
  5. Update SetTab1.val = tab2.val
Similarly, an error occurs if multiple entries in tab2 correspond to one entry in tab1: ORA-30926: unable to get a stable set of rows in the source tables
For example, insert an insert into tab2 values (2, 'xxxx') in tab2 ')
This error can be avoided by filtering repeated records in the subquery of using. For merge future edition:
  1. MergeIntoTab1
  2. Using (Select*FROMTab2 XWHEREX. ROWID =
  3. (SELECT MAX(Y. ROWID)FROMTab2 YWHEREX. ID = Y. ID) tab2
  4. On(Tab1.id = tab2.id)
  5. WhenMatchedThen
  6. Update SetTab1.val = tab2.val

For more information about Oracle, see Oracle topics page http://www.bkjia.com/topicnews.aspx? Tid = 12

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.