SQL | Scalar functions exercise | Create a scalar function to count the total number of letters

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.

Software ==> SQL  (198 exercises)
Version ==> Any version of SQL Server
Topic ==> Scalar functions  (6 exercises)
Level ==> Relatively easy
Subject ==> SQL training
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). Once you've done this:
  1. Go into SQL Server Management Studio;
  2. Open the SQL file you've just unzipped (you can press CTRL + O to do this); then
  3. Execute this script.

This will generate the database that you'll need to use in order to do this exercise (note that the database and script are only to be used for exercises published on this website, and may not be reused or distributed in any form without the prior written permission of Wise Owl).

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.

Create a function called fnLetterCount which takes two parameters:

Parameter What it should contain
@First The name of an event
@Second The details for an event

Your function should sum:

  • The length in letters of the event name (using the LEN function); and
  • The length in letters of the event details column (again using LEN).

Your function should then return this value as an integer.  As a reminder, here's the syntax of a basic function:


@Parameter1 datatype1,



RETURNS ReturnDataType





Test that your function works by running a query like this:

-- this should return the number 7 (4 + 3)

SELECT dbo.fnLetterCount('Wise','Owl')

AS 'Number of letters'

Incorporate this function within a query to list out events in order of the total number of characters used, with the shortest first:

First few events

The first few events this query should return.

Optionally, save this as Pointless statistic.sql, then close it down.

You can unzip this file to see the answers to this exercise, although please remember this is for your personal use only.
This page has 0 threads Add post