【问题标题】:Error with cursor in MySQLMySQL中的游标错误
【发布时间】:2018-04-26 06:20:45
【问题描述】:

我在 MySQL 中的下一个带有光标的脚本中有下一个错误。 “脚本行:4 您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以在 'declare c_salari cursor for select salario from empleados; 附近使用正确的语法;

打开 c_salari;

' 在第 10 行 "

DELIMITER $$

DROP FUNCTION IF EXISTS `empresa`.`EmpleatsRang` $$
CREATE FUNCTION `empresa`.`EmpleatsRang` (valor_inicial int, valor_final int) RETURNS INT
BEGIN
declare i int default 0;
declare resultat int default 0;
declare totalemp int;
declare v_salario int;
declare c_salari cursor for select salario from empleados;

select count(*) into totalemp from empleados;

open c_salari;

while i<totalemp do
  fetch c_salari into v_salario;
  if salari >= valor_inicial and salari <= valor_final then
    resultat=resultat+1;
  end if;
  i=i+1;
end while;

close c_salari;
return resultat;
END $$

DELIMITER ;

【问题讨论】:

  • 为什么当你只对一个范围感兴趣时选择所有的 salarios 到光标中(这反过来意味着你的循环做的比它需要的更多),你没有错误检查 valor_initial , valor_final 来验证您可以做任何明智的事情,而您可以使用计数器退出循环,处理程序是更常用的方法。

标签: mysql sql database


【解决方案1】:

所有 declare 语句都应该出现在 begin 本身之后和任何 select 之前。 所以写

Declare c_salari cursor for select salario from empleados; 

之前

select count(*) into totalemp from empleados;

【讨论】:

    【解决方案2】:

    这是因为我没有将集合放入变量“i”和变量“resultat”

    while i<totalemp do
      fetch c_salari into v_salario;
      if salari >= valor_inicial and salari <= valor_final then
        set resultat=resultat+1; /*Need set*/
      end if;
      set i=i+1; /*Need set*/
    end while;
    

    【讨论】:

      【解决方案3】:

      不要将光标用于这样简单的任务。请改用 SELECT。

      select count(salario)
      from empleados
      where salari >= valor_inicial and salari <= valor_final
      

      经验法则是:如果可能,请使用一条 SQL 语句。如果没有,请使用更多 SQL 语句。游标是最后一个选项,它会影响 DBMS 的性能。

      【讨论】:

      • 我需要使用光标,因为它是为了锻炼
      【解决方案4】:

      请在结束后使用分号

      【讨论】:

        猜你喜欢
        • 2018-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        • 2017-01-14
        • 2018-04-04
        • 1970-01-01
        相关资源
        最近更新 更多