3. User-Defined Functions
3. User-Defined Functions
Functions
Database Programming
Why Use User-Defined functions?
They allow modular programming
You can create the function once,
store it in the database, and
Can be called any number of times in your program
Can be modified independently of the program source code
2
User-Define Functions
A user-defined function is a collection of T-SQL
statements
accepts parameters (optional)
performs an action and
returns a result
Commands used
CREATE FUNCTION: used to create a function
ALTER FUNCTION: used to modify a function
DROP FUNCTION : used to delete a function
3
User-Define Functions (cont.)
User-Defined functions are used to create a reusable
routine
They allow modular programming
They are used:
Anywhere where their returned value is valid
In the definition of another user-defined function
As part of the CREATE TABLE statement
To define a Derived-Column
To define a CHECK constraint on a column
Limitations
Cannot change the state of the database
Cannot return multiple result sets.
Use a stored procedure if you need to return multiple result sets.
Cannot call a stored procedure.
4
Components of a UDF
User-Defined functions have a two-part structure
Header and
Body.
5
Parameters
A User-Defined function can have zero or more input
parameters
The return value can either be a single scalar value or a
result set (table)
This depends on the type of the function
Optional parameters can be used
The DEFAULT keyword is used when the function is called to
retrieve the default value
This is different from stored procedures in which omitting the
parameter also implies the default value.
6
Types of Functions
Three type of User-Defined functions
1. Scalar Functions
2. Inline Table-Valued Function
3. Multi-statement Table-Valued Function
7
Scalar
User-Defined Functions
Database Programming
Scalar UDF - Syntax
CREATE FUNCTION function_name
( [ @parameterName dataType [ = default ] [ ,...n ] ] )
RETURNS returnDataType
AS
BEGIN
function_body
RETURN scalar_expression
END
9
Scalar UDF (cont.)
Scalar User-Defined functions return a single data value
of the type defined in the RETURNS clause.
The return type can be any data type except text, ntext,
image, cursor, and timestamp
Where do we use Scalar Functions
Can be used anywhere that a scalar expression of the same
data type is allowed
Scalar User-Defined functions are invoked by using at
least the two-part name of the function
Can be invoked from a query - like system functions
SELECT dbo.functionName (paramList)
10
Scalar UDF – Example
CREATE FUNCTION getFullName ( @Name1 varchar(50) , @Name2 varchar(50) )
RETURNS varchar(100)
AS
BEGIN
DECLARE @tempFullName varchar(100)
SET @tempFullName = Name1 + ‘ ‘ + Name2
RETURN (@ tempFullName)
END
11
Scalar UDF – Example
CREATE FUNCTION extractLastName ( @fullName varchar(100) )
RETURNS varchar(50)
AS
BEGIN
DECLARE @tempFullName varchar(100)
DECLARE @lastName varchar(50)
DECLARE @spcPosition int
IF(@spcPosition > 0)
SET @lastName = SUBSTRING(@tempFullName, @spcPosition + 1
, LEN(@tempFullName))
ELSE
SET @lastName = ''
RETURN(@lastName);
END
12
Using Scalar UDF – Example
Different ways of using the User-Defined Function:
13
Scalar UDF – Example
CREATE FUNCTION getTotalSalary (@depId int)
RETURNS decimal(8,2)
AS
BEGIN
DECLARE @totSalary decimal(8,2)
RETURN @totSalary
END
14
Using Scalar UDF – Example
Different ways of using the User-Defined Function:
15
Scalar UDF – Example
CREATE FUNCTION getMyKindOfDate(@theDate date)
RETURNS varchar(20)
AS
BEGIN
RETURN DATENAME(D, (@theDate )
+ CASE
WHEN DAY(@theDate) IN (1, 21, 31) THEN 'st'
WHEN DAY(@theDate) IN (2, 22) THEN 'nd'
WHEN DAY(@theDate) IN (3, 23) THEN 'rd'
ELSE 'th'
END
+''
+ DATENAME(MONTH, (@theDate )+ ' '
+ DATENAME(yy, (@theDate )
END
16
Scalar UDF – Example
CREATE FUNCTION Age_In_Days (
@birth_date DATETIME,
@today DATETIME = NULL
)
RETURNS INT
AS BEGIN
IF @today IS NULL SET @today = GETDATE();
RETURN DATEDIFF(DAY, @birth_date, @today);
END;
17
Scalar UDF – Example
CREATE FUNCTION CalculateAge (@dateOfBirth Date )
RETURNS INT
AS
BEGIN
DECLARE @AGE INT
18
Using Scalar UDF – CalculateAge()
SELECT dbo.CalculateAge(‘1931-02-14’ )
19
Calling Scalar UDF
SELECT dbo.GetFullName(fName, LName) AS EmployeeName
FROM Employee
WHERE dbo.getNetSalary(Salary) > 5000.00
UPDATE Employee
SET Salary = dbo.CalculateNewSalary(EmpID)
SELECT dbo.funcTotalSalary(1)
SELECT dbo.getDefaultDate()
SELECT dbo.getMyKindOfDate(GETDATE())
SELECT dbo.getFirstName('Abebe Kassa')
20
Check Point (Review)
What are User-Defined Functions
Types of User-Defined Functions
Scalar Functions
Inline Table-Valued Function
Multi-statement Table-Valued Function
Where can we use them
21
Table-Valued
User-Defined Functions
Database Programming
Table-Valued UDF
Table-Valued UDF (TVF) is a user-defined function that
returns a table data type
Table-Valued Functions can be used in the FROM
clause of a SELECT statement
Can be used just like a table in queries.
The main difference between a view and Table-Valued
Function is that TVFs can use parameters
23
Inline Table-Valued Function
An Inline Table-Valued Function specifies a single
SELECT statement
Can be seen as a VIEW with parameters
Always returns TABLE
The table is the result set of a single SELECT
statement
There is no function body (no BEGIN … END)
Do NOT need the TWO-PART name when using the
function
24
Inline Table-Valued UDF – Example
CREATE FUNCTION funcEmpByDepartment (@depId int)
RETURNS TABLE
AS
RETURN
(
SELECT E.FName, E.LName, E.Salary, D.DepName
FROM Employee AS E
JOIN Department AS D ON D.DepID = E.DepID
WHERE D.DepID = @depId
)
25
Inline Table-Valued UDF – Example
CREATE FUNCTION fn_GetStudentsByGender
( @Gender VARCHAR(50) )
RETURNS TABLE
AS
RETURN ( SELECT Name, DOB, Branch
FROM Student
WHERE Gender = @Gender )
27
Multi-Statement Table-Valued UDF
A multi-statement table-valued UDF returns a table data
type
A TABLE variable is used
To define the structure (columns) of the table
To insert the rows that should be returned
28
Multi-Statement
User-Defined Functions
Database Programming
Multi-Statement Table-Valued UDF
SYNTAX
RETURN
END
30
Multi-Statement Table-Valued UDF
CREATE FUNCTION GetEmployeesByDepartment (@myDepID INT)
RETURNS @empRecs TABLE
( EmployeeID int NOT NULL
, EmpName varchar(100) NOT NULL
, Department varchar(100) NOT NULL
)
AS
BEGIN
INSERT @empRecs
SELECT E.EmpID, E.FirstName + ' ' + E.LastName, D.DepName
FROM Employee E
JOIN Department D ON E.DepID = D.DepID
WHERE D.DepID = @myDepID
RETURN
END;
31
Multi-Statement Table-Valued UDF
Using the function:
32
More Examples
on
User-Defined Functions
Database Programming
Functions - Examples
CREATE FUNCTION udfProductInYear
( @start_year INT, @end_year INT )
RETURNS TABLE
AS
RETURN
SELECT productName, modelYear, listPrice
FROM products
WHERE model_year BETWEEN @start_year AND @end_year
--------
SELECT productName, modelYear, listPrice
FROM udfProductInYear(2017,2018)
ORDER BY productName
34
Functions - Examples
CREATE FUNCTION udfContacts()
RETURNS @contacts TABLE ( firstName VARCHAR(50),
lastName VARCHAR(50),
phone VARCHAR(25),
contactType VARCHAR(20) )
AS
BEGIN
INSERT INTO @contacts
SELECT first_name, last_name, phone, 'Staff'
FROM Staff
36
Review on User-Defined Functions
What are User-Defined Functions
What are they used for?
What is the major limitation of UDFs?
Types of User-Defined Functions
Scalar Functions
Inline Table-Valued Function
Multi-statement Table-Valued Function
Where can we use User-Defined Functions?
What is the difference between
Inline Table-Valued Function
Multi-statement Table-Valued Function
37
Exercise
on
User Defined Functions
Database Programming
Course Registration
CrsCode Course Title CreditHrs Prerequisite RegID Term StudCode CrsCode Grade
CS211 ICT 5 NULL 1 Winter 2022 AX1234 CS211 A
CS314 Database I 5 CS211 2 Winter 2022 XY9876 CS341 C
CS342 Database II 5 CS341 3 Spring 2022 AX1234 CS341 B
4 Spring 2022 XY9876 CS342 C
Loan
MemberID BookID LoanDate isReturned
1 3/10/2022 1
2 5/21/2022 0
3 5/20/2022 0
39
Loan
MemberID BookID LoanDate isReturned
1 3/10/2022 1
2 5/21/2022 0
3 5/20/2022 0
40
AdvWorks Database
SalesOrderDetail SalesOrder
SalesOrderID SalesOrderID
SalesOrderDetailID Customer
CustomerID
CustomerID
Product OrderQty OrderDate
ProductID Title
ProductID TotalAmount
ProductName FirstName
Status
ProductNumber LastName
Comment
CompanyName
UnitPrice
EmailAddress
ProductCategoryID
Phone
41
Exercise on UDF
1. Write a function named getEmployeeNames() that
returns the full names of all the employees
42
Exercise on UDF (cont.)
4. Write a function that returns the grade point for each
letter grade. (A=4, B=3, C=2, D=1, F=0)
5. Write a function that returns the list of members (Member
IDs) with overdue Books
getOverdueBooks( @forNbDays )
6. Create function that can be used to Auto-Generate
the following types of ID numbers
a. HL001 , HL002 , HL003 , etc.
b. HiLCoE’s student codes ( AX1234, XY987 , etc.)
You may use the Rand() function
7. In the Registrar database, write a function that returns
the GPA of a given student for a term
43
Exercise on UDF (cont.)
7. Consider the Registrar database given in question #4
and write a function that returns the GPA of a given
student for a term.
44
Exercise on UDF (cont.)
7. Write appropriate function for each of the following
a. Get the price of a product given its ID
b. Get the products purchased by a customer
c. Get the details for an Order
d. Calculate the total Amount for each order
e. Give the list of products that have never been ordered
f. Get the number of products purchased by a customer
g. Get the list of product names for an order given the SalesOrderID
h. Get the total amount to be paid for an order (given the SalesOrderID)
i. Update the TotalAmount in the SalesOrder table with the correct value
j. We want to produce a bill for a customer’s order.
45
Calculate the unit price of a product
--
CREATE FUNCTION getUnitPrice(@prodID int)
RETURNS decimal(12,2)
AS
BEGIN
DECLARE @UPrice decimal(12,2)
RETURN @UPrice
END
46
Create function for calculating the Total Amount
-- Step-by step solution
SELECT dbo.getUnitPrice(SOD.ProductID )
FROM SalesOrderDetail SOD
WHERE SOD.SalesOrderID = 1
47
Create function for calculating the Total Amount
RETURN @totAmt
END
48