Stored functions
MySQL stored functions provide a powerful and flexible way to manipulate and process data. You can define and run stored functions on any hosting.com server that uses MySQL (or MariaDB, a drop-in replacement for MySQL).Setting up a test database
To demonstrate a basic example of stored functions, let’s start by creating a database that we can use for testing purposes. In the following SQL statement, replace username with your account username:You can run the previous SQL command (and the following SQL commands) from the command line using the MySQL tool, or in your web browser using phpMyAdmin.
Creating the stored function
Now that we have a database and a table to work with, we are ready to create a stored function. Let’s create a function named calcProfit. This function takes two input parameters: the cost and the price of something. It calculates the profit by subtracting the cost from the price, and then returns the value to the calling expression. To create this stored function, run the following MySQL statements:The DELIMITER command at the beginning of these statements prevents MySQL from processing the function definition too soon. The DELIMITER command at the end of these statements returns processing to normal.
Using the stored function
You can now execute the stored function in a database query. The following SQL statement demonstrates how to do this:Stored procedures
Stored procedures are sometimes confused with stored functions, but they are different in some important ways. Stored procedures, for example, must be invoked with the CALL statement, whereas stored functions can be used directly in SQL expressions. You can define and run stored procedures on any hosting.com server that uses MySQL. The following MySQL statements demonstrate how to create a very basic stored procedure named procedureTest. This procedure performs a simple lookup on the products table that we used in the stored function example above. Although this procedure does not have much practical use, it demonstrates the correct syntax and structure for declaring a stored procedure:If you are using phpMyAdmin, type the previous MySQL statement without the \G option at the end.