Lect 3

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

Lebanese French University

College of Engineering and Computer Science


Department of Information technology
Second Semester
2023 - 2024

Asst. Lect. Mateen Naser Ridha


mnaser.naser@lfu.edu.krd

Advanced Database II
Lecture 3
SQL Server Functions

Advanced Database II| IT & CE| Stage #3 2/28/2024 2


Outlines

• User-Defined Functions
• Advantages of UDFs
• Types of User-Defined Functions
• Creation and Execution of User-Defined Functions

Advanced Database II| IT & CE| Stage #3 2/28/2024 3


What a User-Defined Function?

▪ A user-defined function (UDF) is a routine that can


take parameters, perform calculations or other actions,
and return a result.

▪ It is defined and created by the user.

▪ The output of the function depend on the input that is


supplied when it’s invoked.

Advanced Database II| IT & CE| Stage #3 2/28/2024 4


Calling a User-Defined Function
▪ The code inside the function is not executed when the function is created. It’s only
executed when the function is invoked.

▪ We can invoke a UDF by the code, just like you’d call a system function.

▪ For example, you could use a UDF in a WHERE clause in order to narrow the
results of a SELECT statement.

Advanced Database II| IT & CE| Stage #3 2/28/2024 5


Types of User-Defined Function

1. Scalar functions (SFs)

2. Table-valued functions (TVFs)

Inline table-valued UDFs

Multi-statement table-valued UDFs

Advanced Database II| IT & CE| Stage #3 2/28/2024 6


Types of User-Defined Function
1. Scalar UDFs

▪ Scalar UDFs are similar to functions in other procedural languages.

▪ They take zero or more parameters and return a single value.

▪ The return value of scalar functions is always a single value.

▪ scalar functions can be called using the EXECUTE statement, the same way

as stored procedures.

Advanced Database II| IT & CE| Stage #3 2/28/2024 7


User-Defined Function
Creating a scalar function parameters

CREATE FUNCTION [schema_name.]function_name (parameter_list)


specify the data type of
the return value in RETURNS data_type
the RETURNS statement.
BEGIN
statements
RETURN value
END
The schema name is optional. If
RETURN statement to you don’t explicitly specify it, SQL
return a value inside the Server uses dbo by default.
body of the function.

Advanced Database II| IT & CE| Stage #3 2/28/2024 8


User-Defined Function

Scalar Function example

The compute_costs function computes


additional costs that arise when all
budgets of projects increase. The single
input variable, @percent, specifies the
percentage of increase of budgets.

Calling the created function

Advanced Database II| IT & CE| Stage #3 2/28/2024 9


User-Defined Function

Scalar Function example

CREATE FUNCTION fnGetEmpFullName (


Create function to get emp full name @FirstName varchar(50),
@LastName varchar(50)
)
RETURNS varchar(100)
AS
BEGIN
RETURN (SELECT @FirstName +’ ‘ + @LastName);

END
Calling the created function

Select fnGetEmpFullName ( FirstName, LastName ) as Name, Salary from Employee

Advanced Database II| IT & CE| Stage #3 2/28/2024 10


User-Defined Function
Scalar Function example

Let to calculate the total price of each product in the Products table, and the result is displayed
in a column named Total.
Step 1: Create Function

Advanced Database II| IT & CE| Stage #3 2/28/2024 11


User-Defined Function
Scalar Function example

Step 2: Call the Function using dbo.CalculateTotal( ):

Advanced Database II| IT & CE| Stage #3 2/28/2024 12


Types of User-Defined Function
2. Table-valued functions (TVFs)
▪ The table-valued function returns one or more records as a table data type.

▪ This type of function is special because it returns a table that you can query the
results of a join with other tables.

▪ A Table Valued function is further categorized into an “Inline Table Valued Function”
and a “Multi-Statement Table Valued Function”.

Advanced Database II| IT & CE| Stage #3 2/28/2024 13


Types of User-Defined Function

2.1. Inline Table-Values Functions


▪ The user-defined inline table-valued function returns a table variable as a result of
actions performed by the function.
▪ The value of the table variable should be derived from a single SELECT statement.
▪ The result of the query becomes the return value of the function.
▪ There is no need for a BEGIN-END block in an Inline function.

Advanced Database II| IT & CE| Stage #3 2/28/2024 14


Types of User-Defined Function
2.1. Inline Table-Values Functions
• What is the syntax for creating Inline Table Valued Function ?

To create a scalar function the following syntax is used.

CREATE FUNCTION function-name (<optional Parameters>)


RETURNS TABLE
AS
RETURN
<SELECT statement>

Advanced Database II| IT & CE| Stage #3 2/28/2024 15


Types of User-Defined Function
2.1. Inline Table-Values Functions
Inline Table-Values Function SELECT * FROM GetAllStudents(60)
example

CREATE FUNCTION GetAllStudents(@Mark INT)


RETURNS TABLE
AS
RETURN
SELECT *FROM Student WHERE Marks>=@Mark

To execute this function use the following command.

Advanced Database II| IT & CE| Stage #3 2/28/2024 16


Types of User-Defined Function
2.1. Inline Table-Values Functions

Inline Table-Values Function


example
CREATE FUNCTION FN_GetStudentDetailsByID (
@ID INT )
Create a function that accepts student id as RETURNS TABLE
input and returns that student details from the AS
table.
RETURN (SELECT * FROM Student WHERE ID = @ID)

Once you create the above function, then call it like below:

SELECT * FROM FN_GetStudentDetailsByID(2)

Advanced Database II| IT & CE| Stage #3 2/28/2024 17


Types of User-Defined Function
2.2. Multi-statemen Table-Values Functions

▪ A Multi-Statement contains multiple SQL statements enclosed in BEGIN-END blocks.

▪ In the function body you can read data from databases and do some operations.

▪ In a Multi-Statement Table valued function the return value is declared as a table


variable and includes the full structure of the table to be returned.

▪ We can define this function by using a table variable as the return value. Inside the
function, we execute multiple queries and insert data into this table variable.

Advanced Database II| IT & CE| Stage #3 2/28/2024 18


Types of User-Defined Function
2.2. Multi-statemen Table-Values Functions
The Multi-Statement Table Valued Function in SQL Server is the same as the Inline Table-Valued
Function but with the following differences:

Multi-Statement Table-Valued Function In Inline Table-Valued Function


1. Body can contain more than one 1. Body contains only a single Select
statement statement prepared by the return
statement
2. The structure of the table returned from 2. The structure of the table is defined by
the function is defined by user. the Select statement that is going to
return from the function body.

Advanced Database II| IT & CE| Stage #3 2/28/2024 19


2.2. Multi-statemen Table-Values Functions

Syntax CREATE FUNCTION function-name (Parameters)


RETURNS @TableName TABLE
(Column_1 datatype,
.
.
Column_n datatype
)
AS
BEGIN
Statement 1
Statement 2
.
.
Statement n
RETURN
END

Advanced Database II| IT & CE| Stage #3 2/28/2024 20


Types of User-Defined Function
2.2. Multi-statemen Table-Values Functions
Multi-Statement Table-Valued
Function example
CREATE FUNCTION MSTVF_GetEmployees()
RETURNS @Table Table (ID int, Name nvarchar(20), DOB
Multi-Statement Table-Valued functions Date)
in SQL Server that return the following AS
output. BEGIN
INSERT INTO @Table
SELECT ID, Name, Cast(DOB AS Date)
FROM Employee
Return
End

Advanced Database II| IT & CE| Stage #3 2/28/2024 21


2.2. Multi-statemen Table-Values Functions

Multi-Statement Table-Valued
Function example

To execute this function

SELECT * FROM GetAvg('Ram')

Advanced Database II| IT & CE| Stage #3 2/28/2024 22


Update/Delete functions
1. Update User - Defined Functions
• To modify a table-valued function, you use the ALTER instead of CREATE keyword.
The udfProductInYear function now
ALTER FUNCTION udfProductInYear ( returns products whose model year
@start_year INT, between a starting year and an ending
@end_year INT year.
)
The following statement calls the udfProductInYear
RETURNS TABLE
function to get the products whose model years
AS are between 2017 and 2018:
RETURN
SELECT
product_name,
model_year,
list_price
FROM
products
WHERE
model_year BETWEEN @start_year AND @end_year

Advanced Database II| IT & CE| Stage #3 2/28/2024 23


Update/Delete functions
2. Delete User - Defined Functions

To remove an existing user-defined function created by the CREATE FUNCTION statement,


you use the DROP FUNCTION statement as follows:

DROP FUNCTION [ IF EXISTS ] [ schema_name. ] function_name;

The IF EXISTS option allows you to drop the For example:


function only if it exists. Otherwise, the -- dropping previously created scalar
statement does nothing. If you attempt to function DROP FUNCTION scalar_func; --
remove a non-existing function without dropping previously created tabular function
specifying the IF EXISTS option, you will get DROP FUNCTION table_valued_func;
an error.

Advanced Database II| IT & CE| Stage #3 2/28/2024 24


Thanks
Any Question

Advanced Database II| IT & CE| Stage #3


?
2/28/2024 25

You might also like