By Guy Harrison, Steven Feuerstein
Book Price: $44.99 USD
£31.99 GBP
PDF Price: $35.99
Cover | Table of Contents | Colophon
INSERT, UPDATE, DELETE) against a database table. Triggers can be used for data validation or for the automation of denormalization.UPDATE, INSERT, DELETE, and SELECT statements directly into your code, as shown in Example 1-1.
1 CREATE PROCEDURE example1( )
2 BEGIN
3 DECLARE
l_book_count INTEGER;
4
5 SELECT COUNT(*)
6 INTO l_book_count
7 FROM books
8 WHERE author LIKE '%HARRISON,GUY%';
9
10 SELECT CONCAT('Guy has written (or co-written) ',
11 l_book_count ,
12 ' books.');
13
14 -- Oh, and I changed my name, so...
15 UPDATE books
16 SET author = REPLACE (author, 'GUY', 'GUILLERMO')
17 WHERE author LIKE '%HARRISON,GUY%';
18
19 END
|
Line(s)
|
Explanation
|
|---|---|
|
1
|
This section, the header of the program, defines the name (
example1) and type (PROCEDURE) of our stored program. |
|
2
|
This BEGIN keyword indicates the beginning of the |
http://www.onlamp.com/onlamp/general/mysql.csp) for more complete information.http://dev.mysql.com.http://dev.mysql.com.
[gharriso@guyh-rh4-vm2 ~]$mysql -uroot -psecret -hlocalhost
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 5.0.16-nightly-20051017-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
CREATE PROCEDURE
, CREATE FUNCTION
, or CREATE TRIGGER
statement. It is possible to enter these statements directly at the MySQL command line, but this is not practical for stored programs of more than trivial length, so the best thing for us to do is to create a text file containing our stored program text. Then we can submit this file to the database using the command-line client or another tool.http://dev.mysql.com/downloads/. Alternately, you could use an OS text editor such as vi, emacs, or Notepad. We like the MySQL Query Browser because of its built-in help system, syntax highlighting, ability to run SQL statements, and lots of other features.DECLARE
statement. Variable names follow the same naming rules as MySQL table column names and can be of any MySQL data type. You can give variables an initial value with the DEFAULT clause and assign them new values using the SET command, as shown in Figure 2-5.
input_number, and calculates the square root of that number. The resulting number is returned as a result set.IN (read-only), INOUT (read-write), and OUT (write-only). No parameter mode appears in Figure 2-6, because IN is the default and this is an IN parameter.DECLARE
l_sqrt.
SET
SQRT function) to the floating-point number we created with the IF or CASE statements. Both have roughly the same functionality; we will demonstrate the use of IF in this tutorial, as it's probably the most familiar of the two constructs.
mysql> SOURCEdiscounted_price.sql Query OK, 0 rows affected (0.01 sec) Query OK, 0 rows affected (0.00 sec) mysql> CALLdiscounted_price(300,@new_price) $$ Query OK, 0 rows affected (0.00 sec) mysql> SELECT@new_price$$ +------------+ | @new_price | +------------+ | 270.0 | +------------+ 1 row in set (0.00 sec)
IF statement allows you to test the truth of an expression such as normal_price > 500 and take appropriate action based on the result of the expression. As with other programming languages, the ELSEIF clause is used for all conditional branches after the initial IF. The ELSE clause is executed if the Boolean expressions in the IF and ELSEIF clauses all evaluate to false.CASE has very similar functionality, and may be preferable when you are comparing a single expression against a set of possible distinct values. The two conditional statements are explored and contrasted in Chapter 4.LOOP and END LOOP clausesWHILE and END WHILE clausesREPEAT and UNTIL clausesLEAVE statement.LOOP-LEAVE-END LOOP (simple loop) sequence in this tutorial.
|
Line(s)
|
Explanation
|
|---|---|
|
7
|
Declare a simple numeric variable called
counter with an initial value of 0. |
|
9-14
|
The simple loop. All statements between
LOOP and END LOOP are repeated until a LEAVE clause is executed. |
|
9
|
The
LOOP statement is prefixed by the my_simple_loop: label. The LEAVE statement requires that the loop be labeled so it knows which loop to exit. |
SELECT statement using a cursor, a NOT FOUND error handler will prevent the stored program from terminating prematurely.NOT FOUND error handler with a cursor is shown in the next section.INSERT, UPDATE, DELETE, etc.SELECT INTO syntax when you are querying information from a single row of data (whether retrieved from a single row, an aggregate of many rows, or a join of multiple tables). In this case, you include an INTO clause "inside" the SELECT statement that tells MySQL where to put the data retrieved by the query.
CALL
statement, just as you would from the MySQL command-line client.l_bonus_amount is populated from an OUT parameter) is passed to a third procedure.|
Line(s)
|
Explanation
|
|---|---|
|
11
|
Determine if the employee is a manager. If he is a manager, we call the
calc_manager_bonus stored procedure; if he is not a manager, we call the calc_minion_bonus stored procedure. |
|
12 and 14
|
With both stored procedures, pass in the
employee_id and provide a variable—l_bonus_amount—to receive the output of the stored procedure. |
|
16
|
Call the
grant_bonus stored procedure that passes as arguments the employee_id and the bonus amount, as calculated by the stored procedure we called in line 12 or 14. |
1 CREATE PROCEDURE putting_it_all_together(in_department_id INT) 2 MODIFIES SQL DATA 3 BEGIN 4 DECLARE l_employee_id INT; 5 DECLARE l_salary NUMERIC(8,2); 6 DECLARE l_department_id INT; 7 DECLARE l_new_salary NUMERIC(8,2); 8 DECLARE done INT DEFAULT 0; 9 10 DECLARE cur1 CURSOR FOR 11 SELECT employee_id, salary, department_id 12 FROM employees 13 WHERE department_id=in_department_id; 14 15 16 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1; 17 18 CREATE TEMPORARY TABLE IF NOT EXISTS emp_raises 19 (employee_id INT, department_id INT, new_salary NUMERIC(8,2)); 20 21 OPEN cur1; 22 emp_loop: LOOP 23 24 FETCH cur1 INTO l_employee_id, l_salary, l_department_id; 25 26 IF done=1 THEN /* No more rows*/ 27 LEAVE emp_loop; 28 END IF; 29 30 CALL new_salary(l_employee_id,l_new_salary); /*get new salary*/ 31 32 IF (l_new_salary<>l_salary) THEN /*Salary changed*/ 33 34 UPDATE employees 35 SET salary=l_new_salary 36 WHERE employee_id=l_employee_id; 37 /* Keep track of changed salaries*/ 38 INSERT INTO emp_raises (employee_id,department_id,new_salary) 39 VALUES (l_employee_id,l_department_id,l_new_salary); 40 END IF; 41 42 END LOOP emp_loop; 43 CLOSE cur1; 44 /* Print out the changed salaries*/ 45 SELECT employee_id,department_id,new_salary from emp_raises 46 ORDER BY employee_id; 47 END;
|
Line(s)
|
|---|
IN parameters. OUT and INOUT parameters are not allowed. Specifying the IN keyword is neither required nor allowed.discount_price stored procedure we created earlier in this chapter.
|
Line
|
Explanation
|
|---|---|
|
7
|
Specify a
RETURNS clause as part of the function definition. This specifies the type of data that the function will return. |
|
8
|
MySQL applies stricter rules to stored functions than it does to procedures. A function must either be declared not to modify SQL (using the |
INSERT, UPDATE, or DELETE (DML) statement. Triggers implement functionality that must take place whenever a certain change occurs to the table. Because triggers
are attached directly to the table, application code cannot bypass database triggers.INSERT statement completes against the sales table. It automatically applies free shipping and discounts to orders of a specified value.
|
Line(s)
|
Explanation
|
|---|---|
|
5
|
Specify the trigger name.
|
|
6
|
Specify that the trigger fires before an insert on the
sales table. |
|
7
|
Include the (currently) mandatory
FOR EACH ROW clause, indicating that the statements within the trigger will be executed once for every row inserted into the sales table. |
|
8
|
Use BEGIN to start the block containing statements to be executed by the trigger. |
mysqli (MySQL "improved") extension, and the more recent PHP Data Objects (PDO)
extension. In this example we will use the mysqli extension. Chapter 13 describes the details of these extensions.
employee_list to retrieve a list of employees that belong to that department. Figure 2-20 shows the output displayed by the PHP/stored procedure example.IF statement.
IF and CASE), and looping capabilities of the language.SELECT statements.DECLARE
statement allows us to create a variable. As we will see a bit later on, it appears within a block of code before any cursor or handler declarations and before any procedural statements. The syntax of the DECLARE statement is:
DECLARE variable_name [,variable_name...] datatype [DEFAULT value];
DECLARE statement, and the variable(s) can be assigned a default (or initial) value. If you don't use the DEFAULT clause, then the variable starts off with the NULL
value.DEFAULT is a good practice because, unless you initialize a variable, any subsequent operations on that variable—other than a simple assignment—may also return NULL. We'll give an example of this type of error later in the chapter.CREATE TABLE statement. We provide detailed descriptions of each data type later in this chapter; Table 3-1 summarizes those most commonly used.++,—,+=, etc.) are not supported.SET statement to change the value of a variable, within comparison statements such as IF or CASE, and in loop control expressions. Example 3-10 shows a few simple examples of using operators within stored programs.
create procedure operators( )
begin
DECLARE a int default 2;
declare b int default 3;
declare c FLOAT;
set c=a+b; select 'a+b=',c;
SET c=a/b; select 'a/b=',c;
SET c=a*b; Select 'a*b=',c;
IF (a<b) THEN
select 'a is less than b';
END IF;
IF NOT (a=b) THEN
SELECT 'a is not equal to b';
END IF;
end;
+), subtraction (-), multiplication (*), and division (/).DIV operator returns only the integer portion of division, while the modulus operator (%) returns only the remainder from a division. Table 3-2 lists, describes, and provides an example of the MySQL mathematical operators.