Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the MERGE statement in SQL Server 2005?

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?

like image 951
Vikrant More Avatar asked Sep 27 '12 12:09

Vikrant More


People also ask

Can we use merge in SQL?

So if there is a Source table and a Target table that are to be merged, then with the help of MERGE statement, all the three operations (INSERT, UPDATE, DELETE) can be performed at once. A simple example will clarify the use of MERGE Statement.

Which of the following rules of using SQL MERGE is not applicable?

We cannot use WHEN NOT MATCHED BY SOURCE clause more than two times. If WHEN NOT MATCHED BY SOURCE clause in SQL Server MERGE statement was specified two times, one must use an update operation and another one must use delete operation.

Can we use MERGE with CTE in SQL?

In addition, as of SQL Server 2008, you can add a CTE to the new MERGE statement.

Is MERGE better than update in SQL Server?

Both the MERGE and UPDATE statements are designed to modify data in one table based on data from another, but MERGE can do much more. Whereas UPDATE can only modify column values you can use the MERGE statement to synchronize all data changes such as removal and addition of row.


1 Answers

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.

like image 186
Aaron Bertrand Avatar answered Oct 09 '22 20:10

Aaron Bertrand