Stored Procedure
Stored Procedure
A stored procedure is a segment of declarative SQL statements stored inside the database catalog. A
stored procedure can be invoked by triggers, other stored procedures, and applications such as Java,
Python, PHP.
Stored procedures advantages
● Typically, stored procedures help increase the performance of the applications. Once
created, stored procedures are compiled and stored in the database.
● Stored procedures help reduce the traffic between application and database server
● Stored procedures are reusable and transparent to any applications
● Stored procedures are secure.
DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;
The DELIMITER statement changes the standard delimiter which is a semicolon ( ; ) to another. In
this case, the delimiter is changed from the semicolon( ; ) to double-slashes //. We use the CREATE
PROCEDURE statement to create a new stored procedure. We specify the name of the stored
procedure after the CREATE PROCEDURE statement. The section between BEGIN and END is
called the body of the stored procedure. You put the declarative SQL statements in the body to handle
business logic.
Calling stored procedures
In order to execute a stored procedure, you use the following SQL command:
CALL stored_procedure_name();
First, you specify the variable name after the DECLARE keyword. The variable name must follow
the naming rules of MySQL table column names. Second, you specify the data type of the variable
and its size. A variable can have any MySQL data types such as INT, VARCHAR , and DATETIME.
Third, when you declare a variable, its initial value is NULL. You can assign the variable a default
value using the DEFAULTkeyword.
Once you declared a variable, you can start using it. To assign a variable another value, you use the
SET statement, for example:
Besides the SET statement, you can use the SELECT INTO statement to assign the result of a
query, which returns a scalar value, to a variable.
DECLARE total_products INT DEFAULT 0;
SELECT COUNT(*) INTO total_products FROM products;
The MODE could be IN , OUTor INOUT , depending on the purpose of the parameter in the stored
procedure. The param_name is the name of the parameter. Followed the parameter name is its data
type and size. Like a variable, the data type of the parameter can be any valid MySQL data type. Each
parameter is separated by a comma (,) if the stored procedure has more than one parameter.
IF Statement
The MySQL IF statement allows you to execute a set of SQL statements based on a certain condition
or value of an expression. To form an expression in MySQL, you can combine literals, variables,
operators, and even functions. An expression can return TRUE FALSE, or NULL.
IF expression THEN
statements;
END IF;
In case you want to execute statements when the expression does not evaluate to TRUE, you use the
IF-ELSE statement as follows:
IF expression THEN
statements;
ELSE
else-statements;
END IF;
If you want to execute statements conditionally based on multiple expressions, you use the IF-
ELSEIF-ELSE statement as follows:
IF expression THEN
statements;
ELSEIF elseif-expression THEN
elseif-statements;
...
ELSE
else-statements;
END IF;
If the expression evaluates to TRUE , the statements in the IF branch executes; Otherwise, MySQL
will check the elseif-expression and execute the elseif-statements in the ELSEIF branch if the
elseif_expression evaluates to TRUE. The IF statement may have multiple ELSEIF branches to check
multiple expressions. If no expression evaluates to TRUE, the else-statements in the ELSE branch
will execute.
Loop in Stored Procedures
MySQL provides loop statements that allow you to execute a block of SQL code repeatedly based on
a condition. There are three loop statements in MySQL: WHILE, REPEAT and LOOP.
WHILE loop
The syntax of the WHILEstatement is as follows:
WHILE expression DO
statements
END WHILE
The WHILE loop checks the expressionat the beginning of each iteration. If the expressionevaluates
to TRUE, MySQL will execute statementsbetween WHILEand END WHILE until the
expressionevaluates to FALSE. The WHILE loop is called pretest loop because it checks the
expression before the statements execute.
Example to find sum of first N natural numbers using while loop
REPEAT loop
The syntax of the REPEAT loop statement is as follows:
REPEAT
statements;
UNTIL expression
END REPEAT
First, MySQL executes the statements, and then it evaluates the expression. If the expressionevaluates
to FALSE, MySQL executes the statements repeatedly until the expression evaluates to TRUE.
Because the REPEAT loop statement checks the expression after the execution of statements, the
REPEATloop statement is also known as the post-test loop.
Example to List number upto n using UNTIL Loop
DELIMITER $$
DROP PROCEDURE IF EXISTS LIST $$
CREATE PROCEDURE LIST(IN N INT(4))
BEGIN
DECLARE I INT(2) DEFAULT 1;
DECLARE OUTSTR VARCHAR(40) DEFAULT "";
REPEAT
SET OUTSTR=CONCAT(OUTSTR,I,",");
SET I=I+1;
UNTIL I=N
END REPEAT;
SELECT OUTSTR;
END $$
DELIMITER ;
IF (I>N) THEN
LEAVE looplabel;
END IF;
END LOOP;
SELECT outstr;
END $$
DELIMITER ;
MySQL cursor
A cursor allows you to iterate a set of rows returned by a query and process each row accordingly.
MySQL cursor is read-only, non-scrollable and asensitive.
Working with MySQL cursor
First, you have to declare a cursor by using the DECLARE statement:
DECLARE cursor_name CURSOR FOR SELECT_statement;
Next, you open the cursor by using the OPEN statement. The OPEN statement initializes the result
set for the cursor, therefore, you must call the OPEN statement before fetching rows from the result
set.
OPEN cursor_name;
Then, you use the FETCH statement to retrieve the next row pointed by the cursor and move the
cursor to the next row in the result set.
FETCH cursor_name INTO variables list;
Finally, you call the CLOSE statement to deactivate the cursor and release the memory associated
with it as follows:
CLOSE cursor_name;
When working with MySQL cursor, you must also declare a NOT FOUND handler to handle the
situation when the cursor could not find any row. Because each time you call the FETCH statement,
the cursor attempts to read the next row in the result set. When the cursor reaches the end of the
result set, it will not be able to get the data, and a condition is raised. The handler is used to handle
this condition.
To declare a NOT FOUND handler, you use the following syntax:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
The finished is a variable to indicate that the cursor has reached the end of the result set. Notice that
the handler declaration must appear after variable and cursor declaration inside the stored
procedures.
Example
DELIMITER $$
DROP PROCEDURE IF EXISTS CALCTOTAL $$
LOOPLABEL: LOOP
FETCH C1 INTO ID,N,SUB1,SUB2,SUB3;
IF FINISHED=1 THEN
LEAVE LOOPLABEL;
END IF;
SET T=SUB1+SUB2+SUB3;
INSERT INTO TOTALMARK VALUES(ID,T);
END LOOP LOOPLABEL;
END $$
DELIMITER ;
Stored Function
Stored function is a special kind stored program that returns a single value. You use stored functions
to encapsulate common formulas or business rules that are reusable among SQL statements or
stored programs. Different from a stored procedure, you can use a stored function in SQL
statements wherever an expression is used. This helps improve the readability and maintainability
of the procedural code.
First, you specify the name of the stored function after CREATE FUNCTION clause.
Second, you list all parameters of the stored function inside the parentheses. By default, all parameters
are the IN parameters.
Third, you must specify the data type of the return value in the RETURNS statement. It can be any
valid MySQL data types.
Fourth, for the same input parameters, if the stored function returns the same result, it is considered
deterministic; otherwise, the stored function is not deterministic. You have to decide whether a stored
function is deterministic or not.
Fifth, you write the code in the body of the stored function. It can be a single statement or a compound
statement. Inside the body section, you have to specify at least onr RETURN statement to returns a
value to the caller. Whenever the RETURN statement is reached, the stored function’s execution is
terminated immediately.
SQL trigger
A SQL trigger is a set of SQL statements stored in the database catalog. A SQL trigger is executed or
fired whenever an event associated with a table occurs e.g., insert, update or delete. A SQL trigger is
a special type of stored procedure, it is not called directly like a stored procedure. The main difference
between a trigger and a stored procedure is that a trigger is called automatically when a data
modification event is made against a table whereas a stored procedure must be called explicitly.
Advantages of using SQL triggers
● SQL triggers provide an alternative way to check the integrity of data.
● SQL triggers can catch errors in business logic in the database layer.
● By using SQL triggers, you don’t have to wait to run the scheduled tasks because the triggers
are invoked automatically before or after a change is made to the data in the tables.
● SQL triggers are very useful to audit the changes of data in tables.
In MySQL, a trigger is a set of SQL statements that is invoked automatically when a change is made
to the data on the associated table. A trigger can be defined to be invoked either before or after the
data is changed by INSERT, UPDATE or DELETE statement.
you can define a maximum of six triggers for each table.
Following the SIGNAL keyword is a SQLSTATE value. To provide the caller with information, you
use the SET clause. If you want to return multiple condition information item names with values, you
need to separate each name/value pair by a comma. The condition_information_item_name can be
MESSAGE_TEXT, MYSQL_ERRORNO, CURSOR_NAME , etc.
Trigger Examples
STUDENTS
Field Type
SID INT(4)
PRIMARY KEY
SNAME VARCHAR(30)
PROGRAM VARCHAR(30)
SCIENCE INT(3)
MATEMATICSS INT(3)
LANGUAGE INT(3)
AUDIT_STUDENTS
Field Type
ID INT(4) AUTO_INCREMENT
PRIMARY KEY
SID INT(4)
CHANGEDATE DATE
DELIMITER $$
CREATE TRIGGER after_update_students AFTER UPDATE ON students
FOR EACH ROW
BEGIN
if old.program='CT' then
INSERT INTO audit_students(sid,changedate) values(old.sid,now());
end if;
END $$
DELIMITER ;
The term used in the SQL standard for stored procedures is persistent stored modules because these
programs are stored persistently by the DBMS. Stored procedures are useful in the following
circumstances:
If a database program is needed by several applications, it can be stored at the server and invoked by
any of the application programs.
Executing a program at the server can reduce data transfer and communication cost between the client
and server in certain situations.
These procedures can enhance the modeling power provided by views by allowing more complex
types of derived data to be made available to the database users.
The general form of declaring stored procedures is as follows:
In general, each parameter should have a parameter type that is one of the SQL data types. Each
parameter should also have a parameter mode, which is one of IN , OUT , or INOUT . These
correspond to parameters whose values are input only, output (returned) only, or both input and output,
respectively.
The CALL statement in the SQL standard can be used to invoke a stored procedure
CALL <procedure or function name> (<argument list>) ;
Stored function is a special kind stored program that returns a single value. You use stored functions
to encapsulate common formulas or business rules that are reusable among SQL statements or stored
programs. Different from a stored procedure, you can use a stored function in SQL statements
wherever an expression is used. This helps improve the readability and maintainability of the
procedural code.