Week-8-UDF1
Week-8-UDF1
Science
PRACTICAL NO.09
Development of User Defined Functions (UDFs) – Creating Scalar and PLO CLO LL
Table Valued Functions for Code Reusability
3 4 2
Topic: Creating Scalar and Table-Valued Functions for Code Reusability
1. Objectives
• To practically create Scalar UDFs and Table-Valued UDFs to promote code reuse.
2. Overview
In this lab, students will explore User-Defined Functions (UDFs) in SQL Server to enhance
database programming. Functions allow repeated logic to be centralized, making SQL queries
cleaner, faster, and easier to maintain. Students will develop both scalar functions, which
return single values, and table-valued functions, which return sets of data.
3. Introduction
User-Defined Functions (UDFs) are powerful database objects that encapsulate frequently
used logic within reusable units. Functions can accept parameters, perform operations such as
calculations or filtering, and then return results to the caller. SQL Server supports two main
types of UDFs:
Definition
User-Defined Functions (UDFs) are programmable routines in SQL that accept input
parameters, perform a specific action (such as a calculation, modification, or querying data), and return a
result to the calling program.
SQL Server allows developers to create their own functions, which can return either:
UDFs are similar to functions in traditional programming languages like C++ or Java, allowing for code
modularity and reusability in database development.
Explanation
• Encapsulate repetitive code: Instead of repeating complex expressions or queries, you can define
a function once and reuse it whenever needed.
• Enhance code clarity and readability: Functions make SQL queries easier to read and maintain.
• Improve database logic reusability: Functions can be used across different queries, procedures,
and triggers.
SQL Server supports two major types of UDFs:
1. Scalar Functions
• Can be used anywhere a scalar expression is allowed (such as in SELECT, WHERE, or ORDER BY
clauses).
Example Use Case:
A scalar function returns a single value. Here's an example of creating a scalar function that takes two integers as input and
returns their sum:
sql
CREATE FUNCTION dbo.AddTwoNumbers (
@Num1 INT, @Num2 INT
Database system Lab Department of Computer
Science
)
RETURNS INT AS
BEGIN
RETURN @Num1 + @Num2; END
Usage:
sql
SELECT dbo.AddTwoNumbers(5, 10) AS SumResult;
of TVFs:
• Inline TVF: Return the result directly from a single SELECT query (better performance).
• Multi-Statement TVF: Allow multiple SQL statements to build the table before returning it.
Step 1: Introduction to User-Defined Functions (UDFs)
Definition:
User-Defined Functions are routines that accept parameters, perform an action (such as a calculation or
querying data), and return the result of that action as a value.
Types of UDFs:
Task: Create a Scalar UDF that returns the full name of a student.
Expected Output:
FullName
John Doe
Task: Create a TVF that returns students with marks greater than a given number.
Example:
Database system Lab Department of Computer
Science
Suppose you have a table:
1 Ali Raza 90
3 Sara Khan 85
Task: Create a TVF that returns student records along with their grade based on marks.
Database system Lab Department of Computer
Science
Example:
Database system Lab Department of Computer
Science
How to Call the Function:
1 Ali Raza 90 A
2 Sara Khan 82 B
sql
INSERT INTO Employees (EmployeeID, EmployeeName, EmployeeSalary, DepartmentID)
VALUES
(1, 'Alice Johnson', 85000.00, 2),
(2, 'Bob Smith', 95000.00, 1),
(3, 'Charlie Brown', 78000.00, 2),
Database system Lab Department of Computer
Science
(4, 'David Wilson', 120000.00, 3),
(5, 'Eve Davis', 95000.00, 1),
(6, 'Frank Miller', 110000.00, 3),
(7, 'Grace Lee', 65000.00, 1),
(8, 'Hank Ford', 92000.00, 2),
(9, 'Irene Taylor', 105000.00, 3),
(10, 'Jack White', 53000.00, 2);
Exercise 1
Objective: Create a scalar function to calculate the area of a circle.
• Instructions:
1. Create a scalar function named CalculateCircleArea.
2. It should take one parameter, @Radius, of type FLOAT.
3. The function should return the area of the circle using the formula ( \pi
\times \text{@Radius}^2 ).
4. Use the value of ( \pi ) as 3.14159.
Solution
Here is how you can create the CalculateCircleArea scalar function in SQL Server:
sql
CREATE FUNCTION dbo.CalculateCircleArea
(
@Radius FLOAT
)
RETURNS FLOAT
AS
BEGIN
DECLARE @Area FLOAT;
SET @Area = 3.14159 * @Radius * @Radius;
RETURN @Area;
END;
Database system Lab Department of Computer
Science
Explanation
• Function Name: dbo.CalculateCircleArea is the name given to the function. The
dbo.
Example Usage
You can use the function in a SELECT statement to calculate the area of a circle
with a given radius. Here's an example:
sql
SELECT dbo.CalculateCircleArea(10) AS CircleArea;
This query will calculate and return the area of a circle with a radius of 10 units,
using the CalculateCircleArea function we just created.
Exercise 2
Objective: Create an inline table-valued function to return employees from a specific
department.
• Instructions:
1. Create an inline table-valued function named GetEmployeesByDepartment.
2. The function should take one parameter, @DepartmentID of type INT.
3. The function should return a table containing employee IDs
and names for the given department ID.
Solution
For this solution, we will assume that there is an existing table called Employees with at
least the following columns: EmployeeID (an identifier for the employee),
EmployeeName (the name of the employee), and DepartmentID (the department to
which the employee belongs).
sql
CREATE FUNCTION
dbo.GetEmployeesByDepartment (
@DepartmentID INT
)RETURNS TABLE
AS RETURN (
SELECT EmployeeID,
Database system Lab Department of Computer
Science
EmployeeName
FROM Employees
WHERE DepartmentID = @DepartmentID
);
Explanation
Function Name: The function is named GetEmployeesByDepartment and uses the dbo. schema.
• Parameter: The function accepts a single parameter,
@DepartmentID, which signifies the department for which we
want to retrieve employees. It is of type INT.
• Return Type: The function returns a TABLE. There is no need to
define the return type explicitly when using inline functions, as it
is derived from the SELECT statement within the function.
• Logic: The SELECT statement is used to retrieve EmployeeID and
EmployeeName from the Employees table where DepartmentID
matches the parameter @DepartmentID.
Example Usage
Once the function is created, you can use it in a SELECT statement to retrieve employee details for a
specific department. Here's an example:
sql
SELECT * FROM dbo.GetEmployeesByDepartment(2);
This query will return a table of employees who belong to the department with an ID of 2,
displaying their EmployeeID and EmployeeName. If your database setup includes more columns
or conditions, you can adjust the SELECT query accordingly.
Exercise 3
Objective: Create a multi-statement table-valued function to return the top N highest- paid
employees.
Instructions:
Create a multi-statement table-valued function named GetTopPaidEmployees.
The function should take one parameter, @TopN of type INT.
It should return a table containing the employee IDs, names, and salaries of the top N
highest-paid employees.
Solution
For this solution, let's assume there is a table called Employees with at least the following
columns: EmployeeID (an identifier for the employee), EmployeeName (the name of the
employee), and EmployeeSalary (the salary of the employee).Here is how you would define the
multi-statement table-valued function:
sql
CREATE FUNCTION
dbo.GetTopPaidEmployees (
@TopN INT
)RETURNS @TopEmployees TABLE (
EmployeeID INT,
Database system Lab Department of Computer
Science
EmployeeName NVARCHAR(100),
EmployeeSalary DECIMAL(10, 2)
)
AS
BEGIN
-- Insert the top N highest-paid employees into the return table
INSERT INTO @TopEmployees
SELECT TOP(@TopN)
EmployeeID, EmployeeName,
EmployeeSalary
FROM Employees
ORDER BY EmployeeSalary DESC;
RETURN;
END;
Explanation
Function Name: The function is named GetTopPaidEmployees and is prefixed with
dbo. to specify its schema.
Parameter: The function accepts one parameter, @TopN, which will determine how
many of the highest-paid employees to retrieve. It is of type INT.
Return Type: The function returns a table defined as @TopEmployees. This table
includes:
EmployeeID: the identifier for the employee.
EmployeeName: the name of the employee.
EmployeeSalary: the salary of the employee, with a precision of 10 and scale of 2.
Logic:
The INSERT INTO @TopEmployees command is used to populate the return table with
the results of the SELECT query.
The SELECT statement uses the TOP(@TopN) clause to limit the results to the specified
number of highest-paid employees.
The results are ordered in descending order by EmployeeSalary to ensure that only the
highest salaries are selected.
Return Statement: The function explicitly returns the filled table at the end.
Example Usage
After creating the function, you can call it in a SELECT statement to get the top N highest-paid employees. Here’s an
example usage:
sql
SELECT * FROM dbo.GetTopPaidEmployees(5);
This query will return a table containing the EmployeeID, EmployeeName, and EmployeeSalary
of the top 5 highest-paid employees from the Employees table.
Database system Lab Department of Computer
Science
Task 1: Create a scalar function GetStudentStatus that returns "Pass" if marks are above 40,
otherwise "Fail".
Task 2: Create a TVF GetFailingStudents to return students scoring less than 40.
Scenario:
You are working as a database developer for a university’s student portal system.
The portal frequently needs to display a student's full name based on their first and last name
stored separately in the database.
Task:
Create a Scalar Function named GetStudentFullName that accepts FirstName and LastName
as input parameters and returns the full name.
Hint: Use string concatenation inside your function.
Scenario:
The university dean wants to generate a report of students who scored above 85 marks in
their final exams.
Task:
Create an Inline Table-Valued Function named GetTopPerformers that accepts a minimum
marks parameter and returns a table containing StudentID, FullName, and Marks of all
qualifying students.
Scenario:
The examination department wants a quick way to determine whether a student has passed or
failed a subject, based on marks.
Task:
Develop a Scalar Function named GetPassFailStatus that:
• Returns 'Pass' if the marks are greater than or equal to 40, and 'Fail' otherwise.
Scenario:
The administration needs a dynamic report that shows each student's name, marks, and
corresponding grade (A, B, C, D).
Task:
Design a Multi-Statement Table-Valued Function named GetStudentGrades that:
90-100 A
80-89 B
70-79 C
Below 70 D
Scenario:
In a corporate HR database, you are asked to create a function that calculates bonuses based
on employee salary:
• 20% bonus if salary is above 100,000.
Database system Lab Department of Computer
Science
• 5% bonus otherwise.
Task:
Create a Scalar Function named CalculateBonus that returns the bonus amount based on
given salary input.
Hint: Apply CASE conditions to calculate bonus.