Use merge statements in Oracle to prevent repeated Inserts

Source: Internet
Author: User

Batch insertion is required in the Project. To prevent duplicate data insertion, you must first determine whether the inserted data already exists. If yes, ignore this insertion; otherwise, insert this data, at the beginning, we first use an SQL statement to judge whether the returned result is true (the record already exists). Ignore this statement; otherwise, this data is inserted, in this case, we need to initiate two connections to the database to insert a piece of data. Later, we found that the efficiency was too low. After Google, we found that the Oracle Database supports the merge statement and conducted a test, if the call succeeds, it will be recorded for future reference by myself and colleagues.

Database: Test

Create Table Test (ID number not null, namevarchar2 (30) not null, sex varchar2 (2) default 'male ')

Insert two pieces of data:

Insert into test values (1, 'sunhenx', 'male') insert into test values (2, 'sunhailong', 'female ')

Merge statement:

Merge into test a using Test B on (. name = B. name) when matched thenupdate set. sex = 'female 'Where. name = 'sunhenx' when not matched then insert values (3, 'sunhenxing', 'femal ')

Note that the update statement and insert statement in the merge statement are a bit different from the general SQL statement format, ^_^.

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.