Viewers: in countries Watching now:
In SQL Server 2008 Essential Training, Simon Allardice explores all the major features of SQL Server 2008 R2, beginning with core concepts: installing, planning, and building a first database. Explore how Transact-SQL is used to retrieve, update, and insert information, and gain insight into how to effectively administer databases. The course also covers features outside SQL Server's database engine, including technologies that have grown up around it: SQL Server Reporting Services and Integration Services. Exercise files are included with the course.
Not only do you have the over 200 functions defined in SQL Server, you can also define your own, what are referred to as user-defined functions, sometimes abbreviated to UDFs. So let's say I've got a piece of SQL here which is doing a sub-query and what this is doing right now is finding the company name for the customer who has placed the largest order. Okay, it's a simple example but this should do the trick. Let's imagine that I want to get this page of information 25 times a day.
So I'd like a function that returns it. Well I can start off with this SQL that I have, but I do need to provide a few more pieces of information for me to describe what this function is and for a start, I am going to have to give it some kind of name. Now functions often take parameters. So I do have to tell SQL Server does this one have any parameters or does it have no parameters. And then I've also got to say what is returned by the function.
So most of what I am going to have to write is actually wrapping around the contents the actual behavior of this function that I'm going to do. Well, luckily however SQL Server can help you a little bit with that and there are two ways of getting that. I have my Template Explorer open on the right-hand side. If yours is closed, you can get it from the View menu and just hitting Template Explorer and you'll find that in the Function folder, you actually have several boilerplate sets of code for creating functions.
Inline function, table-valued function, multi-statement function, scalar function new menu, and scalar-valued function. Well, this one is quite simple. We are going to return a scalar function, which is the most common. It's the single value. So I have a couple of choices here. Well, which one should I pick? They both do the same thing but just let me show you the difference. If I pick me Create Scalar-valued Function and double click that, what it gives me is some boilerplate code here that sets me through what I've got to do.
Now this is all right, but I actually prefer the other one, which is this guy, Create Scalar Function (New Menu). It's a bit longer but most of it's a comment. Now this is the same one that you would get if you drilled down into the database that you want, found in your Programmability folder, opened up Functions, opened up Scalar-valued Functions and then right click and set New Scalar-valued Function. Now that's what we want. So I might as well do that. Now the boilerplate code that Microsoft provides has a lot of green comments and I am just going to pull those out for readability right now.
But there's a couple of places you could work with them. Let me close this to give us a bit more room to breathe. The first lines up at the top are just a couple of good settings. SET ANSI_NULLS ON SET QUOTED IDENTIFIER OFF and these are really about how things like equality comparisons are happening. I could actually remove these lines from this code. It would work nonetheless but I am just going to leave them there, because this is the stuff that we're interested in. Create function. well, I said on my other tab here that I needed a section for a name, I needed a section for parameters and a return value, and then what does the function do.
And we are going to do all of that here. Here's where we actually say we are giving the function a name. Unlike any other object in our database we are really going to name it with an object name that will be inside a schema. I have currently got AdventureWorksLT selected as my default database. I could otherwise say use AdventureWorksLT here if I wanted to be doubly assure. Well, what I'm going to do is create a function and call it SalesLT. and then the function name. Well it's quite common that you'll see user-defined functions with the prefix such as UDF_ or UDF by itself or something like UFN I have seen quite a lot lately.
I am going to call this ufnBigSpender. The reason for the UFN is it just makes it obvious if there's an error being generated later on that this is a user function. This next section is when I add any parameters. Does this take any arguments and in the way that say the MAX function requires a column name. Well, it actually doesn't. So I am just going to delete that, no parameters, but I'll leave the that just to make that clear. And I said we've got to tell it what it returns and you notice here it's saying you have got to say the function data type.
Well, this is going to return the name of the company, in which case it's going to be a NVARCHAR, and I have got to actually declare it here because it's not returning the column. it's whatever we decide this is. So I am going to say it returns an NVARCHAR with a length of 50, but I haven't yet said what does this do. Now for the first-time what we are hitting is a way of defining a block in SQL. We have got this phrase begin and end and this is really the contents of our function.
We've have set it up here with a name and return type and then what it's asking us to do is declare a return variable, have the two SQL statements for what the function actually does, and then return the result of the function. So we haven't worked with variables yet, so this is a good place to declare our first one. What I have to do is just have a placeholder, some named bucket to hold that company name, so I can return it later. The way we typically do it in SQL, on SQL Server certainly, is we will use the @ sign and that's just a little bit of shorthand. We could call it whatever we wanted, but it becomes obvious this is our own variable and I will call it company and then I give it the data type of NVARCHAR(50) because of course that is what I'm going to return.
Then it says Add the T-SQL statements to compute the return value. Well, I'm going to copy them across from my other file. It isn't perfect, but we can do it here. So I am saying SELECT CompanyName. Now it's highlighted a problem here where I don't just have a boring old regular SELECT statement. what I need to describe inside this SQL is where does this new variable that I just get created get filled.
What I need to say is this. SELECT @Company = CompanyName FROM SalesLT.Customer where our CustomerID is the top one based on the SalesOrderHeader table. That looks all right. So we declare the variable, we fill it, and then finally we return it and we are done. Now, bear in mind what I'm describing here. I am not describing the function. I'm writing the code to create the function.
We have this line up here. That's what I'm telling as SQL Server to do is create this function. I only want to execute all this code once. So I take a scan of it. It looks all right. I'm going to hit Execute. Bang! What I get is Command(s) completed successfully. Now you may be wondering well, why don't I see the name of that company? Because I wasn't asking to do it. I just created that function. Prove it, you say. Well, I can.
Let me go over to the section of the database where I created it. I am looking at the folder that says Scalar-valued Functions. It's not showing up here and they should be there. That's because I need to go up to the top of my Object Explorer and hit Refresh and then I see that I do have SalesLT.ufnBigSpender. Okay, things are looking good. In fact, I can actually close that code that I used to create it and then close that one as well. But it wouldn't be much good if we couldn't prove that this works. So let's open a new query window. I'm looking at AdventureWorksLT as my default.
So I'm just going to say Select and drag this across. It is a function so it should end in the parentheses and I will hit F5 and yes indeed, calling the function ufnBigSpender brings me back Action Bicycle Specialists, which right now is the customer that's placed the largest order. Now you will notice that I'm getting the red squiggly here. It can't find this user-defined function or aggregate or the name is ambiguous, and usually the reason for that is that the IntelliSense just hasn't updated itself.
Now there is a couple of tricks for getting around that, but the easiest and most simplistic way is just reopen SQL Server Management Studio. Bang! Open a new query and the next time I type it, SalesLT.ufnBigSpender is now actually showing up and we don't get the red squiggly anymore. Now, when you're new to SQL Server, creating your own functions isn't something that you should be thinking that you need to do a lot.
In fact, it's quite rare compared to other parts of SQLite stored procedures that we are going to get into a little later. But it is a possibility. These functions can even be used in- line as part of WHERE clauses or INSERTs or UPDATEs, but they can't be used to actually do an UPDATE or INSERT themselves. It wouldn't allow me to actually write an UPDATE or an INSERT statement inside that function. Now the last question is what happens if I want to change it a little bit? Well, I can go back into that function which will be in my Programmability > Functions > Scalar- valued Functions and notice that when I pick my user-defined function here, I can right-click and say Modified.
What I will have here is something that's very similar to the SQL I had before, but notice the phrase here. When I run this, it's not saying create function. It's saying alter function. So this is the SQL I would run to make any changes to it and open it up make a few tweaks, maybe change my sub-query to adjoin or what have you, and then run this SQL again to update that function.
Find answers to the most frequently asked questions about SQL Server 2008 Essential Training .
Here are the FAQs that matched your search "" :
Sorry, there are no matches for your search "" —to search again, type in another word or phrase and click search.
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.