I am trying to create and set a variable:
DECLARE myId INT;
SET myId = 5;
However, I am getting invalid syntax complaint in MySQL Workbench:
SQL syntax error near 'DECLARE myId INT;'
I have tried the following variants:
DECLARE myId INT(4);
SET myId = 5;
DECLARE @myId INT;
SET @myId = 5;
DECLARE @myId INT(4);
SET @myId = 5;
What is wrong?
Declare syntax error in MySQL Workbench? The DECLARE syntax must between BEGIN and END. The syntax is as follows − BEGIN DECLARE yourVariableName1 dataType, DECLARE yourVariableName2 dataType, . . . . END Call the stored procedure with the help of CALL command. The syntax is as follows −
How to Declare Variables in MySQL 1 Declare a User-defined Variable In MySQL, we can use the SET statement to declare a variable and also for initialization. ... 2 Local Variable Declaration We define local variables in a program like stored procedures. MySQL provides the DECLARE statement to specify such a variable. ... 3 Declare System Variables
You can refine the list of status and system variables by typing the variable name into to the text box provided or by selecting a category, such as InnoDB/General . Beginning with MySQL Workbench 8.0.11, you can set one or more global system variables to persist across server restarts.
We define local variables in a program like stored procedures. MySQL provides the DECLARE statement to specify such a variable. Also, we can combine it with the DEFAULT clause to assign some initial value. Otherwise, a local variable is .
As in the comment says Declare is only valid into stored programs like procedures, functions. here you have an example of a store procedure and its call.
DELIMITER $$
CREATE PROCEDURE sp1 (x VARCHAR(5))
BEGIN
DECLARE xname VARCHAR(5) DEFAULT 'bob';
DECLARE myId INT;
SET myId = 5;
SELECT CONCAT(xname,' -- ',myId);
END;
$$
DELIMITER ;
call sp1('MY NAME');
I experienced the same problem. The variables must be declared at the beginning of the script.
DELIMITER &&
DROP PROCEDURE IF EXISTS PS_HANDLERS;
CREATE PROCEDURE PS_HANDLERS(IN ID_USER INT, OUT isError INT)
BEGIN
DECLARE USER_EMAIL VARCHAR(50);
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
SET IsError = 1;
END;
SET USER_EMAIL = CONCAT(RAND(),'@',RAND(),'.com');
SET isError = 0;
INSERT INTO tbl_user VALUES(ID_USER, 'ipsum','lorem','[email protected]','password','ROLE_USER');
SELECT
u.*
FROM
tbl_user u;
END &&
DELIMITER ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With