2. UDF Overview
• A user-defined function is an executable database object
that contains SQL statements.
– Also called a UDF or a function
• Functions always return a value.
– A scalar-valued function returns a single value.
– A table-valued function returns an entire table.
• You can call, or invoke, a scalar-valued function from
within any expression.
• You can invoke a table-valued function anywhere you’d
refer to a table or a view.
3. Function Requirements
• You must specify the name of the schema when
invoking a UDF.
• A function can’t have a permanent effect on the
database.
– Can’t use a function to run an action query against
the database.
4. Function Organization – 1
• Can be defined with input parameters
– Specify after the function name in the CREATE
FUNCTION statement.
– Each parameter can be assigned an optional default
value.
• Functions don’t use output parameters.
– Specify the data type to return in the RETURNS
clause
5. Function Organization – 2
• The statements within the function require a
BEGIN…END block.
– The RETURN statement in this block specifies the
value to be returned.
• When using a function, list the parameters within
parentheses after the function name.
– Can’t pass parameters by name.
– To use the default value of a parameter, code the
DEFAULT keyword in place of the parameter value
in the list.
6. Scalar Function Syntax
CREATE FUNCTION [schema_name.]function_name
([@parameter_name data_type [= default]] [, ...])
RETURNS data_type
[WITH [ENCRYPTION] [, SCHEMABINDING] [,
EXECUTE_AS_clause]]
[AS]
BEGIN
[sql_statements]
RETURN scalar_expression
END