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.

Chapter 13: User-Defined Functions<br />

424<br />

Look back through the list of requirements for a deterministic function and see if you can figure out why<br />

this one doesn’t meet the grade.<br />

When I was working on this example, I got one of those not so nice little reminders about how it’s the<br />

little things that get you. You see, I was certain this function should be deterministic, and, of course, it<br />

wasn’t. After too many nights writing until the morning hours, I completely missed the obvious —<br />

SCHEMABINDING.<br />

Fortunately, we can fix the only problem this one has. All we need to do is add the WITH SCHEMABINDING<br />

option to our function, and we’ll see better results:<br />

ALTER FUNCTION dbo.DayOnly(@Date date)<br />

RETURNS date<br />

WITH SCHEMABINDING<br />

AS<br />

BEGIN<br />

RETURN @Date;<br />

END<br />

Now, we just rerun our OBJECTPROPERTY query:<br />

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

1<br />

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

And voilà — a deterministic function!<br />

We can compare this, however, with our AveragePrice function that we built in the AdventureWorks<strong>2008</strong><br />

database. It looked something like this:<br />

CREATE FUNCTION dbo.AveragePrice()<br />

RETURNS money<br />

WITH SCHEMABINDING<br />

AS<br />

BEGIN<br />

RETURN (SELECT AVG(ListPrice) FROM Production.Product);<br />

END<br />

GO<br />

CREATE FUNCTION dbo.PriceDifference(@Price money)<br />

RETURNS money<br />

AS<br />

BEGIN<br />

RETURN @Price - dbo.AveragePrice();<br />

END<br />

In this function we used schema-binding right from the beginning, so let’s look at our OBJECTPROPERTY:<br />

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

SELECT OBJECTPROPERTY(OBJECT_ID(‘AveragePrice’), ‘IsDeterministic’);

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

Saved successfully!

Ooh no, something went wrong!