Stored Procedures and Functions
Move reusable logic into the database, and know exactly when that pays off.
Big idea: A stored routine is a named block of SQL saved inside the database and executed on demand. A procedure is invoked with
CALL and performs actions (it can return result sets and out-parameters); a function returns a single value and can be used inside an expression such as a SELECT list or a WHERE clause. Both let you package parameters, local variables and control flow (IF, CASE, loops) next to the data they touch.
By the end of this topic you will be able to:
- write
CREATE PROCEDUREandCREATE FUNCTIONand handle the MySQLDELIMITERgotcha, - use
IN,OUTandINOUTparameters correctly, - declare local variables and assign them with
SETandSELECT ... INTO, - drive logic with
IF,CASEand theWHILE/REPEAT/LOOPconstructs, - choose between a procedure and a function, and judge when server-side logic helps and when it hurts.