output function of SQL Server 2008 Merge statement _mssql2008

Source: Internet
Author: User
Tags null null
Here are a few ways to combine the new T-SQL statement merge of output with 2008:
Create a new table below:
Copy Code code as follows:

CREATE TABLE Book (
ISBN varchar () PRIMARY KEY,
Price Decimal,
Shelf int)

CREATE TABLE Weeklychange (
ISBN varchar () PRIMARY KEY,
Price Decimal,
Shelf int)

CREATE TABLE Bookhistory (
Action nvarchar (10),
NEWISBN varchar (20),
Newprice Decimal,
newshelf int,
OLDISBN varchar (20),
Oldprice Decimal,
oldshelf int,
Archivedat datetime2)

SQL statement is
Copy Code code as follows:

MERGE Book as B
USING Weeklychange as WC
On B.ISBN = WC. Isbn
When matched and (B.price <> WC. Price OR b.shelf <> WC. Shelf) THEN
UPDATE SET b.price = WC. Price, b.shelf = WC. Shelf
When not matched THEN
INSERT VALUES (WC. ISBN, WC. Price, WC. Shelf)
OUTPUT $action, inserted.*, deleted.*, Sysdatetime ()
into Bookhistory;

The result set is:

SELECT * from Bookhistory
Go

Action newisbn newprice newshelf oldisbn oldprice oldshelf
------ ------- -------- -------- ------- -------- -------- ---------------------------
UPDATE a 1 a 100 1 2007-11-25 14:47:23.9907552
INSERT C 3 null null 2007-11-25 14:47:23.9907552

There are insert and update two output scenarios. If you only need one of these, you can filter it in the following way:
Copy Code code as follows:

INSERT into book (ISBN, Price, shelf, archivedat)
SELECT ISBN, price, shelf, GETDATE () from
(MERGE book as B
USING Weeklychange as WC
On B.ISBN = WC. ISBN and B.archivedat is NULL
When matched and (B.price <> WC. Price OR b.shelf <> WC. Shelf) THEN
UPDATE SET price = WC. Price, shelf = WC. Shelf
When not matched THEN
INSERT VALUES (WC. ISBN, WC. Price, WC. Shelf, NULL)
OUTPUT $action, WC. ISBN, Deleted.price, deleted.shelf
) CHANGES (Action, ISBN, price, shelf)
WHERE Action = ' UPDATE ';
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.