Show navigation

Week 11 - Procedures

This week we'll look at procedures in MySQL and how to store them.

When a procedure (or function) has no parameters, you can use it without parentheses after the name. Or have an empty set of parentheses, like this: CALL boyThatsEasy(); - that's okay, too!

Exercises

Alright, this week, we're going to create functions and stored procedures in our own databases!

Functions

  1. Take an integer as an input parameter, multiply it by itself, and then multiply that by the value of π (note: you can easily get the value of π with the built-in function PI()). This function can calculate the area of a circle based on the radius!
  2. Take two strings as your input parameters. Concatenate them, starting with the longer of the two strings. (Remember - there is a built-in function for checking the length of strings.)
  3. Set a due date - books are due three weeks from the withdrawal date, unless that date is a Tuesday. The library has shortened hours on Tuesdays, so books withdrawn on a Tuesday are due in three weeks plus one day. Have your function return the due date based on the withdrawal date.
  4. Let's cleanse some data! Take a string as an input parameter. If the string begins with 'ca' (regardless of the casing), and the string is not Cabo Verde, Cambodia, or Cameroon, return 'CAN'. Otherwise, return the value of the input parameter.
  5. Take three integers as your input parameters. Return the sum of those numbers. If arguments passed in for the first or second parameters are null, set the value of the null argument to zero. If the value of the third argument is null, throw an error.

Procedures

  1. Create a procedure that accepts four input parameters: two strings, a date, and a number. Have your procedure perform a select statement that selects values from your input parameters in the following format:
    "{date}'s episode of Sesame Street has been brought to you by the letters {first letter of string1, uppercased} and {first letter of string2, uppercased}, and the number {number}."
  2. Create a procedure that, when called, will insert values into three of your database's tables: two tables with a many-to-many relationship, and the bridging table that manages that relationship. See the example I used of books & authors on how to do this while maintaining data integrity.
  3. Create a procedure that, when called, will set a session variable to the current time. Additionally, write a SELECT statement using that session variable that will subtract the session variable from the current time.
What is a stored procedure?The syntax for creating a stored procedureHow to use procedures with CALLParameters for procedures: IN, OUT, & INOUT variablesInput ParametersOutput ParametersSession variablesINOUT ParametersExercises