Functions (Transact-SQL)

This section describes the built-in functions and user-defined functions that can be used in Transact-SQL statements.

Types of Functions

Transact-SQL functions are categorized into several types:

Common Built-in Functions

SQL Server provides a rich set of built-in functions for various purposes:

String Functions

These functions manipulate string data. Examples include:

SELECT UPPER('sql server') AS UppercaseString;
SELECT LEN('Microsoft') AS StringLength;

Numeric Functions

These functions perform mathematical operations. Examples include:

SELECT ROUND(123.456, 2) AS RoundedValue;
SELECT CEILING(7.3) AS CeilingValue;

Date and Time Functions

These functions work with date and time values. Examples include:

SELECT GETDATE() AS CurrentDateTime;
SELECT DATEADD(day, 5, GETDATE()) AS DateAfterFiveDays;

System Functions

These functions return information about the system or current session. Examples include:

SELECT @@VERSION AS SQLServerVersion;
SELECT DB_NAME() AS CurrentDatabase;

User-Defined Functions (UDFs)

You can create your own functions in Transact-SQL to encapsulate logic and improve code reusability.

Note: User-defined functions can be scalar, inline table-valued, or multi-statement table-valued.

Creating a Scalar User-Defined Function

A scalar UDF returns a single value. Here's an example:

CREATE FUNCTION dbo.CalculateDiscount
(
    @Price DECIMAL(10, 2),
    @DiscountRate DECIMAL(4, 2)
)
RETURNS DECIMAL(10, 2)
AS
BEGIN
    RETURN @Price * (1 - @DiscountRate);
END;
GO

-- Example usage:
SELECT dbo.CalculateDiscount(100.00, 0.10) AS FinalPrice;

Creating an Inline Table-Valued Function

An inline TVF returns a table and is defined by a single `SELECT` statement.

CREATE FUNCTION dbo.GetEmployeesByDepartment
(
    @DepartmentName NVARCHAR(50)
)
RETURNS TABLE
AS
RETURN
(
    SELECT EmployeeID, FirstName, LastName
    FROM Employees
    WHERE Department = @DepartmentName
);
GO

-- Example usage:
SELECT * FROM dbo.GetEmployeesByDepartment('Sales');

Function Permissions

To execute a function, users need the `EXECUTE` permission on the function. Permissions for creating functions typically require `CREATE FUNCTION` permission in the database.