To execute a dynamic command within a function
, procedure
or trigger
it is necessary to prepare the string
and then run it.
For example, to create a procedure that sums two numbers and returns the result would look something like this:
DELIMITER $$
DROP PROCEDURE IF EXISTS soma $$
CREATE PROCEDURE soma(in valor1 INT(11), in valor2 INT(11))
BEGIN
PREPARE stmt FROM CONCAT('SELECT ', valor1,' + ', valor2, ' AS resultado');
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER;
To return the result just execute something like:
CALL soma(1, 2);
In this case the return will be:
+---------+
|resultado|
|---------|
| 3|
+---------+
This same function can also be changed so that parameters are passed. The advantage of passing parameters is that you can reuse the same query
at some point within procedure
.
DELIMITER $$
DROP PROCEDURE IF EXISTS soma $$
CREATE PROCEDURE soma(in valor1 INT(11), in valor2 INT(11))
BEGIN
SET @valor1 = valor1, @valor2 = valor2; # É necessário criar essas variáveis antes de utiliza-las no USING
PREPARE stmt FROM 'SELECT ? + ? AS resultado';
EXECUTE stmt USING @valor1, @valor2;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER;
If you pass the same parameters the return will be exactly the same.
You can see more about prepared statments
here .
Explanation of Commands
-
PREPARE nome_da_variavel FROM sql
: At this point query
is being prepared, that is, the variable nome_da_variavel
will receive a statment
with the query
that was passed after FROM
;
-
EXECUTE nome_da_variavel
: EXECUTE
will execute statment
. If you have parameters, after statment
you must use the reserved word USING
and after that, all the parameters separated by commas.
-
DEALLOCATE PREPARE nome_da_variavel
: DEALLOCATE
is used to release the variable, that is, after running it, the statment will no longer exist.