Pages

Sunday, January 13, 2008

A New Member of the T-SQL Family–The MERGE Statement

One revolutionary addition is the new MERGE statement. On par with other core T-SQL CRUD features such as INSERT, SELECT, UPDATE, and DELETE, the MERGE statement is an ISO-2003 compliant command that is primarily intended to handle what many database users refer to as “UPSERT” functionality. For example, say you have an application where you either need to log a new entry for something that hasn’t been added to your system, or update it if it’s already been added previously. Without the MERGE statement you must either run a SELECT statement to see if a row has already been logged and then UPDATE or INSERT if it’s not there. Or you can try to UPDATE first, and then INSERT if the UPDATE doesn’t affect any rows. With the MERGE statement you can do this all in one fell swoop. Here’s a rather extensive example of the syntax :

MERGE Production.ProductInventory AS pi
USING (SELECT ProductID, SUM(OrderQty) FROM Sales.SalesOrderDetail sod
JOIN Sales.SalesOrderHeader soh
ON sod.SalesOrderID = soh.SalesOrderID
AND soh.OrderDate = GETDATE()
GROUP BY ProductID) AS src (ProductID, OrderQty)
ON (pi.ProductID = src.ProductID)
WHEN MATCHED AND pi.Quantity - src.OrderQty <> 0
THEN UPDATE SET pi.Quantity = pi.Quantity - src.OrderQty
WHEN MATCHED AND pi.Quantity - src.OrderQty = 0
THEN DELETE;

No comments: