Stored Procedure Programming for MySQL5 - Part 1
|
|
|
Click to rate: |
|
|
|
216 votes / avg. rating 36.33%
|
|
A Better ExampleThis is a slightly more advanced example then last one. This stored procedure will take take in and pass out a variable and do some simple logic amongst other things. Nothing to hard - but something that will hopefully expand your mind a bit to the possibilities and power of stored procedures.
mysql> DROP PROCEDURE statusOfDay;
Query OK, 0 rows affected, 3 warnings (0.00 sec)
mysql> DELIMITER //
mysql> CREATE PROCEDURE statusOfDay
(IN inVar VARCHAR(10), OUT outVar VARCHAR(30))
-> BEGIN
-> IF(inVar = "Woohoo") THEN
-> SET outVar = "Today is a good day.";
-> ELSE
-> SET outVar = "Nothing to chear about today.";
-> END IF;
-> END //
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
This example has a number of things that were not in the last example, so lets again break it down to see what each part does.
mysql> DROP PROCEDURE statusOfDay;
I personally like to drop the procedure with the same name as the procedure I am about to create. Saves me from any name clashes when I create the new procedure. Granted I have to be very careful not to accidentally drop a procedure created earlier (by me or someone else) with the same name that may or may not do something completely different then the stored procedure I am currently making... but I should have checked that BEFORE I got ready to write (never mind run) the SQL to create a new stored procedure.
mysql> DELIMITER //
...
mysql> DELIMITER ;
The DELIMITER command is a mysql client command that allows the user to change the statement delimiter. Since a stored procedure can be (and in this case is) a series of mysql SQL commands - when we are creating one we have to be able to place multiple SQL statements in the mysql client without it “running”. By using DELIMITER we can change the statement delimiter to something other then the “;”. A very quick example that changes the delimiter from a semi-colon to a double slash and back to a semi-colon.
mysql> delimiter //
mysql>SELECT COUNT(*) FROM t//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
 |
|
 |
|
Tags:
mysql, procedure, d, storedprocedure, programming, ghdf
Tags Help
Tags are keywords associated with a web page that help classifying information. You can find a good explanation here.
To add one or more tags to this page, simply enter them below (separate them with a comma) and hit enter or click on the "Go" button.
|
|
 |
|
 |
|