To execute a dynamic command within a function
, procedure
or in trigger
it is necessary to prepare the string
and then execute her.
For example, to create a precedent 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 run 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 it query
at some point within the 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 passed 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 the query
is being prepared, that is to say the variable nome_da_variavel
will receive a statment
with the query
which was passed after the FROM
;
EXECUTE nome_da_variavel
: The EXECUTE
will execute the statment
. If you have parameters, after the statment
the word reserved should be used USING
and after it, all parameters separated by comma.
DEALLOCATE PREPARE nome_da_variavel
: The DEALLOCATE
is used to release the variable, that is, after its execution, the statment will no longer exist.
That’s inside my trial, right?
– Leandro Kojima
Exactly, within the proc. I’ll change the answer to play the whole code!!
– rLinhares
It is that you are giving a syntax error: Unexpected 'command' (Identifier)
– Leandro Kojima
ah, I need to put after the $$end, which incidentally, I forgot to put in the code
– Leandro Kojima
Hmmm, blz.. tb didn’t notice =p
– rLinhares
returned nothing, even setting a simple select in the variable
– Leandro Kojima
Okay, I’ll change the
concat
why are you using.
instead of,
and on set I’ll use the:=
. If that doesn’t work, I don’t think I’ll be able to help you =p– rLinhares
Let’s go continue this discussion in chat.
– Leandro Kojima