UDFs in SQL Server are reusable routines that accept parameters, perform calculations or data manipulation, and return a scalar value or table.
UDFs encapsulate business logic, reduce code duplication, and simplify complex queries by returning either a single value or an inline table expression.
SQL Server supports scalar functions, inline table-valued functions (iTVF), and multi-statement table-valued functions (mTVF). Choose scalar for single values, iTVF for set-based logic, and mTVF when multiple statements are required.
Use CREATE FUNCTION schema_name.function_name
, define input parameters, the return type, and include a single RETURN
statement.
This scalar UDF sums all total_amount
for a given customer in the Orders
table:
CREATE FUNCTION dbo.fn_customer_ltv (@customer_id INT)
RETURNS DECIMAL(12,2)
AS
BEGIN
DECLARE @ltv DECIMAL(12,2);
SELECT @ltv = SUM(total_amount)
FROM Orders
WHERE customer_id = @customer_id;
RETURN ISNULL(@ltv,0);
END;
GO
Return a single SELECT
as the function body; the columns match the table definition in the query.
CREATE FUNCTION dbo.fn_latest_orders (@since DATE)
RETURNS TABLE
AS
RETURN (
SELECT o.*
FROM Orders o
WHERE o.order_date >= @since
);
GO
Call scalar UDFs in SELECT, WHERE, or ORDER BY clauses. Join iTVFs like regular tables.
SELECT c.name, dbo.fn_customer_ltv(c.id) AS lifetime_value
FROM Customers c
ORDER BY lifetime_value DESC;
SELECT *
FROM dbo.fn_latest_orders('2024-01-01') lo
JOIN Customers c ON c.id = lo.customer_id;
Prefer inline TVFs for set logic—they can be inlined by the optimizer. Keep scalar UDFs deterministic and avoid side-effects. Always schema-qualify function names.
Use ALTER FUNCTION
to modify the definition without dropping permissions. Remove a function with DROP FUNCTION schema.function
.
No. SQL Server UDFs are read-only. Use stored procedures for inserts, updates, or deletes.
Use PRINT
statements, temporary variables, and execute the internal logic as a standalone query before embedding in the function.
SQL Server caches execution plans for deterministic UDFs, improving subsequent calls. Mark functions as SCHEMABINDING to enhance stability.