Brief,introduction,user,defined,functions,wit
Quick Search for:  in language:    
Brief,introduction,user,defined,functions,wit
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
SQL Stats

 Code: 28,909 lines
 Jobs: 440 postings

 
Sponsored by:

 

You are in:

 
Login



Latest Code Ticker for SQL.
Link_SQLServer_ Oracle
By Daniel G. Menendez on 8/20


SQL Strip Alpha/Numeric
By Jay Gardner on 8/19


how to apply a filter to an Access 2000 form by using a combo box as a filter parameter
By David Nishimoto on 8/16


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!





Affiliate Sites



 
 
   

User Defined Function Intro

Print
Email
 

Submitted on: 3/3/2002 12:17:36 AM
By: Lewis Moten  
Level: Intermediate
User Rating: By 9 Users
Compatibility:Other

Users have accessed this article 3821 times.
 

(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 26 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
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 PM:James 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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/3/2002 11:24:36 PM:Lewis 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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/4/2002 9:21:34 AM:Rasputin
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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/5/2002 2:30:00 AM:Ewald
Isn't this functionality for SQL Server 2000????
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/7/2002 10:11:26 PM:Nazer Mohamed
MS-SQL 7.0 doesn't have the 'Function' future. It is only for SQL-2000
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | SQL Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.