This post will explain different types of UDFs with simple examples.
User Defined Function / UDF
- Unlike SP (Stored Procedure) when you are expecting an input from a simple set of query then you will use UDF, or simply called as Function.
- Another unique feature of UDF is, it can be called from/within a SQL statement, which is not possible with SP.
Types of UDFs
Below are the three types of Functions/UDFs:
1. Scalar Function
- Scalar UDFs return a single value, similar to built-in functions such as OBJECT_NAME(), or GETDATE(), which returns a single string, integer, or date. The output of these functions are based on the input parameters.
- You cannot return values with a user-defined data type from scalar UDFs, but only system-supplied data type.
- The scalar UDFs can return any scalar data type, with the exception of TIMESTAMP.
- Below example is returning a single INT.
CREATE FUNCTION FunctionName (inputParams)
RETURNS INT
AS
RETURN
(
<Your single SELECT statement>
);
2. Table-Value / In-line Function
- In-line UDFs return a single row or multiple rows and can contain a single SELECT statement.
- UDFs are limited to a single SELECT.
- But select statement can return multiple values.
- Below example is returning a Table.
CREATE FUNCTION FunctionName (inputParam)
RETURNS TABLE
AS
RETURN
(
<Your single SELECT statement>
);
3. Multi-statement Table-value Function
- As the name suggests, multi-statement UDFs can contain any number of statements that can populate the table variable prior to returning it.
- Multi-statement UDFs are useful in scenarios where in you need to return a set of rows but the logic is too complex to be contained in a single SELECT statement.
- Note that although you can use INSERT, UPDATE, and DELETE statements against the table variable (which is being returned), a function cannot modify data in a permanent table.
- Example:
CREATE FUNCTION FunctionName (inputParams)
RETURNS @TableName TABLE (Columns)
AS
BEGIN;
<Multiple statements to populate table variable>
RETURN;
END;
Summary
We have described the three types of UDFs in simple words, along with a single example of each.
Your feedback
Your feedback is of paramount importance to us, provide your valuable inputs; what else you would like to read about, or if you would like the author to elaborate on any specific topic from this article, or any other article on this blog.
Disclaimer
The material presented in this blog is to help educate the developers, and the author(s) & owner(s) of this blog are not responsible of any damage arising out of use of the code snippets or any other contents of this blog.
Comments
Post a Comment