CPSC-110 Spring 2009
Lab 7
Thursday, March 26, 2009
Professor Heidi Ellis

Be sure that the professor or TA checks off your work before leaving!!!

Objectives:

In this lab we will write and execute a simple stored procedure in MySQL.

Stored Procedures

SQL is a nonprocedural programming language. This means that you write what you want the code to do using SQL, but you don't explicitly tell the system how to carry out the code. In other words, you don't explicitly tell MySQL how to process the rows in a table when executing a query. We now will learn about using stored procedures which are a way to provide more guidance to MySQL when processing information.

Stored procedures use a procedural language. A procedural program is a list of step-by-step instructions that tell the computer what to do. Think of a currency converter such as XE that supports the conversion of different currencies. The steps in the program consist of:
  1. Prompt the user to enter the amount to convert.
  2. Prompt the user to enter the "from" currency and the "to" currency.
  3. Read the amount and currencies into the program.
  4. Convert the amount of the "from" currency into the "to" currency using a formula similar to: tocurrency = fromcurrency * conversionfactor.
  5. Display the resulting conversion.
Clearly, in order to perform the conversion, the program must first read in the amount and currencies before calculating the conversion. Similarly, the conversion calculation must occur before displaying the results. Therefore, the steps above must be performed in sequential order.

Why do we need stored procedures?

Stored procedures are used for many reasons including:

Creating and Using a Stored Procedure

Creating and using stored procedures have two parts:
  1. Creating the stored procedure: In this first step, the actual code for the procedure is defined. In other words, you will write the statements to be executed in order to carry out the procedure. The process of creating and editing a stored procedure happens once. Once a procedure has been correctly defined, it typically does not need to be modified afterwards.
  2. Running or executing the stored procedure: Once a procedure has been created, it may be run or executed any number of times.

What Does a Stored Procedure Look Like?

At their simplest, stored procedures contain a single SQL statement after a CREATE PROCEDURE statement:
CREATE PROCEDURE SayHello() 
select "Hello World";
The procedure above is named SayHello and simply displays Hello World to the screen. However, in order to properly differentiate between regular SQL code and stored procedure code, MySQL must change the delimiter (that special character that tells MySQL that the end of a line has been reached). MySQL must also indicate that if the procedure already exists, we want to drop that procedure before creating it anew. The full syntax is shown below. Note that the lines beginning with double dashes (--) are comments and are not executed (i.e., they are ignored by the SQL processor).
DELIMITER $$                                 -- Change the delimiter so that we can 
                                             -- use semicolons within our procedure code.
DROP PROCEDURE IF EXISTS `police`.`temp` $$  -- If the procedure exists already, remove it. 
CREATE PROCEDURE `police`.`SayHello` ()      -- Creates the procedure
BEGIN                                        -- Begin execution here
   select "Hello World";                     -- Executable part of the procedure.
END $$                                       -- End execution here
DELIMITER ;
Pair Programming:
  1. Locate your partner and introduce yourself:
  2. Abby AldermanRichard Curtin 
    Cory DiBenedettoElise Galbo 
    Briggs ElwellBrooke Haynes 
    Nikki LustigBrenna Fox 
    Ryan PiacentiniShanice Smith 
    Matt VibertAlyssa Cockrell 
    Robert PerrymanPreston MaddockAndrea Titone
    Ben McDanielWhitney Merrill 
  3. Select one person's account in which to work.
  4. Select one person to start as "driver". Change driver for each new procedure created.
  5. Using KWrite (or another text editor), create a new file called lab7.txt. Put both team members' names in the document.
  6. Copy the procedure code for each procedure created into the lab7.txt file.
  7. Email the completed file to the partner in whose account you were not working so that they have a copy.
  8. Print the lab7.txt file and hand it in at the end of lab.

First Stored Procedure

For this lab you will use your police database. Make sure that your police database has at least 10 rows of data in the incident and vehicle tables. See Step 3 of Lab 5 for details. The first stored procedure we will write will be called temp and will simply print out your name.

Step 1: Creating a Stored Procedure

  1. Open the MySQL query browser.
  2. Select script/Create Stored Procedure/Function menu options. A window should pop up that looks similar to the following:


  3. Enter the name of the procedure that you would like to create in the text box (temp) and press the Create Procedure button.
  4. This will open a script window in the main query window. The script window different from the query window we have used up to this point and is identifiable because it has an icon with text lines. The query window has a lightening bolt. You MUST enter your code using a script window, not a query window:



  5. Correct entry of a procedure name results in a template being shown:
    DELIMITER $$
    
    DROP PROCEDURE IF EXISTS `police`.`temp` $$
    CREATE PROCEDURE `police`.`temp` ()
    BEGIN
    
    END $$
    
    DELIMITER ;
    
    Remember that the DELIMITER statements are required and that the DROP PROCEDURE statement deletes any previous versions of the procedure.
  6. On the blank line between the BEGIN and END statements write: select "Your name"; replacing "Your name" with your name.
  7. Press the Execute button or select the script/execute menu to check the stored procedure code for any errors. If no errors occur you should see the words "Query Executed" in the lower left corner of the Query Browser screen. This means that you are ready to call your stored procedure.
  8. When you have successfully created a new stored procedure, you will see the name of the stored procedure listed within the definition of the database on which the procedure is defined. Stored procedures are identified by a blue box containing gears (as opposed to the blue tables used to designate relations). Below is a picture of the police database showing several procedures:


Step 2: Running a Stored Procedure

  1. To run the stored procedure, open a new query window and use the call key word followed by the name of the procedure. Make sure that there are no blank spaces between the end of the procedure name and the open and close paretheses. Note that the open and close parentheses are required. The presence of the parentheses tells MySQL that you are calling a procedure. A call to the temp procedure looks like:


  2. Don't forget that the creation of the stored procedure must occur in a script window (not a query window) while the execution of the query must occur in a query window.
  3. Don't forget to include the open and closed parens at the end of the call.
  4. If you would like to edit a stored procedure, right click over the procedure name and select Edit in the query browser.

!!Swap Drivers!!

Second Stored Procedure

Stored procedures can execute regular SQL code. Lets write a stored procedure called under35 to retrieve the names of people involved in traffic incidents whose age is less than 35. Remember that the SQL query to perform this is:
select name 
from incident 
where age < 35;
The definition of the stored procedure under35 is shown below.
DELIMITER $$

DROP PROCEDURE IF EXISTS `police`.`under35` $$
CREATE PROCEDURE `under35`()
BEGIN
    select name 
    from incident 
    where age < 35;
END $$

DELIMITER ;
Now execute the query by opening a query tab and typing: call under35(). Double check your answer by executing the SQL statement in a query tab and comparing the results. Note that on the Linux system you are limited to having a single SQL statment within any one stored procedure.

!!Swap Drivers!!

Third Stored Procedure

Now lets do something more interesting. For our third procedure, lets find the average fine paid. Define a stored procedure averageFine that contains the SQL statement:
  select avg(fine)
  from incident;
Next execute the averageFine procedure.

!!Swap Drivers for each procedure!!

Try it on your own

Now write stored procedures for as many of the items below as you have time for. Some of the procedures use both the incident and vehicle tables so make sure that you have sufficient data in both tables. Use the opposite team member's account. Copy the procedures into a your lab7.txt file and hand in at the end of class.
  1. Create a procedure called retrieveSmith that returns all of the names of people in the incident table who have "Smith" in their names.
  2. Create a procedure called infraction3 that returns the names and ages of everyone in the incident table with infraction ID 3.
  3. Create a procedure called totalFines that returns the sum of all fines in the incident table.
  4. Create a procedure called likelyCars that returns the make and model of the cars that have been involved in an incident with a fine greater than or equal to $300.
  5. Create a procedure called likelyDrivers that retrieves the names and ages of people who drive a car younger than 2006.
  6. Create a procedure called cleanOwners that retrieves the owners of vehicles that have not been involved in a traffic incident. Hint: You'll need to use a sub-query.

You're done!! Be sure to have the professor or TA check off your work before you leave!!