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.

-- being defensive, we must drop the old implementation<br />

-- so that reporting periods are implemented<br />

-- only in one place<br />

DROP FUNCTION dbo.MonthReportingPeriodStart ;<br />

GO<br />

CREATE FUNCTION dbo.MonthReportingPeriodStart<br />

( @AsOfDate DATETIME )<br />

RETURNS DATETIME<br />

AS<br />

BEGIN ;<br />

DECLARE @ret DATETIME ;<br />

SET @ret = DATEADD(day, -29, @AsOfDate) ;<br />

RETURN @ret ;<br />

END ;<br />

Listing 6-10: Scalar UDF which implements the definition of reporting period.<br />

177<br />

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

We also have to change our SalesForMonth function, so that it utilizes our new scalar<br />

UDF, as shown in Listing 6-11.<br />

ALTER FUNCTION dbo.SalesForMonth ( @AsOfDate DATETIME )<br />

RETURNS TABLE<br />

AS<br />

RETURN<br />

( SELECT SalesID ,<br />

StateCode ,<br />

SaleDateTime ,<br />

Amount<br />

FROM dbo.Sales AS s<br />

WHERE SaleDateTime >=<br />

dbo.MonthReportingPeriodStart(@AsOfDate)<br />

AND SaleDateTime

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

Saved successfully!

Ooh no, something went wrong!