Use scalar functions in Microsoft Fabric Warehouse and SQL analytics endpoint

Applies to: ✅ SQL analytics endpoint and Warehouse in Microsoft Fabric

A T-SQL scalar user-defined function (UDF) accepts input parameters and returns one value, such as a number, string, or date. Use it in expressions in Microsoft Fabric Warehouse or the SQL analytics endpoint.

You can create, alter, and drop scalar functions in both Warehouse and the SQL analytics endpoint. The SQL analytics endpoint remains read-only for persisted table data.

Why use scalar functions?

Use scalar functions to reuse business rules and calculations inside SQL expressions:

  • Encapsulate business logic. Give calculations, conditional rules, conversions, or formatting logic a descriptive name.
  • Calculate values from row data. Pass columns as arguments instead of repeating an expression.
  • Maintain one definition. Update a calculation behind a stable function signature without rewriting the formula in calling queries.

A scalar function returns one value, not rows or multiple result sets. Use a stored procedure for workflows, data changes, or multiple results.

Note

If you already have a published Fabric user data function, or your logic is better suited to Python and its libraries, see Use user data functions in Fabric Data Warehouse (preview).

Supported syntax

Use the following syntax to define and call T-SQL scalar functions, and to manage permissions.

Create or alter a function

For T-SQL syntax, see CREATE FUNCTION (Transact-SQL) and ALTER FUNCTION (Transact-SQL).

CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name
(
    [ @parameter_name [ AS ] parameter_data_type [ = default ] [ ,...n ] ]
)
RETURNS return_data_type
    [ WITH <function_option> [ ,...n ] ]
[ AS ]
BEGIN
    [ function_body ]
    RETURN scalar_expression [;]
END
[;]

ALTER FUNCTION [ schema_name. ] function_name
(
    [ @parameter_name [ AS ] parameter_data_type [ = default ] [ ,...n ] ]
)
RETURNS return_data_type
    [ WITH <function_option> [ ,...n ] ]
[ AS ]
BEGIN
    [ function_body ]
    RETURN scalar_expression [;]
END
[;]

<function_option> ::=
    INLINE = AUTO
    | SCHEMABINDING
    | RETURNS NULL ON NULL INPUT
    | CALLED ON NULL INPUT

Square brackets indicate optional syntax, braces indicate alternatives, and n indicates repetition. Use CREATE OR ALTER to create a function or update its definition. ALTER requires an existing function. Include parentheses even if you don't define parameters. Choose only one of the two null-input options.

ENCRYPTION, EXECUTE AS, and NATIVE_COMPILATION aren't supported. INLINE = ON and INLINE = OFF aren't supported; INLINE = AUTO is the only supported INLINE value.

Drop a function

For T-SQL syntax, see DROP FUNCTION (Transact-SQL).

DROP FUNCTION [ IF EXISTS ] [ schema_name. ] function_name
[;]

Call a function

Call a scalar function as an expression with a schema-qualified name. This abbreviated form shows a standalone call. For full query syntax, see SELECT (Transact-SQL).

SELECT schema_name.function_name
    ( [ { expression | DEFAULT } [ ,...n ] ] )
    [ AS column_alias ]
[;]

You can also call a scalar function with EXECUTE and capture its return value:

{ EXEC | EXECUTE } @result =
    schema_name.function_name
    [ [ @parameter_name = ] { literal | @variable | DEFAULT } [ ,...n ] ]
[;]

When calling a scalar function with EXECUTE, don't enclose arguments in parentheses. Arguments can be literals, variables, or DEFAULT, but not expressions. To pass an expression result, assign it to a variable first. After the first named argument, all subsequent arguments must also be named. For full syntax, see EXECUTE (Transact-SQL).

Grant permissions on a function

For T-SQL syntax, see GRANT object permissions (Transact-SQL).

GRANT <function_permission> [ ,...n ]
    ON OBJECT::[ schema_name. ] function_name
    TO principal [ ,...n ]
    [ WITH GRANT OPTION ]
[;]

<function_permission> ::=
    ALTER | CONTROL | EXECUTE | REFERENCES | TAKE OWNERSHIP | VIEW DEFINITION

Use WITH GRANT OPTION to let the recipient grant the permission to others. Calling a scalar function requires EXECUTE, even when the call appears in a SELECT statement.

Deny permissions on a function

Use the same function_permission list as for GRANT. For T-SQL syntax, see DENY (Transact-SQL).

DENY <function_permission> [ ,...n ]
    ON OBJECT::[ schema_name. ] function_name
    TO principal [ ,...n ]
    [ CASCADE ]
[;]

CASCADE also denies the permission to principals who received it from the target principal. It's required when the target holds the permission with GRANT OPTION.

Revoke permissions on a function

Use the same function_permission list as for GRANT. For T-SQL syntax, see REVOKE (Transact-SQL).

REVOKE <function_permission> [ ,...n ]
    ON OBJECT::[ schema_name. ] function_name
    FROM principal [ ,...n ]
    [ CASCADE ]
[;]

CASCADE also revokes permissions delegated by the recipient.

Create, alter, and drop a function

Use schema-qualified names. When you alter a function, include its complete signature, options, and body. ALTER and CREATE OR ALTER preserve object-level permissions. Changing argument or return types can break callers.

Keep each function definition in its own batch. GO separates batches in SQL tools. If you're using an application driver, submit each batch separately without sending GO.

For example, create or update a function with one input parameter:

CREATE OR ALTER FUNCTION dbo.fn_GetValue (@Value int)
RETURNS int
AS
BEGIN
    RETURN @Value;
END;
GO

Use DROP FUNCTION IF EXISTS to remove a function without an error if it doesn't exist. Dropping the function removes its permissions and can break callers. Schema-bound objects that depend on the function can prevent you from dropping it. Alter or drop those objects first. If you recreate the function, reapply its grants.

DROP FUNCTION IF EXISTS dbo.fn_ObsoleteExample;

Function body

Use RETURN to return a scalar result. Unlike a stored-procedure return code, the result isn't restricted to an integer.

Within the supported T-SQL surface area, you can:

  • Declare local variables, assign values with SET or SELECT, and branch with IF...ELSE.
  • Call supported built-in functions and other UDFs.
  • Read tables, views, and inline table-valued functions.
  • Use WHILE loops or multiple RETURN statements when the inlining requirements allow them.

You can't use data-changing statements, dynamic SQL, stored-procedure calls, temporary tables, or TRY...CATCH inside a scalar UDF. Use a stored procedure for these operations. Session settings such as SET NOCOUNT ON don't belong in a function, but you can use SET to assign values to local variables.

You can't use every built-in function in a UDF body, like RAND(). The built-in functions used in the body can also affect which inlining techniques the UDF is eligible for. For details, see Built-in functions in scalar UDFs.

Inlining requirements

A scalar UDF must be inlineable to be used in a query over user tables.

Microsoft Fabric Data Warehouse applies inlining and chooses an applicable technique based on your function's definition:

Technique Common scenarios
Expression Block inlining Computation without references to tables, views, inline table-valued functions, or other scalar UDFs. Supports constructs such as WHILE, multiple RETURN statements, and time-dependent built-ins.
Scalar UDF inlining Can handle data access and nested UDF calls, but requires a single RETURN and excludes constructs such as WHILE, BREAK, CONTINUE, and time-dependent built-ins.

Inlining transforms the UDF body into part of the calling query during query compilation.

The following table provides a more detailed comparison of supported function-body constructs.

Function-body construct Expression Block inlining Scalar UDF inlining
Scalar expressions, local variables, and IF/ELSE Supported Supported
WHILE loops, including BREAK and CONTINUE Supported Not supported
Multiple RETURN statements Supported Not supported
NEWID() Supported Not supported
Time-dependent functions (for example, GETDATE() and SYSDATETIME()) Supported Not supported
Table, view, or inline TVF access Not supported Supported
Calls to scalar UDFs Not supported Supported

A function definition can qualify for one or both techniques.

CREATE FUNCTION and ALTER FUNCTION reject non-inlineable definitions by default. WITH INLINE = AUTO lets you create or alter a non-inlineable function for supported standalone execution, such as assigning its result to a variable. It doesn't make the function inlineable or allow its use in a query over user tables. See Create a scalar UDF for standalone execution.

The techniques also differ in the calling-query shapes they support:

Query feature Expression Block inlining Scalar UDF inlining
UDF calls in the SELECT list, WHERE, or JOIN ... ON Supported Supported
Direct UDF calls in GROUP BY or HAVING Supported Not supported
Direct UDF calls in ORDER BY Supported Not supported
CTEs in the calling query Supported Not supported
ROLLUP, CUBE, or GROUPING SETS Not supported Not supported

If any UDF call relies on Scalar UDF inlining, the entire query must meet that technique's calling-query requirements.

If the calling context isn't supported, you might see this error: Scalar UDF execution is currently unavailable in this context.

For examples of making a function inlineable and rewriting calling queries, see Create scalar user-defined functions.

Schema binding

WITH SCHEMABINDING prevents SQL changes to referenced objects that would invalidate the function. Use two-part names and keep references in the same database. Any UDFs you reference must also be schema-bound. To create the function, you need REFERENCES on referenced objects.

To keep schema binding when you update the function, include SCHEMABINDING in the new definition. Schema binding doesn't make a non-inlineable function inlineable.

Nested calls

A function can call another function in its body:

CREATE OR ALTER FUNCTION dbo.fn_GetValueCaller (@Value int)
RETURNS int
AS
BEGIN
    RETURN dbo.fn_GetValue(@Value);
END;
GO

If a function's body references a table, view, or inline table-valued function, the nesting limit is 4 levels. Otherwise, it's 32 levels. If you exceed the limit, the calling function chain fails. Nested calls must still meet the inlining requirements. See Supported function constructs.

Call scalar functions

Use a scalar function in an expression, for example in a SELECT (Transact-SQL) statement:

SELECT dbo.fn_GetValue(25) AS Result;

You can also call dbo.fn_GetValue with EXECUTE and capture its return value:

DECLARE @Result int;

EXECUTE @Result = dbo.fn_GetValue @Value = 25;
SELECT @Result AS Result; -- Returns 25.

Pass parameter values

Specify input types explicitly, including string length or decimal precision and scale. Scalar UDF parameters support all data types supported for Warehouse table columns, plus additional data types available for scalar expressions. For more information, see Data types in Fabric Data Warehouse.

When calling a scalar UDF as part of an expression, pass arguments in parameter order and specify DEFAULT explicitly to use a parameter's default value. You can pass literals, variables, column references, or expressions, including built-in calls.

When calling a scalar UDF with EXECUTE, different argument-passing rules apply. You can supply named arguments in a different order or omit arguments for parameters with default values. Supplied arguments must be literals, variables, or DEFAULT, not expressions.

DECLARE @Input int = 20;

SELECT dbo.fn_GetValue(@Input + 5) AS Result; -- Returns 25.

Use default parameter values

A parameter default is a constant or NULL. In a function expression, pass DEFAULT to use it; unlike a stored procedure, you can't omit the argument. Passing NULL supplies a null value, not a request for the default.

CREATE OR ALTER FUNCTION dbo.fn_GetValueOrDefault (@Value int = 10)
RETURNS int
AS
BEGIN
    RETURN @Value;
END;
GO

SELECT dbo.fn_GetValueOrDefault(DEFAULT) AS Result; -- Returns 10.
SELECT dbo.fn_GetValueOrDefault(NULL) AS Result;    -- Returns NULL.

With EXECUTE, you can omit a parameter that has a default value:

DECLARE @Result int;

EXECUTE @Result = dbo.fn_GetValueOrDefault;
SELECT @Result AS Result; -- Returns 10.

Handle null inputs

CALLED ON NULL INPUT is the default: the body runs even when an argument is NULL. Use it when the function must provide its own null handling:

CREATE OR ALTER FUNCTION dbo.fn_ValueOrZero (@Value int)
RETURNS int
WITH CALLED ON NULL INPUT
AS
BEGIN
    RETURN COALESCE(@Value, 0);
END;
GO

SELECT dbo.fn_ValueOrZero(NULL) AS Result; -- Returns 0.

Alternatively, RETURNS NULL ON NULL INPUT returns NULL for a null input without requiring the body to evaluate it. Choose the option that matches how you want the function to handle nulls. Scalar functions don't have OUTPUT parameters or return result sets; use the returned value in the caller's expression.

Security and permissions

To connect to the warehouse or SQL analytics endpoint, you need at least Read permission on the item, either directly or through a workspace role. See Fabric security and SQL granular permissions.

If you're a workspace Admin, Member, or Contributor, you can create functions.

Operation Required SQL permission
Create a function CREATE FUNCTION in the database and ALTER on the target schema.
Alter a function ALTER on the function.
Drop a function CONTROL on the function or ALTER on its schema.
Call a scalar function EXECUTE on the function. Permissions on referenced objects also depend on ownership chaining.
Bind a function to referenced objects REFERENCES on those objects, in addition to the creation or alteration permissions.
Read a function definition VIEW DEFINITION on the function.
Deny or revoke a permission CONTROL on the function.

You can also meet these requirements through higher-level permissions. To grant a permission, you need GRANT OPTION or a higher permission that lets you grant it.

For example, grant execution and definition access separately. Replace FunctionUsers with the name of your Microsoft Entra user or group.

GRANT EXECUTE ON OBJECT::dbo.fn_GetValue TO [FunctionUsers];
GRANT VIEW DEFINITION ON OBJECT::dbo.fn_GetValue TO [FunctionUsers];

You can't run CREATE USER. Fabric creates the database user automatically when you grant or deny permissions.

Prefer object-level grants. A schema-level EXECUTE grant includes current and future executable objects in that schema.

Use DENY to block a permission, including grants inherited through roles or groups. It doesn't restrict the function's owner. For example, block calls:

DENY EXECUTE ON OBJECT::dbo.fn_GetValue TO [FunctionUsers];

Use REVOKE to remove an explicit GRANT or DENY without blocking other grants. For example, remove the preceding denial:

REVOKE EXECUTE ON OBJECT::dbo.fn_GetValue FROM [FunctionUsers];

Removing the denial doesn't restore the earlier explicit GRANT. Other grants can still allow access.

Ownership chaining can allow access to referenced tables when the objects have the same owner. If the ownership chain is broken, you need additional permissions.

SQL permissions don't secure other access paths to the same lakehouse data, such as Spark. See SQL analytics endpoint security.

Metadata and function definitions

Query these catalog views and functions in the database that contains the function:

Catalog view or function Information
sys.objects (Transact-SQL) T-SQL scalar functions have type = 'FN' and type_desc = 'SQL_SCALAR_FUNCTION'.
sys.parameters (Transact-SQL) Input names, order, and types. parameter_id = 0 describes the scalar return value; positive IDs describe inputs.
sys.sql_modules (Transact-SQL) Source text in definition, schema-binding status, is_inlineable, and inline_eligibility_mask.
OBJECT_ID (Transact-SQL) Returns a function's object ID from its schema-qualified name. Specify 'FN' for a T-SQL scalar function.
OBJECT_NAME (Transact-SQL) Returns a function's name, without its schema, from its object ID.
OBJECT_SCHEMA_NAME (Transact-SQL) Returns a function's schema name from its object ID.
SCHEMA_NAME (Transact-SQL) Returns a schema name from a schema ID, such as sys.objects.schema_id.
OBJECT_DEFINITION (Transact-SQL) Returns a function's T-SQL definition from its object ID, not its name.
sys.sql_expression_dependencies (Transact-SQL) Recorded references to tables, views, and other functions.

For example, retrieve a function's definition and inlining metadata:

SELECT OBJECT_SCHEMA_NAME(m.object_id) AS SchemaName,
    OBJECT_NAME(m.object_id) AS FunctionName,
    m.definition AS FunctionDefinition,
    m.is_inlineable,
    m.inline_eligibility_mask
FROM sys.sql_modules AS m
WHERE m.object_id = OBJECT_ID('dbo.fn_GetValue', 'FN');

is_inlineable reports definition eligibility, not whether a particular calling query is supported. inline_eligibility_mask is 0 for neither technique, 1 for Scalar UDF inlining, 2 for Expression Block inlining, and 3 for either.

The metadata you can see depends on the objects you own and the permissions you have. Name and definition lookups can return NULL if the function doesn't exist or you don't have metadata permissions. EXECUTE doesn't let you read the definition. These lookups use the current database. Object IDs aren't globally unique.

To find a T-SQL function's parameter defaults, read its definition. sys.parameters doesn't store them in default_value.

In sys.sql_expression_dependencies, filter referencing_id by the function's object ID to find what it uses, or referenced_id to find resolved callers in the current database. Cross-database or unresolved references can have a NULL referenced_id; inspect referenced_database_name, referenced_schema_name, and referenced_entity_name as well. To read this catalog view, you need database-level VIEW DEFINITION and SELECT on sys.sql_expression_dependencies.