WISE OWL EXERCISES
- Simple Queries (4)
- Setting criteria using WHERE (5)
- Calculations (7)
- Calculations using dates (4)
- Basic joins (8)
- More exotic joins (2)
- Aggregation and grouping (8)
- Views (5)
- Subqueries (5)
- Stored procedures (5)
- Variables (8)
- Parameters and return values (11)
- Testing conditions (1)
- Looping (3)
- Scalar functions (6)
- Transactions (5)
- Creating tables (5)
- Temporary tables and table variables (9)
- Table-valued functions (6)
- Derived tables and CTEs (13)
- Dynamic SQL (4)
- Pivots (2)
- Triggers (2)
- Archived (70)
SQL | Table-valued functions 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!
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(
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.