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.

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

208<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);<br />

Note that the semicolon is required at the end of the MERGE statement. While the semicolon remains<br />

optional on most <strong>SQL</strong> Statements for backward-compatibility reasons, you’ll find it working its way into<br />

more and more statements as a required delimiter of the end of the statement. This is particularly true<br />

for multipart statements such as MERGE.<br />

When you run this, you should get 192 rows affected, assuming you haven’t been altering the data in<br />

AdventureWorks<strong>2008</strong>. Now, since our Sales.MonthlyRollup table was empty, there wouldn’t have been<br />

any matches, so all rows were inserted. We can verify that by querying our Sales.MonthlyRollup table:<br />

SELECT *<br />

FROM Sales.MonthlyRollup;<br />

This gets us back the expected 192 rows:<br />

Year Month ProductID QtySold<br />

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

2003 8 707 242<br />

2003 8 708 281<br />

2003 8 711 302<br />

…<br />

…<br />

2003 8 997 43<br />

2003 8 998 138<br />

2003 8 999 103<br />

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

Every row that was in the basic SELECT that powered our MERGE wound up being inserted into our<br />

table. Let’s move on, however, to the second day of the month:<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’

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

Saved successfully!

Ooh no, something went wrong!