【问题标题】:ERROR 1064 (42000): You have an error in your SQL syntax; check the manual mysql stored procedure errorERROR 1064 (42000):您的 SQL 语法有错误;检查手动mysql存储过程错误
【发布时间】:2020-08-01 13:02:37
【问题描述】:

我只是在尝试 mysql 存储过程,但出现以下错误:

ERROR 1064 (42000):您的 SQL 语法有错误;检查 与您的 MySQL 服务器版本相对应的手册 '; 附近使用的语法

DECLARE cur CURSOR for 从员工中选择出生日期;

' 在第 3 行

代码:

delimiter //
create procedure getminmaxbirthdate(OUT minage date,OUT maxage date)
    begin
        DECLARE minsofar,maxsofar,curage,done;

        DECLARE cur CURSOR for
            select birth_date from employees;

        set minsofar = 2040-12-12;
        set maxsofar = 0;
        set done = 0;

        DECLARE continue handler for not found
            set done = 1;

        open cur;
            while done = 0 do
                fetch birthdate into curage;
                if curage > maxsofar then
                    set maxsofar = curage;
                end if;
                if curage < minsofar then
                    set minsofar = curage;
                end if;
            end while;    
        close cur;

        set minage = minsofar;
        set maxage = maxsofar;
    end //
delimiter ;   
    

【问题讨论】:

  • 为什么要为此使用存储过程?您可以通过直接的 SQL 查询获得所需的信息。
  • @GMB 我正在学习

标签: mysql


【解决方案1】:

您的代码中有一些错误

  • 没有 tyoe 的声明无效
  • SET 只能在 DECLARE 之后使用
  • 你的 CORSOR 是当前不是生日

必须检查minsofar,maxsofar,curage,done的数据类型

存储过程:

   delimiter //
 create procedure getminmaxbirthdate(OUT minage date,OUT maxage date)
    begin
        DECLARE minsofar,maxsofar,curage,done VARCHAR(10);

        DECLARE cur CURSOR for
            select birth_date from employees;
            
        DECLARE continue handler for not found
            set done = 1;

        set minsofar = 2040-12-12;
        set maxsofar = 0;
        set done = 0;


        open cur;
            while done = 0 do
                fetch cur into curage;
                if curage > maxsofar then
                    set maxsofar = curage;
                end if;
                if curage < minsofar then
                    set minsofar = curage;
                end if;
            end while;    
        close cur;

        set minage = minsofar;
        set maxage = maxsofar;
    end //
delimiter ; 

【讨论】:

    【解决方案2】:

    您不使用简单查询是否有原因?

    select min(birth_date), max(birth_date)
    from employee;
    

    这个可以被合并到一个存储过程中,但这似乎是多余的。使用游标只是一种非常非常非常糟糕的做法——即使您正在学习 SQL。应避免使用游标,除非在必要的情况下——例如调用存储过程或为每一行调用动态 SQL。

    您的代码似乎也混淆了“年龄”和“日期”。有点不清楚你真正想要完成什么。

    【讨论】:

    • 我只想输出最小年龄和最大年龄
    • @SugumarVenkatesan 。 . .只需根据最小和最大生日计算年龄。
    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多