Use cursor within stored procedure [duplicate] - mysql

This question already has answers here:
syntax error for mysql declaration of variable
(2 answers)
Closed 4 years ago.
I'm trying to make a stored procedure that include a cursor inside it and fill one of my tables based on another table's data , every day .
I think I'm doing something wrong with syntax , I already wrote a simple Stored procedure with cursor and it worked totally right , but when it get a little more complicated it does not work any more .
I'm getting
Error Code: 1064. You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use
near 'DECLARE brandId int ;' at line 1.
Please note that I'm using Mysql 5.7 and I'm creating this at phpmMyAdmin .
CREATE PROCEDURE ّFillCommentGrowth()
BEGIN
DECLARE brandId int;
DECLARE todayComment int ;
DECLARE brandCount int ;
DECLARE yesterdayComment int;
DECLARE crs CURSOR for SELECT id from brands;
SET brandCount = (SELECT count(*) from brands);
open crs;
WHILE brandCount > 0 DO
FETCH crs into brandId ;
set todayComment = (select IFNULL((select count(*) from comments as c where date(c.created_at) = date(subdate(NOW(),1)) and c.brand_id = brandId ),0));
set yesterdayComment = (select IFNULL((select commentAmount from commentsGrowth where moment = date(subdate(NOW(),2)) and brand_Ref= brandId),0));
INSERT INTO commentsGrowth
(
brand_Ref,
commentAmount,
diffrenceByYesterday,
degree,
AmountPercent,
moment)
VALUES
(brandId ,
todayComment,
(todayComment - yesterdayComment ) ,
(((ATAN(todayComment - yesterdayComment )*180))/PI()),
(degree*(1.1)),
date(subdate(NOW(),1)));
SET brandCount = brandCount - 1;
END WHILE;
close crs;
END

The error you are getting has nothing to do with cursor. You need to change the DELIMITER from standard semicolon (;). For example
DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;
The DELIMITER statement changes the standard delimiter which is semicolon ( ; ) to another. In this case, the delimiter is changed from the semicolon( ; ) to double-slashes //. Why do we have to change the delimiter? Because we want to pass the stored procedure to the server as a whole rather than letting mysql tool interpret each statement at a time. Following the END keyword, we use the delimiter // to indicate the end of the stored procedure. The last command ( DELIMITER; ) changes the delimiter back to the semicolon (;).

Related

Mysterious error in CREATE PROCEDURE in MariaDB/MySQL

I tried to make a simple procedure in MariaDB 10.2 but I encountered an issue regarding variables defining.
I am receiving (conn:107) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 3 message when I declare a variable.
I read the MariaDB documentation and I it says that a variable is defined like this DECLARE var_name [, var_name] ... type [DEFAULT value]
Where I am wrong? I am coming from Oracle SQL and some sintax is wired for me.
I use Eclipse with MariaDB JDBC to connect on SQL.
CREATE PROCEDURE nom_jobs_insert(IN p_name varchar(100) CHARACTER SET 'utf8')
BEGIN
DECLARE counter INT DEFAULT 0;
SELECT count(*) INTO counter
FROM nom_jobs
WHERE lower(name) = lower(p_name)
IF counter = 1 THEN
INSERT INTO nom_jobs(name) VALUES (p_name);
END IF;
END;
I found the solution.
In MariaDB you have to define a delimiter before create a procedure and you need to mark where the procedure code is finished.
DELIMITER //
CREATE PROCEDURE nom_jobs_insert(IN p_name varchar(100) CHARACTER SET 'utf8')
BEGIN
DECLARE counter INT DEFAULT 0;
SELECT count(*) INTO counter
FROM nom_jobs
WHERE lower(name) = lower(p_name);
IF counter = 1 THEN
INSERT INTO nom_jobs(name) VALUES (p_name);
END IF;
END; //
You have error not in DECLARE expression, add ; after SELECT statement
Here are the clues that point to a missing DELIMITER:
near '' at line 3
Line 3 contains the first ;
When the error says near '', the parser thinks it has run off the end of the "statement".
Put those together -- it thinks that there is one 3-line statement ending with ;. But the CREATE PROCEDURE should be longer than that.
CREATE PROCEDURE nom_jobs_insert(IN p_name varchar(100) CHARACTER SET 'utf8')
IS
DECLARE counter INTEGER DEFAULT 0;
BEGIN
SELECT count(*) INTO counter
FROM nom_jobs
WHERE lower(name) = lower(p_name)
IF counter = 1 THEN
INSERT INTO nom_jobs(name) VALUES (p_name);
END IF;
END;

Cannot create Function MySQL syntax errors

I cannot seem to get this working properly, its always a different error I am getting. Any suggestions are appreciated at this point...
CREATE DEFINER=`db`#`localhost` FUNCTION `output_date`(in_date DATE) RETURNS DATE
READS SQL DATA
BEGIN
DECLARE date_format_index INT;
DECLARE date_format_string VARCHAR;
SELECT s.output_date_format INTO date_format_index FROM config s
SET date_format_string = ( CASE date_format_index WHEN 2 THEN '%d-%m-%Y' WHEN 3 THEN '%m-%d-%Y' ELSE '%Y-%m-%d' END );
RETURN in_date
END
I am using DELIMITER $$ when attempting to process this function.
The current error is ...
Error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '; SELECT s.output_date_format INTO date_format_index FROM system_config s SET d'
My environment is MyEclipse, newest version.
The MySQL version I have is 5.2.
You are missing some semi-colons and a problem with varchar, try this:
DELIMITER $$
CREATE DEFINER=`db`#`localhost` FUNCTION `output_date`(in_date DATE) RETURNS DATE
READS SQL DATA
BEGIN
DECLARE date_format_index INT;
DECLARE date_format_string VARCHAR(100); -- obviously change the size
SELECT s.output_date_format INTO date_format_index FROM config s;
SET date_format_string = ( CASE date_format_index WHEN 2 THEN '%d-%m-%Y' WHEN 3 THEN '%m-%d-%Y' ELSE '%Y-%m-%d' END );
RETURN in_date;
END
$$
DELIMITER ;
It runs on my box.

MySQL Stored Procedure error

I have a simple stored procedure which inserts records into four character fields in table. Below is the procedure
CREATE PROCEDURE dowhile()
BEGIN
DECLARE I INT DEFAULT 5
v1loop: WHILE I < 10000 DO
INSERT INTO TestTable1(A,B,C,D)
SELECT CONCAT(I,'A'), CONCAT(I,'B'), CONCAT(I,'C'), CONCAT(I,'D')
SET I = I + 1
END WHILE v1loop
END;
Checked online - there are no free MSSQL to MYSQL SQL Conversion Tools
Error is
- SQL Syntax Error in Insert - SELECT Statement
I have checked the syntax this seem to be correct.
Any pointers for this would be helpful.
Not to bad actually, you just need to add some semi-colons and change MySQL's default delimiter. This needs to be done since we're using SQL inside SQL.
DELIMITER $$
CREATE PROCEDURE dowhile()
BEGIN
DECLARE I INT DEFAULT 5;
v1loop: WHILE I < 10000 DO
INSERT INTO TestTable1(A,B,C,D)
SELECT CONCAT(I,'A'), CONCAT(I,'B'), CONCAT(I,'C'), CONCAT(I,'D');
SET I = I + 1;
END WHILE v1loop;
END$$
DELIMITER ;
Just tested this on my MySQL server.

can't create mysql stored procedure

I'm a bit of a noob when it comes to stored procedures in general, but I'm trying to write the following
Create procedure clone_perms
as
declare #new_id varchar(30), #old_id varchar(30)
declare get_perms cursor for select userspermsUserid, userspermsPermission from users_permissions where userspermsUserid=#old_id
declare #perms varchar(30), #on_off boolean
FETCH get_perms into #perms, #on_off
while(##sqlstatus=0)
BEGIN
if exists ( select 1 from permissions where userspermsUserid=#new_id and userspermsPermID=#perm )
BEGIN
update permissions set userspermsPermission=#on_off where userspermsUserid=#new_id and userspermsPermID=#perm
END
else
BEGIN
insert permissions (userspermsUserID, userspermsPermID, userspermsPermission) values (#new_id, #perms, #on_off)
END
FETCH get_perms into #perms, #on_off
END
CLOSE get_perms
DEALLOCATE CURSOR get_perms
end
. I get the following error when trying to create it:
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as declare #new_id varchar(30) declare #old_id varchar(30) declare get_perm' at line 2 */
. Does anyone know what I need to do to make this work?
You need to have BEGIN tag after CREATE PROCEDURE clone_perms and not AS
don't use an # to start local (declared) variable names, that's only for user variables you create with the
SET #varname=value;
statement. you'll also need to terminate your statements with a semicolon. that's the cause of the latest error, there's no ; after your first declare statement.

SQL syntax error when creating a stored procedure in MySQL

I have a hard time locating an error when trying to create a stored procedure in mysql.
If I run every single line of the procedure independently, everything works just fine.
CREATE PROCEDURE cms_proc_add_child
(
param_parent_id INT, param_name CHAR(255),
param_content_type CHAR(255)
)
BEGIN
SELECT #child_left := rgt FROM cms_tree WHERE id = param_parent_id;
UPDATE cms_tree SET rgt = rgt+2 WHERE rgt >= #child_left;
UPDATE cms_tree SET lft = lft+2 WHERE lft >= #child_left;
INSERT INTO cms_tree (name, lft, rgt, content_type) VALUES
(
param_name,
#child_left,
#child_left+1,
param_content_type
);
END
I get the following (helpful) error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
I just don't know where to start debugging, as every single one of these lines is correct.
Do you have any tips?
As line 3 contains the first ; perhaps you have a problem with your delimiters.
See http://dev.mysql.com/doc/refman/en/stored-programs-defining.html
DELIMITER //
CREATE PROCEDURE dorepeat(p1 INT)
BEGIN
SET #x = 0;
REPEAT SET #x = #x + 1; UNTIL #x > p1 END REPEAT;
END//
DELIMITER ;
Thanks, near '' at line 3 was my problem and the delimiter statement fixed it! I always want things to make sense and this does. As the '' indicates it's at the end of the procedure, but no END statement was found thus the syntax error. And I wondered why I kept seeing a lot of people using the delimiter statement. I see the light!
You never declare your #child_left variable.
If you having issues with a bunch of Procedure that can't run at the same time but can run successfully alone, Try separate them with Go command.
Ex:
--i)
CREATE PROCEDURE A
AS
BEGIN
END;
GO
--ii)
CREATE PROCEDURE B
AS
BEGIN
END;