# Exercise: Create a function to list episodes for a given series and author

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

The answer to the exercise will be included and explained if you attend the course listed below!

 Category ==> SQL  (192 exercises) Topic ==> Table-valued functions  (6 exercises) Level ==> Average difficulty Course ==> Advanced SQL
Before you can do this exercise, you'll need to download and unzip this file (if you have any problems doing this, click here for help).

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

First (if you haven't already done so) run the script shown above to generate the Doctor Who training database.

Create a function to list out the episodes for any given series number and part of an author name.  This could begin:

CREATE FUNCTION fnChosenEpisodes(

@SeriesNumber int,

@AuthorName varchar(100)

)

RETURNS TABLE

AS

For example, you could run this SQL query:

SELECT * FROM dbo.fnChosenEpisodes(1,'russell')

This would show the 9 series one episodes written by Russell T. Davies:

The first 2 or 3 of the 9 episodes in series 1 written by Russell T. Davies

Functions can't have optional parameters, but you can pass dummy values and detect them.  Amend your function so that it shows:

• Episodes for any series if you pass the first argument as Null;
• Episodes for any author if you pass the second argument as Null.

To help you know whether you've succeeded, here's what 4 possible combinations should show:

-- there is 1 episode written by Steven Moffat for series 2

SELECT COUNT(*) FROM dbo.fnChosenEpisodes(2,'moffat')

-- -- there are 14 episodes in series 2 (for any author)

SELECT COUNT(*) FROM dbo.fnChosenEpisodes(2,null)

-- there are 32 episodes written by Steven Moffat (for any series)

SELECT COUNT(*) FROM dbo.fnChosenEpisodes(null,'moffat')

-- there are 117 episodes (any series, any author)

SELECT COUNT(*) FROM dbo.fnChosenEpisodes(null,null)

Optionally, save your query as Series and author.sql, then close it down.