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 />

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

RETURNS money<br />

AS<br />

BEGIN<br />

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

END<br />

Notice that it’s completely legal to embed one UDF in another one.<br />

Note that the WITH SCHEMABINDING option works for functions just the way that it did for views — if<br />

a function is built using schema-binding, then any object that function depends on cannot be altered or<br />

dropped without first removing the schema-bound function. In this case, schema-binding wasn’t really<br />

necessary, but I wanted to point out its usage and also prepare this example for something we’re going<br />

to do with it a little later in the chapter.<br />

Now let’s run our query using the new functions instead of the old subquery model:<br />

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

SELECT Name,<br />

ListPrice,<br />

dbo.AveragePrice() AS Average,<br />

dbo.PriceDifference(ListPrice) AS Difference<br />

FROM Production.Product<br />

WHERE ProductSubCategoryID = 1; -- The Mountain Bikes Sub-cat<br />

This yields us the same results we had with our subquery.<br />

Note that, beyond the readability issue, we also get the added benefit of reuse out of this. For a little<br />

example like this, it probably doesn’t seem like a big deal, but as your functions become more complex,<br />

it can be quite a time saver.<br />

UDFs That Retur n a Table<br />

416<br />

User-defined functions in <strong>SQL</strong> <strong>Server</strong> are not limited to just returning scalar values. They can return<br />

something far more interesting — tables. Now, while the possible impacts of this are sinking in on you,<br />

I’ll go ahead and add that the table that is returned is, for the most part, usable much as any other table<br />

is. You can perform a JOIN against it and even apply WHERE conditions against the results. It’s very cool<br />

stuff indeed.<br />

To make the change to using a table as a return value is not hard at all — a table is just like any other<br />

<strong>SQL</strong> <strong>Server</strong> data type as far as a UDF is concerned. To illustrate this, we’ll build a relatively simple one<br />

to start:<br />

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

GO<br />

CREATE FUNCTION dbo.fnContactList()<br />

RETURNS TABLE

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

Saved successfully!

Ooh no, something went wrong!