Quantcast
Channel: Syntax Warriors » SQL
Viewing all articles
Browse latest Browse all 4

SQL 2008 and the Merge statement

$
0
0

I recently had the pleasure of playing around with the Merge statement which was introduced in SQL Server 2008 and I am pretty impressed by it. Although it dosen’t add any new functionality it makes the task of synchronizing two tables in or between databases much faster (and simpler).

Here is a self contained example of how the Merge command can be used to move data from one table to another, inserting new values and updating old ones.

IF OBJECT_ID('dbo.source') IS NOT NULL
    DROP TABLE dbo.[Source]
GO
IF OBJECT_ID('dbo.target') IS NOT NULL
    DROP TABLE dbo.[Target]
GO
CREATE TABLE dbo.[Source]
    (
      id INT NOT NULL ,
      name NVARCHAR(50) NOT NULL ,
      occupation NVARCHAR(50) NOT NULL
    )
GO

CREATE TABLE dbo.[Target]
    (
      id INT NOT NULL ,
      name NVARCHAR(50) NOT NULL ,
      occupation NVARCHAR(50) NOT NULL
    )
GO

-- New records that we want to merge into the target
INSERT  INTO dbo.[Source]
VALUES  ( 5, 'Erik', 'Taxi Driver' )
INSERT  INTO dbo.[Source]
VALUES  ( 10, 'Michael', 'Doctor' )
INSERT  INTO dbo.[Source]
VALUES  ( 15, 'Josh', 'Pilot' )
INSERT  INTO dbo.[Source]
VALUES  ( 40, 'Jasmine', 'Evil Lawyer' )

-- Add an existing record into the destination
INSERT  INTO dbo.[Target]
VALUES  ( 15, 'Josh', 'Unemployed' )

-- what do we have before we merge?
SELECT  *
FROM    [Source]
ORDER BY id

SELECT  *
FROM    [Target]
ORDER BY id
GO

-- The actual merge.
MERGE INTO [Target] AS T
    USING [Source] AS S
    ON T.id = S.id
    WHEN MATCHED
    -- this is run on each row where the Merge finds a match.
        THEN
          UPDATE
			SET T.name = S.name, T.occupation = S.occupation
			-- Note that we dont need a where statement.
    WHEN NOT MATCHED
    -- this is run on every row where the Target does not have a matching id.
        THEN
          INSERT   ( id, name, occupation )
          VALUES    ( S.id ,
                      S.name ,
                      S.occupation
                    )

    OUTPUT
        $ACTION , -- This line tells us what actually happened with the row.
        INSERTED.id ,
        DELETED.id ;

-- What did we end up with?
SELECT  *
FROM    [Source]
ORDER BY id

SELECT  *
FROM    [Target]
ORDER BY id
GO

This results in the following:
mergeoneway
What happened here is that the rows with id 5, 10 and 40 were inserted into the target while the row with id 15 was matched between the source and the target. Josh, with id 15, is therefore no longer unemployed.

You can read more about Merge on MSDN


Viewing all articles
Browse latest Browse all 4

Trending Articles