Creating Functions This presentation was prepared by Professor Steve Ross, with the advice of other MIS Faculty, for use in MIS Classes at Western Washington University. Please contact Dr. Ross for permission to use in other settings. Further modifications by Kraig Pencil.Dr. Ross
The Challenge Create a function that displays a person’s name in a single field: –Ex.: Last, First Middle –Ex.: First Middle Last The function should accommodate possibility of missing or null First, Middle or Last names
Design Before You Build What input fields – from what tables – are required? –tblPerson LastName – Data Type: variable character length (size) FirstName – Data Type: variable character length (size) MidName – Data Type: variable character length (size) What is the output and how should the output? For First Middle Last –Include a space after the first or middle name (if there is one) For Last, First Middle –Include a comma after the last name only when followed by non-blank first name.
Creating the Function, Step 1 Functions are contained under Programmability in the database –Scalar-valued Functions return a single value (not a table of values) –We will create a Scalar-valued Function by typing the SQL declaration in a query script window:
Example of a Function Definition CREATE FUNCTION ufnEqualOrNot ( -- Declare your function parameters, e.g. varchar(30) ) RETURNS varchar(60) AS BEGIN -- Declare any additional variables needed varchar(60) -- Add your program logic (“code”) to compute the return value = 'not equal' Else = 'equal' -- Return the result of the function END GO Use CREATE FUNCTION to create the function. Use ALTER FUNCTION to alter the function.
“Clean Up Your Data” with RTRIM & LTRIM Problems can arise when the data (names) contain spaces, Null, or empty strings -- Given the following data, what will the resulting string be? = ' Kraig ' = NULL = ' Pencil ' = result: ' Kraig Pencil ' = The result: 'Kraig Pencil' = + The result: 'KraigPencil' = + The result: + NULL
Bulletproof Your Code This code handles problems that can arise when the data contain spaces, Null or empty strings BEGIN -- Note: '' is two single quotation marks. ' ' has a space between the quotes. -- This variable will hold the fullname varchar(75) -- to '', otherwise it will contain NULL = '' IF IS NOT NULL '') Add [space] and middle name IF IS NOT NULL <> '') + ' ' + -- Add [space] and last name IF IS NOT NULL <> '') + ' ' + could have a leading space. How? RETURN END
Testing the Function I Open a New Query window Type a simple SELECT statement Execute the statement
Testing the Function II SELECT statement to refer to fields from a table Execute the statement Note: No leading spaces