Multiline Table Value Functions

Today, I continuing my talk about database objects that are associated with stored (compiled) code. A user-defined function is any Transactional SQL (TSQL) or Common Language Runtime (CLR) routine that accepts parameters, performs an action, and returns the result of that action as a value.

The return value can either be a scalar (single) value datatype or a composite (multiple) values table. These Table Valued Functions (TVF) functions come in two flavors: inline and multiline. I am going to concentrate on the later.

Like most Data Definition Language (DDL) constructs, a user define function has three operations associated with it: CREATE FUNCTION, ALTER FUNCTION and DROP FUNCTION

I will be using the Adventure Works 2012 sample database supplied by Microsoft during this talk. The SQL snippet below, drops the function if it exists, creates a new stub function, and alters the function to be identical to the original.

Please note that the return type of the function is a strongly typed local TABLE variable. Also, the function definition contains multiple lines of T-SQL. The example above takes in a color (@Name) as input and returns various (@RgbValues) as output .

The code snippet below returns the Red Green Blue (RGB) properties for the color named ‘Yellow’.

Unlike its INLINE cousin, the MULTILINE table variable function (TVF) is strongly typed and can be coded to do multiple tasks.

Many of the Dynamic Management Functions are either INLINE or MULTILINE table variable function (TVF). Please see the example below that shows the internals of the missing index columns.

For a brief recap, I went over three of the five different ways to define a function. For both the scalar and table valued functions, we can extend the functionality of SQL Server by using the Common Language Runtime (CLR) using assemblies. That is an advanced topic that will not be talked about today.

Next time, I am going to go over the two APPLY operators that can be used to add in Table Valued Function result sets to a SELECT statement.

Multiline Table Value Function Example

Related posts

Leave a Comment