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.

soh.OrderDate,<br />

sod.ProductID,<br />

pp.Name,<br />

sod.OrderQty,<br />

sod.UnitPrice,<br />

sod.UnitPriceDiscount * sod.UnitPrice * sod.OrderQty AS TotalDiscount,<br />

sod.LineTotal<br />

FROM Sales.Customer AS sc<br />

INNER JOIN Sales.SalesOrderHeader AS soh<br />

ON sc.CustomerID = soh.CustomerID<br />

INNER JOIN Sales.SalesOrderDetail AS sod<br />

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

INNER JOIN Production.Product AS pp<br />

ON sod.ProductID = pp.ProductID<br />

WHERE CAST(soh.OrderDate AS Date) =<br />

CAST(DATEADD(day,-1,GETDATE()) AS Date);<br />

All the dates in the AdventureWorks<strong>2008</strong> database are old enough that this view wouldn’t return any<br />

data, so let’s modify a few existing rows to test it:<br />

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

UPDATE Sales.SalesOrderHeader<br />

SET OrderDate = CAST(DATEADD(day,-1,GETDATE()) AS Date),<br />

DueDate = CAST(DATEADD(day,11,GETDATE()) AS Date),<br />

ShipDate = CAST(DATEADD(day,6,GETDATE()) AS Date)<br />

WHERE Sales.SalesOrderID BETWEEN 43659 AND 43662;<br />

The core of this is a relatively simple update statement that is resetting the dates on a few orders to be<br />

relative to yesterday (the day before whatever day you run that update statement). The GETDATE()<br />

function is, just as you would expect, getting your current date. We’ll discuss some of the other pieces in<br />

a bit. For now, I’ll ask that you just take this one largely on faith, and trust that you’ll need to run this to<br />

have a value in AdventureWorks<strong>2008</strong> that will come up for our view. You should see a result from the<br />

Management Studio that looks something like this:<br />

(31,465 row(s) affected)<br />

Be aware that the message will appear on the Messages tab only if you are using the Management Studio’s<br />

Results In Grid mode. It should show up in your Results table if you’re in text mode.<br />

The OrderID might vary, but the rest should hold pretty true.<br />

Now let’s run a query against your view and see what we get:<br />

SELECT AccountNumber, SalesOrderID, OrderDate FROM YesterdaysOrders_vw;<br />

You can see that our four orders do show up. Indeed, since each has several line items, you should wind<br />

up with a total of 121,317 rows:<br />

AccountNumber SalesOrderID OrderDate<br />

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

AW00000676 43659 2007-09-30 00:00:00.000<br />

Chapter 10: Views<br />

307

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

Saved successfully!

Ooh no, something went wrong!