我不明白为什么我的代码下面会出现语法错误。谁能帮我?

时间:2017-07-21 03:03:33

标签: mysql cursor declare

 DELIMITER ##
 create trigger tra_Price after update on assets_cdn_charge for each row
 begin
 declare res int;
 declare ids int;
 declare idq int;
 declare idt int;
 set res = (select price from assets_cdn_charge where price = new.price);
 set ids = (select id from assets_cdn_charge where price = new.price);
 DECLARE cur CURSOR FOR SELECT id FROM assets_cdn_composite WHERE cdn_charge_id = ids;
 open cur;
 ins_loop:LOOP
 fetch cur into idq;
 declare curs cursor for select id from assets_cdn_traffic where domain_name_id = idq;
 open curs;
 ins1_loop:LOOP
 fetch curs into idt;
 update assets_cdn_traffic set cost = traffic * res where domain_namd_id = idt;
 end LOOP;
 close curs;
 end LOOP;
 close cur;
 END; ##

当我运行此代码时,我收到此错误:

  

错误1064(42000):您的SQL语法有错误;检查   手册,对应右边的MySQL服务器版本   在'DECLARE cur CURSOR FOR SELECT id FROM附近使用的语法   assets_cdn_composite WHERE cdn_charge_id ='第9行

1 个答案:

答案 0 :(得分:0)

可能是因为:

  

仅允许在BEGIN ... END复合语句中使用DECLARE   并且必须在其他任何陈述之前开始

...因此该行应该可以在该点之上的两个set语句之前移动。

我相信如果修复了这个错误,您将会遇到其他问题,因为我不知道您希望在该点之前宣布要检索的查询为idq,但是未设置为任何值?

=====

更新:

以下是关于完全消除游标的可能性的先前评论的示例。试试这个:

BEGIN
    UPDATE assets_cdn_traffic
        JOIN assets_cdn_composite ON assets_cdn_traffic.domain_name_id = assets_cdn_composite.cdn_charge_id
        JOIN assets_cdn_charge ON assets_cdn_charge.id = assets_cdn_composite.cdn_charge_id
    SET cost = traffic * NEW.price
    WHERE assets_cdn_charge.id = NEW.id
END

但是,我会在使用触发器之前单独尝试更新查询,以确保它按预期工作。将NEW.priceNEW.id替换为测试值以验证处理。