Microsoft Learn

T-SQL Functions

Functions are routines that accept parameters, perform an action, and return a value. SQL Server provides built-in functions for a wide range of purposes, and you can also create your own user-defined functions.

Built-in Functions

SQL Server offers a rich set of built-in functions categorized by their purpose:

Aggregate Functions

These functions perform a calculation on a set of values and return a single value.

Scalar Functions

These functions return a single value based on the input provided. They can operate on string, date, numeric, and other data types.

Table-Valued Functions

These functions return a table as a result. They can be inline or multi-statement.

User-Defined Functions (UDFs)

You can create your own functions to encapsulate complex logic or reusable computations.

Types of UDFs:

Creating a User-Defined Function:

The basic syntax for creating a function is:

CREATE FUNCTION schema_name.function_name
(
    @parameter1 data_type,
    @parameter2 data_type = default_value
)
RETURNS return_type
[WITH SCHEMABINDING]
AS
BEGIN
    -- T-SQL statements to perform the function's logic
    DECLARE @result data_type;
    -- ... calculation ...
    SET @result = ...;
    RETURN @result;
END;

Example: Scalar UDF

CalculateTotalSalary

Calculates the total salary for an employee, including a bonus.

CREATE FUNCTION dbo.CalculateTotalSalary (@baseSalary DECIMAL(10, 2), @bonus DECIMAL(10, 2) = 0)
RETURNS DECIMAL(10, 2)
AS
BEGIN
    RETURN @baseSalary + @bonus;
END;

Usage:

SELECT dbo.CalculateTotalSalary(50000, 5000) AS TotalSalary;

Example: Inline Table-Valued Function

GetProductsByCategory

Returns all products belonging to a specified category.

CREATE FUNCTION dbo.GetProductsByCategory (@CategoryID INT)
RETURNS TABLE
AS
RETURN
(
    SELECT ProductID, ProductName, UnitPrice
    FROM Production.Products
    WHERE CategoryID = @CategoryID
);

Usage:

SELECT * FROM dbo.GetProductsByCategory(1);

Key Considerations

For detailed information on specific functions, refer to the official Microsoft documentation.