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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

13<br />

User-Defined Functions<br />

Well, here we are already at one of my favorite topics. Long after their introduction, user-defined<br />

functions — or UDFs — remain one of the more underutilized and misunderstood objects in <strong>SQL</strong><br />

<strong>Server</strong>. In short, these were awesome when <strong>Microsoft</strong> first introduced them in <strong>SQL</strong> <strong>Server</strong> 2000, and<br />

the addition of .NET functionality back in <strong>SQL</strong> <strong>Server</strong> 2005 just added all that much more to them.<br />

One of the best things about UDFs from your point of view is, provided you’ve done the book in<br />

order, you already know most of what you need to write them. They are actually very, very similar<br />

to stored procedures — they just have certain behaviors and capabilities about them that set them<br />

apart and make them the answer in many situations.<br />

In this chapter, we’re not only going to introduce what UDFs are, but we’re also going to take a<br />

look at the different types of UDFs, how they vary from stored procedures (often called sprocs),<br />

and, of course, what kinds of situations we might want to use them in. Finally, we’ll take a quick<br />

look at how you can use .NET to expand on their power.<br />

What a UDF Is<br />

A user-defined function is, much like a sproc, an ordered set of T-<strong>SQL</strong> statements that are preoptimized<br />

and compiled and can be called to work as a single unit. The primary difference between<br />

them is how results are returned. Because of things that need to happen in order to support these<br />

different kinds of returned values, UDFs have a few more limitations to them than sprocs do.<br />

OK, so I’ve said what a UDF is, so I suspect I ought to take a moment to say what it is not. A<br />

UDF is definitely NOT a replacement for a sproc — they are just a different option that offers us<br />

yet one more form of code flexibility.<br />

With a sproc, you can pass parameters in and also get values in parameters passed back out. You<br />

can return a value, but that value is really intended to indicate success or failure rather than return<br />

data. You can also return result sets, but you can’t really use those result sets in a query without<br />

first inserting them into some kind of table (usually a temporary table) to work with them further.

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

Saved successfully!

Ooh no, something went wrong!