559 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owls only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Inline and multi-statement table-valued functions
Part three of a four-part series of blogs
This blog shows you how to create table-valued functions in SQL (ie functions which return a table of data!).
A multi-statement table-valued function (which I wall call from now on the equally unmemorable MSTVF) is a function which returns a table of data, but only after some additional processing.
Suppose that you frequently want to show all of the actors or directors in a films database who were born in a particular year. To this end you want to get the following function working:
-- show actors and directors born in 1945
PersonName AS Who,
PersonRole AS What,
CONVERT(char(10),Dob,103) AS DOB
So the function called fnPeopleBornYear will take an integer parameter (the year of birth), and spit out some rows. Here's what the example below would show:
The results for the Wise Owl Movies database: two directors and two actors.
It would be possible to create this as a simple in-line table-valued function using the UNION ALL keyword, but I'm going to build it up in two stages: first add the actors, then add the directors.
Here is the basic syntax of a multi-statement table-valued function (someone give these things a snappier name, please!):
CREATE FUNCTION fnName(
-- can have 0, 1, 2 or more parameters
@param2 datatype, ...
-- define table to return
RETURNS @TableName TABLE (
-- typically insert rows into this table
-- eventually, return the results
With that in mind, let's look at how we could write our fnPeopleBornYear function.
Here's how you could write the SQL for our function. First pass in the parameter giving the year in question:
CREATE FUNCTION fnPeopleBornYear(
Next, define what the output from the function will be - a table with 3 columns:
RETURNS @people TABLE (
You now need to begin your function proper:
-- all code lies in a BEGIN / END block
You can now add one row to our table for each actor born in the year in question:
-- insert the actors born in this year into table
INSERT INTO @people (
Year(ActorDob) = @BirthYear
I've written a separate blog on SQL statements for inserting rows into tables, if you need a refresher on this.
Now you can add the directors born in the year in question into the table:
-- now add the directors born in this year
INSERT INTO @people (
Year(DirectorDob) = @BirthYear
Finally, you can end the function by saying that you want to return the set of rows built up:
-- return the results
Phew - I don't have to write the phrase Multi-Statement Table-Valued Function again!
As the last part of this blog, we'll have a look at some of the limitations of table-valued functions.
|Parts of this blog|
25 Aytoun Street