In SQL, a User-Defined Function (UDF) is a custom function that allows you to encapsulate reusable logic within your queries. UDFs can be used for various purposes such as calculations, transformations, or returning complex results. They make your code cleaner, more readable, and modular. Below is a guide to creating UDFs in SQL, along with examples.
There are generally two types of UDFs:
A scalar function performs a calculation or transformation and returns a single value. The syntax for creating a scalar function is:
CREATE FUNCTION function_name (parameters) RETURNS return_type AS BEGIN -- function logic RETURN value END;
Here’s an example of a simple scalar function that calculates the area of a circle given its radius:
CREATE FUNCTION CalculateArea (@radius FLOAT) RETURNS FLOAT AS BEGIN RETURN 3.14159 * @radius * @radius; END;
This function accepts a radius as input and returns the area of the circle. To use it, you can call it in a SELECT statement:
SELECT dbo.CalculateArea(5) AS CircleArea;
The result would be:
CircleArea ------------ 78.53975
A table-valued function returns a table, which can be used in queries just like a regular table. The syntax for creating a TVF is:
CREATE FUNCTION function_name (parameters) RETURNS TABLE AS RETURN ( -- query that returns a table );
Here’s an example of a TVF that returns employees from a specific department:
CREATE FUNCTION GetEmployeesByDepartment (@departmentId INT) RETURNS TABLE AS RETURN ( SELECT EmployeeID, Name FROM Employees WHERE DepartmentID = @departmentId );
You can use this function in a query as follows:
SELECT * FROM dbo.GetEmployeesByDepartment(3);
This query will return all employees in the department with ID 3.
User-defined functions have several benefits, including:
User-defined functions are a powerful feature in SQL that allow you to encapsulate complex logic and reuse it across queries. Whether you are creating scalar functions for calculations or table-valued functions to return result sets, UDFs help improve code efficiency, readability, and maintenance. Practice creating and using these functions to enhance your SQL skills.