16.0. IntroductionThis chapter discusses the following kinds of database objects:
Stored routines and triggers are supported as of MySQL 5.0. Event support begins with MySQL 5.1. These different kinds of objects have in common the property that they are user-defined but stored on the server side for later execution. This differs from sending an SQL statement from the client to the server for immediate execution. Each of these objects also has the property that it is defined in terms of other SQL statements to be executed when the object is invoked. The object has a body that is a single SQL statement, but that statement can use compound-statement syntax (a BEGIN ... END block) that contains multiple statements. This means that the body can range from very simple to extremely complex. The following stored procedure is a trivial routine that does nothing but set a user-defined variable and for which the body consists of a single SET statement: CREATE PROCEDURE get_time() SET @current_time = CURTIME(); For more complex operations, a compound statement is necessary: CREATE PROCEDURE part_of_day() BEGIN CALL get_time(); IF @current_time < '12:00:00' THEN SET @day_part = 'morning'; ELSEIF @current_time = '12:00:00' THEN SET @day_part = 'noon'; ELSE SET @day_part = 'afternoon or night'; END IF; END; Here, the BEGIN ... END block contains multiple statements, but is itself considered to constitute a single statement. Compound statements enable you to declare local variables and to use conditional logic and looping constructs. Note also that one stored procedure can invoke another: part_of_day( ) calls get_time( ). These capabilities provide you with considerably more flexibility for algorithmic expression than you have when you write inline expressions in noncompound statements such as SELECT or UPDATE. The statements within a compound statement must each be terminated by a ; character. That requirement causes a problem if you use the mysql client to define an object that uses compound statements because mysql itself interprets ; to determine statement boundaries. The solution to this problem is to redefine mysql's statement delimiter while you're defining a compound-statement object. Section 16.1 covers how to do this; make sure that you read that recipe before proceeding to those that follow it. Due to space limitations, this chapter illustrates by example but does not otherwise go into much detail about the extensive syntax for stored routines, triggers, and events. For complete syntax descriptions, see the MySQL Reference Manual. The scripts for the examples shown in this chapter can be found in the routines, triggers, and events directories of the recipes distribution. Scripts to create some of the tables are in the tables directory. In addition to the stored routines shown in this chapter, others can be found elsewhere in this book. See, for example, Recipes Section 5.7, Section 6.2, and Section 11.11.
|