Can't declare variable in MySQL [duplicate] - mysql

I don't get what is wrong with this script
BEGIN
DECLARE crs INT DEFAULT 0;
WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs)
SET crs = crs + 1;
END WHILE;
END;
I want it to insert 10 values into the table continent but there is an error at the second line.

declare variable in MySQL with # and assign with :=
SET #crs = 0; // declaration
--here your query
#crs := #crs+1 // assignment
References
user defined variables
assignment

MySQL does not support the execution of anonymous blocks of stored procedure code.
You need to create a stored procedure including that code and then invoke it.
Also, you were missing the semi-colon at the end of your insert statements. I fixed that. You also probably want to use concat() instead of + to generate the names, but I'll leave that change to you.
Create the procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS insert_ten_rows $$
CREATE PROCEDURE insert_ten_rows ()
BEGIN
DECLARE crs INT DEFAULT 0;
WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs);
SET crs = crs + 1;
END WHILE;
END $$
DELIMITER ;
Invoke the procedure:
CALL insert_ten_rows();

Related

Is this the right way to set a value to a variable in a mysql trigger?

So I have this variable configId and I set it's value to 1 but the result is different from
DROP TRIGGER IF EXISTS input_verification;
DELIMITER $$
CREATE TRIGGER input_verification
AFTER INSERT ON InputHistory FOR EACH ROW
BEGIN
DECLARE configId integer;
SET #configId := 1;
IF( SELECT count(*)FROM InputHistory JOIN Input on InputHistory.inputId = Input.inputId WHERE InputHistory.inputHistoryOrderNumber=Input.inputOrderNumber AND InputHistory.inputHistoryStatus >= 300)=0 THEN
UPDATE Configuration SET configurationReady = true WHERE configurationId= configId;
END IF;
END $$
DELIMITER ;
this:
DROP TRIGGER IF EXISTS input_verification;
DELIMITER $$
CREATE TRIGGER input_verification
AFTER INSERT ON InputHistory FOR EACH ROW
BEGIN
DECLARE configId integer;
SET #configId := 1;
IF( SELECT count(*)FROM InputHistory JOIN Input on InputHistory.inputId = Input.inputId WHERE InputHistory.inputHistoryOrderNumber=Input.inputOrderNumber AND InputHistory.inputHistoryStatus >= 300)=0 THEN
UPDATE Configuration SET configurationReady = true WHERE configurationId= 1;
END IF;
END $$
DELIMITER ;
Where I put directly the value 1 to the update statement.
Don't put the # sigil on local variables you declared in the body of your trigger.
In MySQL, variables with the # sigil are user-defined variables. You don't need to declare these. But they have scope outside your trigger. If they have a value before your trigger executes, the trigger can read that value. If you change the value of such a variable inside the trigger, the value will be preserved after the trigger is done.
Whereas variables without the # sigil are local variables. You must use DECLARE to create these variables, as you have done above. They are limited to the scope of the body they are declared in, i.e. in this case, the variable is only visible within this trigger.
Don't mix them. Just think of configId and #configId as different variables. In fact, they are different variables. Setting one does not change the value of the other.

REVERSE of a number in mysql

used the following stored procedure to find reverse of a number , but it is showing error:use the right syntax to use near loop.
DELIMITER //
CREATE PROCEDURE ggrepeat1()
begin
declare num1 int;
declare num2 int;
declare rev int default 0;
set #num1:='&num1';
while num1>0
loop
set #num2:=num1 mod 10;
set #rev:=num2+(rev*10);
set #num1:=floor(num1/10);
end loop;
dbms_output.put_line('Reverse number is: '||rev);
end//
DELIMITER ;
As noted in the comments, you can't use oracle syntax in mysql. Regardless, I think you're over-complicating things. A simpler approach would be to cast your number to a string, reverse it using built-in functions and cast it back to a number:
CREATE FUNCTION reverse_int(num INT)
RETURNS INT DETERMINISTIC
RETURN CAST(REVERSE(CAST(num AS CHAT)) AS INT);
The while loop in mysql should be used in this like.
This is the first problem
while n>0 do
content..
end while
The second problem is
dbms_output.put_line('Reverse number is: '||rev);
In mysql you cannot use the above code.
Instead you can use this
Select 'The reverse of number is 'rev;
So your code would be
DELIMITER //
CREATE PROCEDURE ggrepeat1()
begin
declare num1 int;
declare num2 int;
declare rev int default 0;
set #num1:='&num1';
while num1>0 do
set #num2:=num1 mod 10;
set #rev:=num2+(rev*10);
set #num1:=floor(num1/10);
end while;
Select 'Reverse number is: 'rev;
end//
DELIMITER ;

End while loop missing semicolon

I created a simple stored procedure that loops through rows of one table and inserts them into another. For some reason the END WHILE loop is throwing a missing semicolon error. All the code looked right to me, and all the delimiters were set up right. I just can't figure out why it would be throwing these errors, googling this problem only pointed me to improperly used delimiter answers, but nothing more. Any help would be nice!
USE test;
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM `test_dropship_upload` INTO n;
SET i=0;
WHILE i<n DO
INSERT INTO `test_2` (sku, qty) VALUES(sku, qty) FROM `test_dropship_upload` LIMIT i,1;
SET i = i + 1;
END WHILE;
END $$
DELIMITER ;
When I am stuck with a problem in a large block of code and can't find where the problem is, I usually split my code in smaller chunks and test them one at a time:
Test 1:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE testLoop()
BEGIN
END $$
DELIMITER ;
No errors: procedure declaration and use of delimiters is OK.
Test 2:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
END $$
DELIMITER ;
No errors: the declaration of variables within the procedure is OK.
Test 3:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM `test_dropship_upload` INTO n;
SET i=0;
END $$
DELIMITER ;
No errors: the SELECT query and the variable assignment are OK.
Test 4:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM `test_dropship_upload` INTO n;
SET i=0;
WHILE i<n DO
SET i = i + 1;
END WHILE;
END $$
DELIMITER ;
No errors: the WHILE loop is OK.
Test 5:
The only untested part is now the INSERT query:
INSERT INTO `test_2` (sku, qty) VALUES(sku, qty) FROM `test_dropship_upload` LIMIT i,1;
Looking a the documentation for INSERT and INSERT ... SELECT, we can see that your query is not valid: it is apparently missing a SELECT part and shouldn't have a VALUES part if you want to insert values from another table:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM `test_dropship_upload` INTO n;
SET i=0;
WHILE i<n DO
INSERT INTO `test_2` (sku, qty) SELECT sku, qty FROM `test_dropship_upload` LIMIT i, 1;
SET i = i + 1;
END WHILE;
END $$
DELIMITER ;
The procedure creation now completes without errors.
Test 6:
However, you will get a syntax error on the SELECT query when executing the procedure: MySQL doesn't accept using LIMIT with a variable.
To make it work, you need to use a prepared statement.
PREPARE stmt FROM "INSERT INTO `test_2` (sku, qty) SELECT sku, qty FROM `test_dropship_upload` LIMIT ?, 1";
EXECUTE stmt using #i;
DEALLOCATE PREPARE stmt;
It is also not allowed to used local variables in prepared statements:
Because local variables are in scope only during stored program
execution, references to them are not permitted in prepared statements
created within a stored program. Prepared statement scope is the
current session, not the stored program, so the statement could be
executed after the program ends, at which point the variables would no
longer be in scope. For example, SELECT ... INTO local_var cannot be
used as a prepared statement. This restriction also applies to stored
procedure and function parameters.
To circumvent this problem, use a session variable #i instead of your local variable i:
Final version of the procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testLoop`$$
CREATE PROCEDURE `testLoop`()
BEGIN
DECLARE n INT DEFAULT 0;
SELECT COUNT(*) FROM `test_dropship_upload` INTO n;
SET #i=0;
WHILE #i<n DO
PREPARE stmt FROM "INSERT INTO `test_2`(sku, qty) SELECT sku, qty FROM `test_dropship_upload` LIMIT ?, 1";
EXECUTE stmt USING #i;
DEALLOCATE PREPARE stmt;
SET #i = #i + 1;
END WHILE;
END $$
DELIMITER ;
You can apply the same method to debug many complex programming problems: start with a simple version of your code, test it. If it works test again with a more code, if not locate and fix the errors before continuing.

MYSQL declaring variables

I don't get what is wrong with this script
BEGIN
DECLARE crs INT DEFAULT 0;
WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs)
SET crs = crs + 1;
END WHILE;
END;
I want it to insert 10 values into the table continent but there is an error at the second line.
declare variable in MySQL with # and assign with :=
SET #crs = 0; // declaration
--here your query
#crs := #crs+1 // assignment
References
user defined variables
assignment
MySQL does not support the execution of anonymous blocks of stored procedure code.
You need to create a stored procedure including that code and then invoke it.
Also, you were missing the semi-colon at the end of your insert statements. I fixed that. You also probably want to use concat() instead of + to generate the names, but I'll leave that change to you.
Create the procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS insert_ten_rows $$
CREATE PROCEDURE insert_ten_rows ()
BEGIN
DECLARE crs INT DEFAULT 0;
WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs);
SET crs = crs + 1;
END WHILE;
END $$
DELIMITER ;
Invoke the procedure:
CALL insert_ten_rows();

Getting errors when trying to create a PROCEDURE in mysql

I am trying to create a mysql stored procedure, but I get this error:
Script line: 2 Failed to CREATE PROCEDURE proc_test_bideep
The stored procedure code is:
DELIMITER $$
DROP PROCEDURE IF EXISTS `commun`.`insert_categorie` $$
CREATE PROCEDURE `commun`.`insert_categorie` (id_mere INT,
lib_categ VARCHAR(50),
id_categ_sup INT ,
categ_authInstantBuy INT)
BEGIN
SET #bg_mere := (SELECT categ_bg FROM categ_basic WHERE categ_id = id_mere);
#bg_mere+2,categ_level_bideep,categ_statut,categ_adult,categ_authSmallBid,categ_authBid,categ_authInstantBuy);
SELECT '1' AS code_retour; END IF;
ecetera.........
END $$
DELIMITER ;
a) You need to DECLARE any variables on the first lines of the procedure, including their datatype:
DECLARE bg_mere INT;
b) To fetch a value from the database into a variable, you use SELECT ... INTO syntax:
SELECT categ_bg INTO bg_mere FROM categ_basic WHERE categ_basic.categ_id = id_mere;
c) You have an END IF without the corresponding IF.
d) The closing END needs a semicolon (not BEGIN though), only then do you need a delimiter to finish the entire statement, and finally you should reset the delimiter back to normal:
BEGIN
# body of the stored procedure goes here
END;
$$
DELIMITER ;
Your parameters are missing the keyword IN such as: ...(IN id_mere INT, IN lib_categ ...). Also, you need to configure your OUT variable for #bg_mere in the initial parameter list such as (IN xxx, ..., OUT bg_mere VARCHAR/INT/WHATEVER).