Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

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

17
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

18
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')

19
Check Point
 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

20
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

22
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

23
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)

24
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
25
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')

26
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

27
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

28
Multi-Statement Table-Valued UDF
CREATE FUNCTION GetEmployeesByDepartment (@myDepID INT)
RETURNS @empList TABLE
( EmployeeID int primary key NOT NULL
, EmpName varchar(100) NOT NULL
, Department varchar(100) NOT NULL
)
AS
BEGIN
INSERT @empList
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;
29
Multi-Statement Table-Valued UDF
 Using the function:

SELECT EmployeeID , EmpName , Department


FROM GetEmployeesByDepartment(1)

30
More Examples
on
User-Defined Functions

Database Programming
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

32
Functions - Examples
- - 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

33
Functions - Examples
-- Create function for calculating the Total Amount

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

34
Functions - Examples
-- 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

35
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

36
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 37
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)
)

38

You might also like