Can I use the MERGE statement in SQL Server 2005?

22,483

MERGE was introduced in SQL Server 2008. If you want to use that syntax, you'll need to upgrade.

Otherwise, the typical approach will depend on where the source data is from. If it's just one row and you don't know if you need to update or insert, you'd probably do:

UPDATE ... WHERE key = @key;

IF @@ROWCOUNT = 0
BEGIN
    INSERT ...
END

If your source is a #temp table, table variable, TVP or other table, you can do:

UPDATE dest SET ...
  FROM dbo.destination AS dest
  INNER JOIN dbo.source AS src
  ON dest.key = src.key;

INSERT dbo.destination SELECT ... FROM dbo.source AS src
  WHERE NOT EXISTS (SELECT 1 FROM dbo.destination WHERE key = src.key);

As with MERGE (and as Michael Swart demonstrated here), you will still want to surround any of these methods with proper transactions, error handling and isolation level to behave like a true, single operation. Even a single MERGE statement does not protect you from concurrency.

I've published some other cautions about MERGE in more detail here and here.

Share:
22,483
Vikrant More
Author by

Vikrant More

Working as a Senior Performance Database Engineer with Wolters Kluwer Financial Services Pvt. Ltd. I have been part of Industry from more the 8+ years. During my career, I worked in India, mostly working with SQL Server Technology on SQL, T-SQL, Administration and Automation right from the version 2008 to its latest form. Since year 2015 working on oracle 12c for AWR, ASH and ADDM and MySQL 5.5. I worked on Database Administration and optimization projects for high transnational system. Received Master Of Computer Application from University of Pune and Bachelors of Computer Science from Nagpur University.

Updated on July 05, 2022

Comments

  • Vikrant More
    Vikrant More almost 2 years

    I am using SQL Server 2005 and I wanted to create MERGE statement or concept in single query in SQL Server 2005. Is it possible?