17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7: Adding More to Our Queries<br />

There are other possible mixes, but these easily cover the bulk of things that most any <strong>SQL</strong> developer<br />

will see.<br />

The Output Clause<br />

210<br />

The MERGE command also provides us the option of outputting what amounts to a SELECT statement<br />

with the details of what actions were actually performed by the MERGE. The OUTPUT keyword is<br />

essentially a substitute for SELECT, but brings along several special operators to allow us to match up to<br />

the merged data. These include:<br />

❑ $action: Returns INSERTED, UPDATED, or DELETED, as appropriate, to indicate the action taken<br />

for that particular row<br />

❑ inserted: A reference to an internal working table that contains a reference to any data inserted<br />

for a given row, note that this includes the current values for data that has been updated.<br />

❑ deleted: A reference to an internal working table that contains a reference to any data deleted<br />

from a given row, note that this includes the previous values for data that has been updated.<br />

We will visit the inserted and deleted tables in much more detail when we explore triggers in<br />

Chapter 15.<br />

Let’s try these out by resetting our MonthlyRollup table, and executing our MERGE statements again with<br />

the OUTPUT clause included. Start by truncating the MonthlyRollup table to clear out our previous work:<br />

USE AdventureWorks<strong>2008</strong><br />

TRUNCATE TABLE Sales.MonthlyRollup;<br />

This clears all data out of our table and resets everything about the table to a state as though it had just<br />

been created using the CREATE command. We’re now ready to execute our first MERGE statement again,<br />

but this time we’ll include the OUTPUT clause:<br />

MERGE Sales.MonthlyRollup AS smr<br />

USING<br />

(<br />

SELECT soh.OrderDate, sod.ProductID, SUM(sod.OrderQty) AS QtySold<br />

FROM Sales.SalesOrderHeader soh<br />

JOIN Sales.SalesOrderDetail sod<br />

ON soh.SalesOrderID = sod.SalesOrderID<br />

WHERE soh.OrderDate >= ‘2003-08-01’ AND soh.OrderDate < ‘2003-08-02’<br />

GROUP BY soh.OrderDate, sod.ProductID<br />

) AS s<br />

ON (s.ProductID = smr.ProductID)<br />

WHEN MATCHED THEN<br />

UPDATE SET smr.QtySold = smr.QtySold + s.QtySold<br />

WHEN NOT MATCHED THEN<br />

INSERT (Year, Month, ProductID, QtySold)<br />

VALUES (DATEPART(yy, s.OrderDate),<br />

DATEPART(m, s.OrderDate),<br />

s.ProductID,<br />

s.QtySold)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!