0% found this document useful (0 votes)
3 views

3. User-Defined Functions

User-Defined Functions (UDFs) in database programming enable modular programming, faster execution, and reusability of code. They can accept parameters, perform actions, and return results, but cannot modify database states or return multiple result sets. UDFs are categorized into scalar functions, inline table-valued functions, and multi-statement table-valued functions, each with specific use cases and syntax.

Uploaded by

Akinahom Yoseph
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

3. User-Defined Functions

User-Defined Functions (UDFs) in database programming enable modular programming, faster execution, and reusability of code. They can accept parameters, perform actions, and return results, but cannot modify database states or return multiple result sets. UDFs are categorized into scalar functions, inline table-valued functions, and multi-statement table-valued functions, each with specific use cases and syntax.

Uploaded by

Akinahom Yoseph
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

User-Defined

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

 They allow faster execution.


 Similar to stored procedures, they reduce the compilation cost by
caching the plans and reusing them for repeated executions.

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

 Cannot be used to perform actions that produce a side


effect such as modifying a table

 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.

 The header defines:


 Function name
 Input parameter name and data type
 Return parameter data type and optional name

 The body defines the action, or logic, the function is to


perform

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

 Scalar Functions return a single(scalar) value


 Table-Valued functions return a result set

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

CREATE FUNCTION getFullName ( @Name1 varchar(50) , @Name2 varchar(50) )


RETURNS varchar(100)
AS
BEGIN
RETURN (@ Name1 + ‘ ‘ + Name2)
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

SET @tempFullName = LTrim(RTrim(@fullName))


SET @spcPosition = CHARINDEX( ' ', @tempFullName)

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:

SELECT dbo. extractLastName( ‘Genet Abebe’)

SELECT dbo. extractLastName( FullName )


FROM Employee

SELECT dbo. extractLastName( FullName) + ‘@hilcoe.com’


FROM Student

13
Scalar UDF – Example
CREATE FUNCTION getTotalSalary (@depId int)
RETURNS decimal(8,2)
AS
BEGIN
DECLARE @totSalary decimal(8,2)

SELECT @totSalary = SUM(Salary)


FROM Employee
WHERE DepID = @depId

RETURN @totSalary
END

14
Using Scalar UDF – Example
Different ways of using the User-Defined Function:

SELECT dbo.getTotalSalary (4)

SELECT DepartmentName, dbo.getTotalSalary (depId)


FROM Department

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;

-- Calling the function


dbo.Age_In_Days('01-Jan-2007', DEFAULT));

17
Scalar UDF – Example
CREATE FUNCTION CalculateAge (@dateOfBirth Date )
RETURNS INT
AS
BEGIN
DECLARE @AGE INT

SET @AGE = DATEDIFF(YEAR, @dateOfBirth, GETDATE()) -


CASE
WHEN ( MONTH(@dateOfBirth) > MONTH(GETDATE()) ) OR
(MONTH(@dateOfBirth) = MONTH(GETDATE()) AND
DAY(@dateOfBirth) > DAY(GETDATE()))
THEN 1
ELSE 0
END
RETURN @AGE
END

18
Using Scalar UDF – CalculateAge()
SELECT dbo.CalculateAge(‘1931-02-14’ )

SELECT FirstName, LastName, dbo.CalculateAge(dob)


FROM Employee

SELECT FirstName + ‘ ‘ + LastName AS ‘Employee Name’


FROM Employee
ORDER BY dbo.CalculateAge(dob) DESC

SELECT FirstName + ‘ ‘ + LastName AS ‘Student Name’


FROM Student
WHERE dbo.CalculateAge(dateOfBirth) < 30

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

 Table-Valued Functions are categorized into two types:


 INLINE TVFs and
 MULTI-STATEMENT TVFs

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
)

 Using the function:


SELECT * FROM funcEmpByDepartment(2)

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 )

-- Calling the Function:


SELECT *
FROM fn_GetStudentsByGender(‘Female’)

SELECT Name, Gender, DOB, DepartmentName


FROM fn_GetStudentsByGender('Male') Emp
JOIN Department Dept on Dept.ID = Emp.DeptID
26
Inline Table-Valued UDF – Example
CREATE FUNCTION funcTableColumns(@tableName varchar(100))
RETURNS TABLE
AS
RETURN
(
SELECT sc.name
FROM SysColumns sc
JOIN SysObjects so ON sc.id = so.id
WHERE so.name = @tableName
)

Using the function:


SELECT * FROM funcTableColumns('Employee')

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

 The function body is defined in a BEGIN...END block


 A RETURN statement is used without a return value
 You do not need the TWO-PART name when using the
function

28
Multi-Statement
User-Defined Functions

Database Programming
Multi-Statement Table-Valued UDF
SYNTAX

CREATE FUNCTION functionName


( @param1 Datatype , @param 2 Datatype , … )

RETURNS @tableVar TABLE ( column definitions )


AS
BEGIN
function Body

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:

SELECT EmployeeID , EmpName , Department


FROM GetEmployeesByDepartment(1)

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

INSERT INTO @contacts


SELECT first_name, last_name, phone, 'Customer '
FROM Customer
RETURN
END 35
Functions - Examples
CREATE FUNCTION GetClients ( @clientName nvarchar(max) = null )
RETURNS TABLE
RETURN (
SELECT *
FROM Clients as a
WHERE ((a.ClientName = @clientName) or a.ClientName is null)
)

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

2. Modify the getEmployeeNames() function so that it


accepts the name of a department (DepName) and
returns the names of all the employees working in that
department

3. Write a function named getNumberOfEmployee() that


returns the number of employees in a department when
given name of a department (DepName)

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)

SELECT @UPrice = UnitPrice


FROM Product
WHERE ProductID = @prodID

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

SELECT dbo.getUnitPrice(SOD.ProductID ) * SOD.OrderQty


FROM SalesOrderDetail SOD
WHERE SOD.SalesOrderID = 1

SELECT SUM( dbo.getUnitPrice(SOD.ProductID ) * SOD.OrderQty )


FROM SalesOrderDetail SOD
WHERE SOD.SalesOrderID = 1

47
Create function for calculating the Total Amount

CREATE FUNCTION getTotalAmount(@salesOrderID int)


RETURNS decimal(12,2)
AS
BEGIN

DECLARE @totAmt decimal(12,2), @UPrice decimal(12,2)

SELECT @totAmt = SUM(dbo.getUnitPrice(SOD.ProductID) * SOD.OrderQty )


FROM SalesOrderDetail SOD
WHERE SOD.SalesOrderID = @salesOrderID

RETURN @totAmt
END

48

You might also like