Professional Documents
Culture Documents
User-Defined Functions
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 CalculateAge (@dateOfBirth Date )
RETURNS INT
AS
BEGIN
DECLARE @AGE INT
17
Using Scalar UDF – CalculateAge()
SELECT dbo.CalculateAge(‘1931-02-14’ )
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
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
)
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 )
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
27
Multi-Statement Table-Valued UDF
SYNTAX
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:
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
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
34
Functions - Examples
-- Create function for calculating the Total Amount
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
38