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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

OUTPUT $action,<br />

inserted.Year,<br />

inserted.Month,<br />

inserted.ProductID,<br />

inserted.QtySold,<br />

deleted.Year,<br />

deleted.Month,<br />

deleted.ProductID,<br />

deleted.QtySold;<br />

This, of course, performs exactly the same action it did the first time we ran it (inserting 192 rows), but<br />

this time we get a result set back that provides information about the action taken:<br />

$action Year Month ProductID QtySold Year Month ProductID QtySold<br />

---------- ------ ----- ----------- ----------- ------ ----- ----------- ----------<br />

INSERT 2003 8 707 242 NULL NULL NULL NULL<br />

INSERT 2003 8 708 281 NULL NULL NULL NULL<br />

INSERT 2003 8 711 302 NULL NULL NULL NULL<br />

…<br />

…<br />

INSERT 2003 8 997 43 NULL NULL NULL NULL<br />

INSERT 2003 8 998 138 NULL NULL NULL NULL<br />

INSERT 2003 8 999 103 NULL NULL NULL NULL<br />

(192 row(s) affected)<br />

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

Notice that, since we only had inserted rows in this particular query, all of the data from the deleted<br />

table is null. Things change quickly though when we run the second MERGE statement (with the same<br />

OUTPUT clause added):<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-02’ AND soh.OrderDate < ‘2003-08-03’<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)<br />

OUTPUT $action,<br />

inserted.Year,<br />

inserted.Month,<br />

inserted.ProductID,<br />

inserted.QtySold,<br />

211

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

Saved successfully!

Ooh no, something went wrong!