SQL merge addition, update, or revoke data

Source: Internet
Author: User

If you want to add data when there is no data, or update or delete data when there is data, you must first select the statement to determine whether to insert, update, or delete data, the merge indexing method can save these steps, and the entire method is included.

 

Merge is defined in the standard of SQL 2003.

Supported DBMS

  • Oracle9i or above
  • Ms SQL Server 2008 or above (slow down for years ).
  • MySQL 5.0 or above

Every DBMS has its own overhead. Please take the test on your own.

 

Limit Method

Merge Table_name Using Table_name On( Condition)

When matched then update set Column1= Value1[, Column2= Value2...]

When not matched then insert( Column1[, Column2...]) Values( Value1[, Value2...])

 

Example

1. There are resources updated and no resources are added

Merge tablea as target
Using (select 'testvalue') as source (Columna)
On (target. Columna = source. Columna)
When matched then update set Columna = 'testvalue'
When not matched by target then insert (Columna, columnb) values ('testvalue', 'testvalue ')

2. There are resources to be deleted, and no resources to be added

Merge tablea as target
Using (select 'testvalue') as source (Columna)
On (target. Columna = source. Columna)
When matched then delete
When not matched by target then insert (Columna, columnb) values ('testvalue', 'testvalue ')

Additional information

Merge (SQL)-Wikipedia

Merge (TRANSACT-SQL)

Permanent Link to merge command enhancements in Oracle 10g

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.