What is a Function
What is a Function
What is a Function
• A function is a set of SQL statements that perform a specific task.
• Basically, it is a set of SQL statements that accept only input parameters, perform actions and return the result.
Function can return an only single value or a table.
• We can’t use a function to Insert, Update, Delete records in the database table(s).
• If you have to repeatedly write large SQL scripts to perform the same task, you can create a function that performs
that task.
• Of course, you could create a stored procedure to group a set of SQL statements and execute them, however,
stored procedures cannot be called within SQL statements. Functions, on the other hand, can be.
Basic Syntax of Function
• CREATE FUNCTION [database_name.]function_name (parameters)
RETURNS data_type AS
BEGIN
SQL statements
RETURN value
END;
Built-In Functions
• SQL server adds some built-in functions to every database.
• Built-in functions are grouped into different types depending upon their functionality.
• Scalar Function: Scalar functions operate on a single value and return a single value
• Aggregate Functions: Aggregate functions operate on a collection of values and return a single value.
• Scalar Function: The user-defined scalar function also returns a single value as a result of actions performed by
the function.
• Inline Table-Valued Function: The user-defined inline table-valued function returns a table variable as a result of
actions performed by the function.
• Functions can have only input parameters for it whereas Procedures can have input or output parameters.
• Functions can be called from Procedure whereas Procedures cannot be called from a Function.
• Procedures cannot be utilized in a SELECT statement whereas Function can be embedded in a SELECT
statement.
• Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section
whereas Function can be.
• An exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a
Function.