New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Start learning with our library of video tutorials taught by experts. Get started

SQL Server 2008 Essential Training
Illustration by

Creating user-defined functions


From:

SQL Server 2008 Essential Training

with Simon Allardice

Video: Creating user-defined functions

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.
Expand all | Collapse all
  1. 2m 21s
    1. Welcome
      1m 19s
    2. Using the exercise files
      1m 2s
  2. 17m 58s
    1. SQL Server core concepts
      9m 4s
    2. SQL Server editions
      3m 8s
    3. Applications included with SQL Server
      5m 46s
  3. 26m 1s
    1. Preparing for installation
      3m 44s
    2. Creating service accounts
      2m 33s
    3. Installing SQL Server
      11m 42s
    4. Post-installation checks
      3m 9s
    5. Installing sample databases
      4m 53s
  4. 13m 35s
    1. Introduction to SQL Server Management Studio
      8m 7s
    2. Introduction to SQL Server Books Online
      3m 6s
    3. SQL Server system databases
      2m 22s
  5. 1h 26m
    1. Planning your database
      9m 39s
    2. Creating a SQL Server database
      4m 7s
    3. Creating tables
      7m 51s
    4. Data types in SQL Server
      12m 25s
    5. Defining keys
      8m 9s
    6. Creating default values
      4m 39s
    7. Creating check constraints
      2m 25s
    8. Creating unique constraints
      4m 34s
    9. Introduction to relationships and foreign keys
      9m 51s
    10. Creating relationships in SQL Server Management Studio
      8m 14s
    11. Database normalization
      11m 47s
    12. Creating computed columns
      3m 10s
  6. 23m 11s
    1. Using the SQL Server Import and Export Wizard
      3m 58s
    2. Importing Excel files into SQL Server
      6m 11s
    3. Importing CSV files into SQL Server
      5m 27s
    4. Importing Access databases into SQL Server
      7m 35s
  7. 55m 29s
    1. Introduction to Transact-SQL
      3m 43s
    2. Using SELECT statements
      7m 16s
    3. Changing the default database
      2m 21s
    4. Creating conditions in SQL
      8m 10s
    5. Sorting your output
      3m 23s
    6. Using aggregate functions
      7m 12s
    7. Finding unique values
      2m 14s
    8. Joining multiple tables together
      8m 0s
    9. Using subqueries
      9m 33s
    10. Viewing execution plans
      3m 37s
  8. 19m 36s
    1. Writing INSERT statements
      5m 47s
    2. Writing UPDATE statements
      4m 38s
    3. Writing DELETE statements
      2m 54s
    4. Using the OUTPUT clause to return inserted keys and GUIDs
      6m 17s
  9. 32m 52s
    1. Introduction to SQL functions
      6m 26s
    2. Using SQL configuration functions
      2m 14s
    3. Using string functions
      7m 26s
    4. Using date functions
      6m 27s
    5. Creating user-defined functions
      10m 19s
  10. 28m 46s
    1. Introduction to stored procedures
      4m 23s
    2. Creating stored procedures
      11m 23s
    3. Introducing transactions
      4m 23s
    4. Creating transactions
      8m 37s
  11. 16m 39s
    1. Understanding and creating indexes
      6m 32s
    2. Monitoring and rebuilding indexes
      6m 0s
    3. Monitoring database size and integrity
      4m 7s
  12. 11m 41s
    1. Creating backups
      4m 21s
    2. Creating differential backups and using backup compression
      3m 40s
    3. Restoring databases
      3m 40s
  13. 17m 40s
    1. Introduction to SQL Server security and permissions
      5m 54s
    2. Adding a Windows user to the database
      5m 7s
    3. Creating SQL Server logins and switching authentication modes
      6m 39s
  14. 36m 41s
    1. Introduction to SQL Server Reporting Services
      2m 52s
    2. Connecting to the Report Manager
      4m 29s
    3. Using Report Builder
      12m 4s
    4. Formatting values in reports
      4m 17s
    5. Adding indicators to reports
      5m 11s
    6. Adding charts to reports
      3m 54s
    7. Working with report security
      3m 54s
  15. 24m 41s
    1. Introduction to SQL Server Integration Services (SSIS)
      1m 57s
    2. Using Business Intelligence Development Studio (BIDS)
      6m 59s
    3. Creating and executing a simple SSIS package
      7m 35s
    4. Importing packages into SQL Server Management Studio
      3m 21s
    5. Scheduling jobs with SQL Server Agent
      4m 49s
  16. 31s
    1. Goodbye
      31s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
SQL Server 2008 Essential Training
6h 54m Beginner Dec 15, 2010

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.

Topics include:
  • Using T-SQL (Transact-SQL)
  • Managing databases with SQL Server Management Studio
  • Understanding database normalization
  • Using SELECT statements
  • Building indexes
  • Monitoring database size and integrity
  • Backing up and restoring databases
  • Creating functions and stored procedures
  • Managing database permissions
  • Creating and formatting reports
  • Adding charts to reports
  • Creating and executing a simple SSIS package
Subjects:
Business Developer Servers Databases
Software:
SQL Server
Author:
Simon Allardice

Creating user-defined functions

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.


Expand all | Collapse all
please wait ...
Q: I'm having problems installing the free Express R2 version of SQL Server on Windows XP. I tried 64-bit and 32-bit versions. In the videos, the author installs from a DVD. Do I need to do the same?
A: While the author installs from a DVD, it's not strictly necessary. There certainly shouldn't be a problem installing the Express edition from a regular download. That's the way it's intended to be installed.

If you're using Windows XP, the only officially supported version is the 32-bit version. However, you do need to make sure that your Windows XP install is completely up-to-date and patched, with XP Service Pack 3 installed. (See http://msdn.microsoft.com/en-us/library/ms143506.aspx#Express32 for formal requirements.)

It's not unusual for the install process to take a while, and with older operating systems like XP, you'll often have to back it out and try again, as usually there's a bunch of prerequisites that need to be installed. (Like the .NET Framework 3.5 SP1, the correct version of Windows Installer, etc.)
Q: The link to the installer for the AdventureWorks sample database, as shown in the Chapter 2 movie "Installing sample databases," no longer works. Where can I find the installer?
A: Microsoft has reorganized its site. The sample files are still there, but they're a bit harder to find. To install them:

1) Visit http://msftdbprodsamples.codeplex.com/.
2) Click the link to "SQL Server 2008 R2 OLTP."
3) Click the AdventureWOkrs2008R2 Data File link and agree to the conditions to download the MDF file.
4) Move the MDF file to your SQL Server Directory, usually located at C:\Program Files\Microsfot SQL Server\MSSQL 10_50.MSSQLSERVER\MSSQL\DATA.
5) Open the SQL Sever Management Studio and connect to your instance using an account with administrative privileges.
6) Attach the sample database by right-clicking the Databases folder in the Object Explorer and choosing Attach from the pop-up menu.
7) Click the Add button in the next menu and navigate to the MDF file in the Locate Database Files window that appears. Select it and click OK.
8) Remove the reference to the log file in the "AdventureWorks2008R2" database details: pane by selecting the Log entry and clicking removing.*
9) Click OK to return to SQL Server Management Studio and complete the attachment process.

*MDF files are the "data" files for SQL Server databases. They often come along with LOG files (ldf files). This one didn't so we need to REMOVE the reference to the non-existent log file. Select the second row in the lower section (it should say File Type: Log and Message: Not Found) and click the REMOVE button.

For an illustrated version of these instructions (with screenshots), click here for a PDF version.
 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed SQL Server 2008 Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

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.

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.