Important alert: (current site time 7/15/2013 6:57:08 PM EDT)
 

article

User Defined Function Intro

Email
Submitted on: 3/3/2002 12:17:36 AM
By: Lewis E. Moten III  
Level: Intermediate
User Rating: By 12 Users
Compatibility: Other
Views: 33240
author picture
(About the author)
 
     Brief introduction to user defined functions with examples and benefits explained.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				
Brief introduction to User Defined Functions

What is a user defined function?

User defined functions are very simular to stored procedures. Rather then returning recordsets, they can only return variables. They are also limited to the types of variables you may return. For example - text, ntext, and image datatypes can not be returned.

Ok, so how would it benefit me?

The magic of user defined functions is that you can use them in SELECT, UPDATE, DELETE, & SET statments. You can use them in triggers and other places. Somehow I get the idea that you are scratching your head still asking "What is it?". Let me show you a small example.

SELECT UserID, dbo.FullName(UserID) FROM Users

In this example, the function is called FullName. As you may have guessed, the function returns the full name of the user within the record.

How would I make a function?

Glad you asked. When you open your database in the SQL Server Enterprise Manager, one of the nodes available will state "User Defined Functions". I usually do a right-mouse-click and click on

A default template may appear ...

CREATE FUNCTION [OWNER].[FUNCTION NAME] (PARAMETER LIST)
RETURNS (return_type_spec) AS
BEGIN
(FUNCTION BODY)
END

This function is not valid nor helpful. It doesn't even pass when you click on the button "Check Syntax". It took me a good amount of research along with trial & error before I got the gist of what was going on.

So how about a demonstration?

Right O! Lets go with creating the "FullName" function. Here is my code:


CREATE FUNCTION [dbo].[FullName] (@UserID int)
RETURNS varchar(255)
AS 
BEGIN 
	Select
		@FullName = @FirstName + ' ' + @LastName
	FROM
		[Users]
	WHERE
		[UserID] = @UserID
	Return(@FullName)
END

So first, you can see that the parameter list has been changed to pass a Integer variable called UserID. You can add more parameters as long as you seperate them with a comma.

Next we see that the return type, and the parethesies around it has been replaced with a datatype "varchar(255)". You are not limited to varchars alone. Just about any type of datatype is available except cursors, records, and datatypes with pointers (text, ntext, image, etc.).

If you look at the very bottom, you will see "Return(@FullName)". This is where we return the results to the query that called the function.

And within the BEGIN and END statements, we have the body of the function.

Closing Comments

The demonstration here is very inefficient. It is here only as a reference to get you started. Defining your own functions allows more complex business logic & formatting to be possible. Consider the ability to pass in a piece of text of 4000 characters long and inserting HTML links on specific keywords. Another idea would be to perform lookups on multiple tables and return a value that best suites your query.


Other 31 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments
3/3/2002 4:14:56 PMJames Travis

I give it a 5 but do have the following you should consider adding. SQL does require the ownername.functionname to use the function. You cannot drop off the object owner name and dbo is not considered default. The reason can be found it SQL Books Online.
(If this comment was disrespectful, please report it.)

 
3/3/2002 11:24:36 PMLewis Moten

Thanks. I wasn't sure if I should mention it or not. I was thinking that the exmple showing the owner in the select query would help people get off to a good start and let them learn on there own.
(If this comment was disrespectful, please report it.)

 
3/4/2002 9:21:34 AMRasputin

Lewis,

I do not know what motivates you to give so much, but I am glad to see that an ungrateful world has not stopped you.
I always look forward to your contributions here on PSC. There are not enought high quality contributors to PSC, so THANK YOU, and please keep up the great work!

*x5!

- Ras
(If this comment was disrespectful, please report it.)

 
3/5/2002 2:30:00 AMEwald

Isn't this functionality for SQL Server 2000????
(If this comment was disrespectful, please report it.)

 
3/7/2002 10:11:26 PMNazer Mohamed

MS-SQL 7.0 doesn't have the 'Function' future. It is only for SQL-2000
(If this comment was disrespectful, please report it.)

 
3/18/2003 8:42:59 AM

I have a little function I was trying to write. This article got me a long way through it but I'm getting errors on variables not being declared. Any idea where/how this is done?
(If this comment was disrespectful, please report it.)

 
10/16/2003 6:52:52 AM

hi lewis ! , how do u run this function thru query analyser? do send in the syntax , thanks . praveen_amiable@yahoo.com
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.