Stored functions are similar to stored procedures: they are named program units that contain one or more MySQL statements. They differ from procedures in the following ways:
Generally, you should consider using a stored function rather than a stored procedure when you have a program whose sole purpose is to compute and return a single value or when you want to create a user-defined function for use within SQL statements.
Figure 2-16 shows a function that implements the same functionality found in the discount_price stored procedure we created earlier in this chapter.
Figure 2-16. A stored function
The following table explains a few things that set apart this function from its stored procedure equivalent:
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 NO SQL or READS SQL DATA clauses) or be declared to be DETERMINISTIC (if it is to be allowed in servers that have binary logging enabled). This restriction is designed to prevent inconsistencies between replicated databases caused by functions that return an unpredictable value (see Chapter 10 for more details). Our example routine is "deterministic" we can guarantee that it will return the same result if it is provided with the same input parameter. |
21 |
Use the RETURN statement to pass back the discount price calculated by the IF statement. |
Example 2-9 shows calling this function from within a SQL statement.
Example 2-9. Calling a stored function from a SELECT statement
mysql> SELECT f_discount_price(300) $$ +-----------------------+ | f_discount_price(300) | +-----------------------+ | 270.0 | +-----------------------+ |
We can also call this function from within another stored program (procedure, function, or trigger), or any place that we could use a built-in MySQL function.
Part I: Stored Programming Fundamentals
Introduction to MySQL Stored Programs
MySQL Stored Programming Tutorial
Language Fundamentals
Blocks, Conditional Statements, and Iterative Programming
Using SQL in Stored Programming
Error Handling
Part II: Stored Program Construction
Creating and Maintaining Stored Programs
Transaction Management
MySQL Built-in Functions
Stored Functions
Triggers
Part III: Using MySQL Stored Programs in Applications
Using MySQL Stored Programs in Applications
Using MySQL Stored Programs with PHP
Using MySQL Stored Programs with Java
Using MySQL Stored Programs with Perl
Using MySQL Stored Programs with Python
Using MySQL Stored Programs with .NET
Part IV: Optimizing Stored Programs
Stored Program Security
Tuning Stored Programs and Their SQL
Basic SQL Tuning
Advanced SQL Tuning
Optimizing Stored Program Code
Best Practices in MySQL Stored Program Development