30.06.2013 Views

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

171<br />

Chapter 6: Reusing T-<strong>SQL</strong> Code<br />

we run the report. For this purpose, our stored procedure serves the customers' needs<br />

well, and we soon receive a request for a similar report, returning the average sales per<br />

state, for a given month. Note that our new report is required to use the same definition<br />

of "for a given month."<br />

It is very tempting to just copy the existing SelectTotalSalesPerStateForMonth<br />

procedure, and replace sum with avg to meet the new requirements, as shown in<br />

Listing 6-3.<br />

CREATE PROCEDURE dbo.SelectAverageSalesPerStateForMonth<br />

@AsOfDate DATETIME<br />

AS<br />

SELECT AVG(Amount) AS SalesPerState ,<br />

StateCode<br />

FROM dbo.Sales<br />

-- month begins on the first calendar day of the month<br />

WHERE SaleDateTime >= DATEADD(month,<br />

DATEDIFF(month, '19900101',<br />

@AsOfDate),<br />

'19900101')<br />

AND SaleDateTime

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

Saved successfully!

Ooh no, something went wrong!