11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

www.it-ebooks.infoCHAPTER 32 • STORED ROUTINESHow <strong>MySQL</strong> Implements Stored RoutinesAlthough the term stored routines is commonly bandied about, <strong>MySQL</strong> actually implements twoprocedural variants that are collectively referred to as stored routines:• Stored procedures: Stored procedures support execution of SQL commands suchas SELECT, INSERT, UPDATE, and DELETE. They also can set parameters that can bereferenced later from outside of the procedure.• Stored functions: Stored functions support execution only of the SELECTcommand, accept only input parameters, and must return one and only onevalue. Furthermore, you can embed a stored function directly into a SQLcommand just like you might do with standard <strong>MySQL</strong> functions such as count()and date_format().Generally speaking, you use stored procedures when you need to work with data found in thedatabase, perhaps to retrieve rows or insert, update, and delete values, whereas you use stored functionsto manipulate that data or perform special calculations. In fact, the syntax presented throughout thischapter is practically identical for both variations, except that when working with stored procedures thesyntax will use the term procedure instead of function. For example, the command DROP PROCEDUREprocedure_name is used to delete an existing stored procedure, while DROP FUNCTION function_name isused to delete an existing stored function.Creating a Stored RoutineThe following syntax is available for creating a stored procedureCREATE[DEFINER = { user | CURRENT_USER }PROCEDURE procedure_name ([parameter[, ...]])[characteristics, ...] routine_bodywhereas the following is used to create a stored functionCREATE[DEFINER = { user | CURRENT_USER }FUNCTION function_name ([parameter[, ...]])RETURNS type[characteristics, ...] routine_bodyFor example, the following creates a simple stored procedure that returns a static string:mysql>CREATE PROCEDURE get_inventory()->SELECT 45 AS inventory;That’s it. Now execute the procedure using the following command:mysql>CALL get_inventory();Executing this procedure returns the following output:629

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!