You are on page 1of 17

Link training tables with 2 parameters

If you haven't already done so, run the stored procedure in the above folder to generate
a database of training courses and delegates. This exercise uses the following tables:

The five tables you need to join together!

1. Create a stored procedure called spListDelegates which displays, for a given


company name and course name extract, the people who are attending courses.
If you leave either of the two parameters out, your stored procedure should show
all rows for that parameter.

Here are some ways in which you could test your stored procedure:
These calls to your procedure should return 1 (if you're looking for an exact company name
match), 20 and 124 delegates respectively.

Optionally, save the query to generate your stored procedure as Delegates for course
and company.sql, then close it down.

Linking events, countries and continents


USE the Historical Events database

2. Create a join to list out all of the Asian events in your database. This is trickier
than it looks, as you'll have to create an inner join not just to
the tblCountry table, but also to the tblContinent table so that you can put in
a WHERE clause:

An example of what the WHERE clause could look like

The final result of running your query should look like this:
Here the events are listed in date order

Save this query as Asian Events, and close it down.

List events with country type using CASE


USE the Historical Events database.

3. Use a CASE statement to show the type for each event, using the following
rules:

 If it's country 18, it must be United States


 If it's country 17, it must be UK
 Otherwise, it must be Somewhere else

The final results from running the query should look like this:

This query lists the events in date order

Save this query as Events by country type, then close it down.

List French events to do with Concorde


USE the Historical Events database.

4. Create a query which lists out all of the events to do with Concorde (ie which
have Concordesomewhere in the Description column):
Include the CountryId in your query, for reasons which will become apparent

Now add another WHERE clause to your query so that it only shows events to do with
Concorde which took place in country number 6 (France):

From glory to gloom ...

Discussion for the day - is the withdrawal of fast Concorde flights the only example in history of
mankind going backwards technologically?

Save this query as French Concorde events.sql, then close it down.

Listing first half of countries


USE the Historical Events database.

5. Create a query to list out the names of the first half of the countries in
the tblCountry table.

To put this a more helpful way, your query should list out the TOP 50 PERCENT of countries!

Your final results should look like this:


There are 21 countries, but SQL Server rounds up the odd half

Save this query as Listing first half of countries, and close it down.

Move person in procedure, and log if OK


If you haven't already done so, run the stored procedure in the above folder to generate
a database of training courses and delegates.

6. This exercise will create a procedure to allow you to move a person to a different
organisation. Your procedure will begin in a similar way to this:

The two arguments are the person to move, and the organisation to move them to

Create a log table to hold a record of every successful move:

Create 2 columns as shown here - initially your table will be empty

Write your stored procedure so that it:


 Begins a transaction
 Inserts a record in the log table recording that a person has been moved
 Runs an UPDATE statement to change the person's OrgId column value
 Commits the transaction if this doesn't generate an error, or rolls it back
otherwise

Try testing your stored procedure - here are 3 suggestions to try:

Existing constraints will ensure that you can only move someone to a company which already exists

Optionally, save the code to generate your stored procedure as Log person
moves.sql, then close it down.

Show closest events to birthday


USE the Historical Events database .

7. Create a query listing the events in the database, starting with the closest to your
birthday and finishing with the furthest away:

The results for an imaginary Wise Owl trainer born on 4th March 1964
You will need to use the ABS function, which returns the absolute value of a number. For example,
ABS(-8) = 8.

Save this query as Closest events to birthday.sql, then close it down.

Show directors and actors for given string


8. Create an in-line table-valued function which returns all of the film characters
containing a given string of text. For example:

You could use your function to show all of the characters containing BEN

When you run the sample command shown above, for example, you should see:

Include the FilmDirectorId column in the results from the function

Now write a SELECT statement which joins the results of your function to
the tblDirector table to show the people who have directed films containing characters
with particular names!
The results for BEN again - Steven Soderbergh dominates!

Save the query containing all of this code as Character search, then close it down.

Subqueries: first batch exercises


If you haven't already got it set up in SQL server, restore the Movies database from the
above folder.

9. Create a query to list out all the films which were made by directors who are
older than any of the actors in the database:

Your answer should look like this

Save this query as Films made by old directors.

Create a query to list out any films starring any of the 3 youngest actors in the database.

You can use SELECT TOP 3 in the subquery to list the 3 youngest actors, and DISTINCT to avoid
duplicates in the main query

Your final results should look like this:


Your results should look like this

Save this query as Youngest actors.

Use cursor to print each website


If you haven't already done so, run the stored procedure in the above folder to generate
a database of the world's leading websites.

10. Use a cursor to print out a list of the top 10 websites in terms of incoming links:

Use the PRINT statement to print out each website's details

Declare an integer variable to hold the position number, initialise it to 0 and increase it by 1 each
time you fetch another row from the cursor.

Optionally, save your work as Websites with links.sql, then close it down.

Use vbl to remember and redisplay @@rowcount


11. If you haven't already done so, run the stored procedure in the above folder to
generate a database of the world's leading websites.
Our task is to customise the standard (n row(s) affected) SQL message which appears
after running a query. To start this, first create a simple SELECT statement to list out all
of the columns and rows in the tblWebsite table:

This will list out 122 rows

When you run this query, it should produce the following message:

Your task is to replace this with a customised message

Add the following line of code (as always, no need to bother with the comment) to your
stored procedure:

This will suppress the row count message above

Now amend your stored procedure so that it summarises the rows affected as follows
(using the hint below):

The new version looks similar, but it has a heading, and the wording is subtly different

To do this, you'll need to declare a variable and set it equal to @@rowcount - otherwise
the PRINT statements will reset the row count, and you'll get the wrong answer!

When your stored procedure is working, optionally save the query which generates it
as RowCountWebsites.sql, then close it down.
Variable detail level for website query - Ifs
12. If you haven't already done so, run the stored procedure in the above folder to
generate a database of the world's leading websites. This database contains a
table of websites called tblWebsite with (among others) the following columns:

 WebsiteName (the name of the website)


 WebsiteUrl (the website's address)
 AlexaRankWorld (the website's ranking, as measured by Alexa)

Create a stored procedure which starts as follows:

Feel free to omit the comments and use different parameter names

Now write the rest of the stored procedure so that it does what the comments suggest it
should. For example, if you run the command EXEC spGooglySites 3 you should see:

The order of your rows may be different, but there should be 17 in all

Optionally, save the query to generate the stored procedure as Variable detail
level.sql, then close it down.
Websites going online between 2 variable dates
13. If you haven't already done so, run the stored procedure in the above folder to
generate a database of the world's leading websites. This database contains a
table of websites called tblWebsite, which has (among others) two columns
called:

 WebsiteName (the name of the website); and


 DateOnline (the date it first went online)

Create a stored procedure called spSchedules which takes two parameters:

 From date for searching (if not passed in, this should take the default value 1st
January 1990)
 To date for searching (if not passed in, this should take the default value 31st
December 1999)

The stored procedure should then show all websites registered between the two dates
passed.

Try testing your query out - here are some things to try:

A couple of examples to try - but feel free to use your own instead

Use your stored procedure to show that only one website went online in 1991. The
name might look vaguely familiar ...

Optionally, save the query to generate this stored procedure as Websites reg between
2 dates.sql, then close it down.

Count how many people by status – vbls


14. If you haven't already done so, run the stored procedure in the above folder to
generate a database of training courses and delegates.

The tblPersonStatus table contains two rows as follows:


A person is either current or obsolete!

By linking the tblPerson table to this tblPersonStatus table, create a simple query to
show the number of people who still work at their companies:

By declaring and using two variables


(called @NumberCurrent and @NumberObsolete, perhaps?) create a query to show
how many people there are in the database for each of the two statuses
(stati?) Current and Obsolete:

What the result of running your query should look like

Optionally, save this query as Count persons by status.sql, then close it down.

Create a function showing difference in lengths


15. USE the Historical Events database.

Import the query called Extra text function. If you try running this query, it falls over -
that's because the fnExtraText function doesn't yet exist!

This query should consider the extent to which the description of any event is longer than its short
name
Create the function (and test that it works), then save the script to create it
as CreatExtra text function.

Creating a view
USE Historical Events database.

16. Create a view using the view designer which will be a repeat of one we did in an
earlier exercise. The view should show for each country the number of events
occurring since 1990, but exclude countries with less than 5 events:

What you should see when you run your view

Save this view as vwEventsByCountry.

CTE for Spielberg films and actors


17. The aim of this exercise is to display all of the actors who have appeared in films
directed by Spielberg, but we'll do it in two passes, using a CTE:

The first few rows of the 24 actors we should see at the end

Yes, you could do this all with a single SELECT statement, but using the CTE - arguably - makes the
whole thing easier to understand.

To accomplish this:
 create a CTE which shows all of the films directed by Spielberg; then
 link the results of this CTE to the tblCast and tblActor tables to show the results
above

When you've finished, save this query as Spielberg, then close it down.

Delete adult and betting sites, then roll back


18. If you haven't already done so, run the stored procedure in the above folder to
generate a database of the world's leading websites.

This database contains a table called Data_at_14_Jan_2010, which contains the


source data for the other tables:

We're going to remove all BETTING and ADULT sites, such as the one shown selected

Write a query which:

 Begins a transaction
 Within this transaction, deletes all rows from the above table where
the Category column is Betting or Adult
 Stores how many rows are left in the table in an integer variable
 Rolls back the transaction
 Stores how many rows are in the table after this roll back (in a second integer
variable)
 Displays the final figures

Your query should display output similar to this, when run:

The transaction (if not rolled back) would have deleted 9 sites

Optionally, save this code as Delete sites then roll back.sql, then close it down.
Fn to count trainer ids
19. If you haven't already done so, run the stored procedure in the above folder to
generate a database of training courses and delegates.

Each row in the tblSchedule table contains a column called TrainerIds, giving details
of who is assigned to train on the course:

Scheduled course 1, for example, has trainers number 21 and 93 assigned to it

We will create a function called fnCountIds to count how many trainers there are
assigned to each course (note that exactly the same function could also count how
many resources are assigned). The following Hint to help you do this:

Count the number of trainers by seeing how long the string of ids is with and without its commas,
and then taking the difference between these two numbers

Incorporate your function in a query to count the number of trainers assigned to a


course:

The first few rows of the final query, sorted by course start date

Optionally, save the code to generate your function as Count trainers.sql, then close it
down.

Function to return punk era


20. Create a function using a CASE statement to return the punk era for any given
date, using these dubious statistics:

 Punk is defined to have begun on 1st January 1975


 Punk finished on 31st December 1979
Write a query using your function to test it works:

Things are looking good!

Amend your query so that it shows how many events there were for each era, with the
busiest era first:

Nothing much has happened since the Sex Pistols broke up ...

Save and close all of your queries.

You might also like