0% found this document useful (0 votes)
2 views

Practical Scenarios UDF

The document outlines practical User-Defined Function (UDF) implementations in SQL Server for various scenarios, including calculating employee age, validating email formats, and retrieving employees by department. It describes different types of UDFs: Scalar, Inline Table-Valued, and Multi-Statement Table-Valued, each serving specific purposes. The conclusion emphasizes the modular and reusable nature of UDFs for business logic and data retrieval.

Uploaded by

bilalmhasan855
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Practical Scenarios UDF

The document outlines practical User-Defined Function (UDF) implementations in SQL Server for various scenarios, including calculating employee age, validating email formats, and retrieving employees by department. It describes different types of UDFs: Scalar, Inline Table-Valued, and Multi-Statement Table-Valued, each serving specific purposes. The conclusion emphasizes the modular and reusable nature of UDFs for business logic and data retrieval.

Uploaded by

bilalmhasan855
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

practical User-Defined Function (UDF) implementations using SQL Server for different

scenarios.

Scenario 1: Calculate Employee Age

A company needs to determine employees' ages dynamically from their Date of Birth
(DOB).

Solution: Scalar UDF

CREATE FUNCTION dbo.CalculateAge (@DOB DATE)


RETURNS INT
AS
BEGIN
DECLARE @Age INT
SET @Age = DATEDIFF(YEAR, @DOB, GETDATE()) -
CASE WHEN (MONTH(@DOB) > MONTH(GETDATE()))
OR (MONTH(@DOB) = MONTH(GETDATE()) AND DAY(@DOB) >
DAY(GETDATE()))
THEN 1 ELSE 0 END
RETURN @Age
END;

Usage

SELECT EmployeeID, Name, dbo.CalculateAge(DateOfBirth) AS Age


FROM Employees;

Benefit: Ensures accurate employee age calculation without modifying queries.

Scenario 2: Validate Email Format

A system needs to check if stored email addresses follow a basic pattern.

Solution: Scalar UDF

CREATE FUNCTION dbo.IsValidEmail (@Email NVARCHAR(255))


RETURNS BIT
AS
BEGIN
IF @Email LIKE '_%@_%._%'
RETURN 1
RETURN 0
END;

Usage

SELECT EmployeeID, Email, dbo.IsValidEmail(Email) AS IsValid


FROM Employees;

Benefit: Ensures only valid emails are stored or used.


Scenario 3: Get Employees by Department

A manager needs to fetch employees based on their department dynamically.

Solution: Inline Table-Valued UDF

CREATE FUNCTION dbo.GetEmployeesByDepartment (@DeptName NVARCHAR(50))


RETURNS TABLE
AS
RETURN
(
SELECT EmpID, EmpName, JobTitle, Department
FROM Employees
WHERE Department = @DeptName
);

Usage

SELECT * FROM dbo.GetEmployeesByDepartment('HR');

Benefit: Provides dynamic, parameterized filtering without modifying SQL queries.

Scenario 4: Get Full Name of an Employee

A web app needs to concatenate first and last names.

Solution: Scalar UDF

CREATE FUNCTION dbo.GetFullName (@FirstName NVARCHAR(50), @LastName


NVARCHAR(50))
RETURNS NVARCHAR(100)
AS
BEGIN
RETURN @FirstName + ' ' + @LastName
END;

Usage

SELECT EmployeeID, dbo.GetFullName(FirstName, LastName) AS FullName


FROM Employees;

Benefit: Ensures a consistent format for displaying full names.

Scenario 5: Get Top 3 Best-Selling Products

A retailer wants to dynamically retrieve the top 3 best-selling products.

Solution: Inline Table-Valued UDF


CREATE FUNCTION dbo.GetTopSellingProducts ()
RETURNS TABLE
AS
RETURN
(
SELECT TOP 3 ProductID, ProductName, SUM(QuantitySold) AS TotalSold
FROM Sales
GROUP BY ProductID, ProductName
ORDER BY TotalSold DESC
);

Usage

SELECT * FROM dbo.GetTopSellingProducts();

Benefit: Provides real-time tracking of top products.

Scenario 6: Convert Celsius to Fahrenheit

A weather application requires temperature conversion.

Solution: Scalar UDF

CREATE FUNCTION dbo.ConvertToFahrenheit (@Celsius FLOAT)


RETURNS FLOAT
AS
BEGIN
RETURN (@Celsius * 9/5) + 32
END;

Usage

SELECT dbo.ConvertToFahrenheit(25) AS Fahrenheit;

Benefit: Ensures accurate and reusable temperature conversions.

Scenario 7: Retrieve Employees Hired in the Last X Years

A company needs to check employees hired within the last N years.

Solution: Multi-Statement Table-Valued UDF

CREATE FUNCTION dbo.GetEmployeesHiredLastNYears (@Years INT)


RETURNS @EmployeeTable TABLE
(
EmployeeID INT,
Name NVARCHAR(100),
HireDate DATE
)
AS
BEGIN
INSERT INTO @EmployeeTable
SELECT EmployeeID, Name, HireDate
FROM Employees
WHERE DATEDIFF(YEAR, HireDate, GETDATE()) <= @Years;

RETURN;
END;

Usage

SELECT * FROM dbo.GetEmployeesHiredLastNYears(5);

Benefit: Provides HR departments with easy filtering of recent hires.

Scenario 8: Calculate Employee Bonus Based on Salary

A company wants to apply a 10% bonus for employees earning below $5000.

Solution: Scalar UDF

CREATE FUNCTION dbo.CalculateBonus (@Salary DECIMAL(10,2))


RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN CASE
WHEN @Salary < 5000 THEN @Salary * 0.10
ELSE 0
END
END;

Usage

SELECT EmployeeID, Salary, dbo.CalculateBonus(Salary) AS Bonus


FROM Employees;

Benefit: Automates bonus calculations based on salary conditions.

Conclusion
UDFs in SQL Server provide modular and reusable solutions for business logic,
validations, and data retrieval.

 Scalar Functions return a single value (e.g., age, email validation, salary bonus).
 Inline Table-Valued Functions return a table and are used in queries like views.
 Multi-Statement Table-Valued Functions allow complex operations before
returning a table.

You might also like