Introduction to the merge keyword in SQL Server

Source: Internet
Author: User
Tags final

Brief introduction

The merge keyword is a magical DML keyword. It was introduced in SQL Server 2008, and it can be insert,update,delete simple and a sentence. MSDN's explanation for the merge is very concise: "Inserts, updates, or deletes are performed on the target table based on the results of joins to the source table." For example, you can synchronize two tables by inserting, updating, or deleting rows in a table based on differences found in another table. With this description, we can see that the merge is about manipulating data between two tables.

You can imagine a scenario where you need to use the merge:

Data synchronization

Data conversion

Insert,update,delete operation of target table based on source table

Benefits of using the Merge keyword

The first is a more concise statement, in the era of SQL Server 2008 without the merge, based on the source table to the target table operations need to write several insert,update,delete. Using the merge, you just need to use a single statement. Let's take a look at the example below.

First, create the source and target tables and insert the relevant data, as shown in Figure 1.

Figure 1. Create a test table and insert test data

Now let's write a simple merge statement, as shown in Figure 2.

Figure 2. A simple merge statement

The resulting results are shown in Figure 3.

Figure 3. Update of the merge statement for the target table

The results of the final target table are shown in Figure 4.

Figure 4. Results of the final target table

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.