在存储过程中使用游标

时间:2019-02-12 06:37:21

标签: mysql sql phpmyadmin

我试图制作一个存储过程,在其中包含一个游标,并每天根据另一个表的数据填充其中一个表。

我认为我在语法上做错了事,我已经用游标编写了一个简单的存储过程,并且完全可以正常工作,但是当它变得更加复杂时,它将不再起作用。 我正在

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.

请注意,我正在使用Mysql 5.7,并且正在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 

1 个答案:

答案 0 :(得分:0)

您遇到的错误与游标无关。您需要从标准分号(;)更改DELIMITER。例如

DELIMITER //
 CREATE PROCEDURE GetAllProducts()
   BEGIN
   SELECT *  FROM products;
   END //
 DELIMITER ;

DELIMITER语句将标准分隔符(分号(;))更改为另一个。在这种情况下,定界符从分号(;)更改为双斜杠//。为什么我们必须更改定界符?因为我们想将存储过程作为一个整体传递给服务器,而不是让mysql工具一次解释每个语句。在END关键字之后,我们使用定界符//指示存储过程的结束。最后一个命令(DELIMITER;)将定界符改回分号(;)。