Sometimes there is need to use conditional expression inside
stored procedure to control the flow of execution.
We can use IF or CASE statements for this.
Below is a stored procedure to check the performance of a student
based on its score.
Store the below stored procedure in a file called
get_performance.sql
DELIMITER $$
DROP PROCEDURE IF EXISTS
get_performance$$
CREATE PROCEDURE get_performance
(score NUMERIC(8, 2),
OUT result VARCHAR(11))
BEGIN
IF (score >= 90) THEN
SET result =
'OUTSTANDING';
ELSEIF (score >= 70 …
DELIMITER $$
-- Change the delimiter
DROP PROCEDURE IF EXISTS demo$$ -- Remove if
previously exists
CREATE PROCEDURE demo() -- Create
Stored Procedure
BEGIN
-- Start of
definition
DECLARE my_int INT;
-- Declare variables
DECLARE my_big_int BIGINT;
DECLARE my_text TEXT;
DECLARE my_name VARCHAR(30) --
Declare variables with
DEFAULT 'Rookie Dev';
-- default value set
SET my_int = 20;
-- Set variables to values …
At Open Query we steer clear of code development for clients. We sometimes advise on code, but as a company we don’t want to be in the programmer role. Naturally we do write scripts and other necessities to do our job.
Assisting with an Open Source project, I encountered three old UDFs. User Defined Functions are native functions that are compiled and then loaded by the server similar to a plugin. As with plugins, compiling can be a pest as it requires some of the server MySQL header files and matching build switches to the server it’s going to be loaded in. Consequentially, binaries cannot be considered safely portable and that means that you don’t really want to have a project rely on UDFs as it can hinder adoption quite severely.
Since MySQL 5.0 we can also use SQL stored functions and procedures. Slower, of course, but …
[Read more]