SQL Server merge Usage

There were two tables: source table and the target table, and to update the target value in accordance with the table matches the source table.

There are three cases:

  • source table has a number of target table row does not exist. In this case, source rows in the table needs to be inserted into the target.
  • There are a number of source table rows target table does not exist. In this case, you need to delete rows from the target table.
  • Some rows source and target table having a table row the same key. However, these lines have different values ​​in the non-key columns. In this case, it is necessary to use values ​​from the source table update target table row.

Under diagram illustrating some of the operations of the source table and the target table: insert, update, delete:

If used alone INSERT, UPDATE, and DELETE statements, it requires three separate statement, to cause data matching rows in the source table to the target table updates.

However, the use of three merge operation may be performed simultaneously. Here is the syntax merge statement:

MERGE target_table USING source_table
ON merge_condition
WHEN MATCHED
    THEN update_statement
WHEN NOT MATCHED
    THEN insert_statement
WHEN NOT MATCHED BY SOURCE
    THEN DELETE;

Example of use:

CREATE TABLE sales.category (
    category_id INT PRIMARY KEY,
    category_name VARCHAR(255) NOT NULL,
    amount DECIMAL(10 , 2 )
);

INSERT INTO sales.category(category_id, category_name, amount)
VALUES(1,'Children Bicycles',15000),
    (2,'Comfort Bicycles',25000),
    (3,'Cruisers Bicycles',13000),
    (4,'Cyclocross Bicycles',10000);


CREATE TABLE sales.category_staging (
    category_id INT PRIMARY KEY,
    category_name VARCHAR(255) NOT NULL,
    amount DECIMAL(10 , 2 )
);


INSERT INTO sales.category_staging(category_id, category_name, amount)
VALUES(1,'Children Bicycles',15000),
    (3,'Cruisers Bicycles',13000),
    (4,'Cyclocross Bicycles',20000),
    (5,'Electric Bikes',10000),
    (6,'Mountain Bikes',10000);

Value sales.category_staging (source table) to be used to update data sales.category (target table), to use merge:

MERGE sales.category t 
    USING sales.category_staging s
ON (s.category_id = t.category_id)
WHEN MATCHED
    THEN UPDATE SET 
        t.category_name = s.category_name,
        t.amount = s.amount
WHEN NOT MATCHED BY TARGET 
    THEN INSERT (category_id, category_name, amount)
         VALUES (s.category_id, s.category_name, s.amount)
WHEN NOT MATCHED BY SOURCE 
    THEN DELETE;

FIG performed as follows:

 

Guess you like

Origin www.cnblogs.com/Vincent-yuan/p/11521229.html