0% found this document useful (0 votes)
6 views14 pages

Week-8-UDF1

Uploaded by

afsaattiq1
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)
6 views14 pages

Week-8-UDF1

Uploaded by

afsaattiq1
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/ 14

Database system Lab Department of Computer

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 understand the concept and purpose of User-Defined Functions (UDFs) in SQL.


• To learn the difference between Scalar and Table-Valued Functions (TVFs).

• To practically create Scalar UDFs and Table-Valued UDFs to promote code reuse.

• To apply UDFs in real-world database operations and queries.

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:

• Scalar Functions (return single values)


• Table-Valued Functions (return tables)

Incorporating UDFs significantly improves code modularity, readability, and


maintainability in SQL development.
4. Purpose

The purpose of this lab is to:

• Develop hands-on skills for creating and using User-Defined Functions.

• Enhance code reusability by modularizing database logic.

• Improve SQL programming efficiency and maintainability.

• Enable students to apply UDFs in various real-world data retrieval scenarios.

5. Key Learning Objectives

After completing this lab, students will be able to:


Database system Lab Department of Computer
Science
• Define what User-Defined Functions are and why they are important.

• Create and execute Scalar User-Defined Functions.

• Create and execute Table-Valued Functions (both Inline and Multi-Statement).

• Use UDFs inside SQL queries for enhanced modular programming.


• Apply best practices when designing and implementing 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:

• A single scalar value (e.g., a number, string, or date), or

• A complete table (set of rows and columns).

UDFs are similar to functions in traditional programming languages like C++ or Java, allowing for code
modularity and reusability in database development.
Explanation

User-Defined Functions (UDFs) are mainly created to:

• 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

• Return a single value (such as int, nvarchar, float, etc.).

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

2. Table-Valued Functions (TVFs)

• Return a table (set of rows and columns).


• Can be used as a table source in SELECT queries, joins, etc.
Example Use Case:
Return all students who have marks greater than a given threshold. There are two types

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:

• Scalar Functions: Return a single value.

• Table-Valued Functions (TVFs): Return a table.


Step 2: Creating a Scalar Function

Task: Create a Scalar UDF that returns the full name of a student.

Example: Create a function to concatenate First Name and Last Name.


Database system Lab Department of Computer
Science

How to Call the Function:

Expected Output:

FullName

John Doe

Step 3: Creating an Inline Table-Valued Function (iTVF)

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:

Now, create a TVF:

How to Call the Function:

Expected Output Example:

StudentID FirstName LastName Marks

1 Ali Raza 90

3 Sara Khan 85

Step 4: Creating a Multi-Statement Table-Valued Function (mTVF)

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:

Expected Output Example:

StudentID FullName Marks Grade

1 Ali Raza 90 A

2 Sara Khan 82 B

Step 5: Best Practices for UDFs

• Use meaningful names for functions and parameters.

• Always define the schema (dbo.) to avoid ambiguity.


• Keep functions simple and focused on a single task.

• Use SCHEMABINDING option if needed to improve performance.

• Document your function (what it does, parameters, and output).

Lab exercise with solution


Sample Table Definition
sql
CREATE TABLE Employees
(
EmployeeID INT PRIMARY KEY,
EmployeeName NVARCHAR(100),
EmployeeSalary DECIMAL(10,
DepartmentID INT
);

Sample Data Insertion


Here are some sample records to insert into the Employees table:

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.

prefix specifies the schema, which is optional but commonly used.


• Parameter: The function takes one parameter, @Radius, which
represents the radius of the circle. It is of type FLOAT to
accommodate decimal values.
• Return Type: The function returns a FLOAT, representing the area of the circle.
• Logic: Inside the function, we declare a variable @Area to store
the computed area. We then use the formula ( \pi \times
\text{@Radius}^2 ) to calculate the area and store it in @Area.
• Return Statement: The function returns the calculated area.

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

Here's how you would define the inline table-valued function:

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

Step 6: Lab Activity Practice

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.

Activity Tasks (Scenario-Based Questions)

Activity 1: Student Portal Enhancement

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.

Activity 2: Top Performers Report

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.

Hint: Use a SELECT query inside the RETURN statement.


Database system Lab Department of Computer
Science

Activity 3: Student Status Checker

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:

• Takes a student's marks as input.

• Returns 'Pass' if the marks are greater than or equal to 40, and 'Fail' otherwise.

Hint: Use IF...ELSE logic or a CASE expression.

Activity 4: Generating Student Grade Sheets

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:

• Accepts a minimum marks value.

• Returns StudentID, FullName, Marks, and Grade.


Grade Criteria:

Marks Range Grade

90-100 A

80-89 B

70-79 C

Below 70 D

Hint: Insert into a table variable inside your function.

Activity 5: Employee Bonus Calculator (Advanced)

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

• 10% bonus if salary is between 50,000 and 100,000.

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

You might also like