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.

types!), except for BLOBs, cursors, and timestamps. Even if you wanted to return an integer, a UDF should<br />

look very attractive to you for two different reasons:<br />

❑ Unlike sprocs, the whole purpose of the return value is to serve as a meaningful piece of data —<br />

for sprocs, a return value is meant as an indication of success or failure and, in the event of failure,<br />

to provide some specific information about the nature of that failure.<br />

❑ You can perform functions inline to your queries (for instance, include it as part of your SELECT<br />

statement) — you can’t do that with a sproc.<br />

So, that said, let’s create a simple UDF to get our feet wet on the whole idea of how we might utilize<br />

them differently from a sproc. I’m not kidding when I say this is a simple one from a code point of view,<br />

but I think you’ll see how it illustrates my sprocs versus UDFs point.<br />

One of the most common function-like requirements I see is a desire to see if an entry in a datetime<br />

field occurred on a specific day. The usual problem here is that your datetime field has specific time-ofday<br />

information that prevents it from easily being compared with just the date. Indeed, we’ve already<br />

seen this problem in some of our comparisons in previous chapters.<br />

Let’s go back to our Accounting database that we created in Chapter 5. Imagine for a moment that we<br />

want to know all the orders that came in today. Let’s start by adding a few orders in with today’s date.<br />

We’ll just pick customer and employee IDs we know already exist in their respective tables (if you don’t<br />

have any records there, you’ll need to insert a couple of dummy rows to reference). I’m also going to<br />

create a small loop to add in several rows:<br />

USE Accounting;<br />

DECLARE @Counter int = 1;<br />

WHILE @Counter

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

Saved successfully!

Ooh no, something went wrong!