MySQL声明游标错误

时间:2016-04-15 22:32:40

标签: mysql cursor

这是我第一次使用游标上的MySQL,我遇到了一些问题,它不接受我的光标声明,我的代码有什么问题?它告诉我这个错误messgae:

#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 @MyCursor CURSOR' at line 1 

我的代码是:

DECLARE @MyCursor CURSOR;
DECLARE @MyField varchar2(255);
BEGIN
    SET @MyCursor = CURSOR FOR
    SELECT codeMaint from affectationmc where iduser=29;     

    OPEN @MyCursor 
    FETCH NEXT FROM @MyCursor 
    INTO @MyField

    WHILE @@FETCH_STATUS = 0
    BEGIN
    delete from mcorr where codemaint=@MyField ;
      FETCH NEXT FROM @MyCursor 
      INTO @MyField 
    END; 

    CLOSE @MyCursor ;
    DEALLOCATE @MyCursor;
END;

2 个答案:

答案 0 :(得分:0)

这是我用于游标的模板。它只是从select中取出项目并将它们映射到最顶层声明的变量并执行你的语句。一旦它处理--Action to Loop Here部分中的语句,它就会通过从select语句中选择下一行来更改变量。这将重复,直到它处理选择中的所有行。

DECLARE 

 @variable_A AS varchar(15)
,@variable_B AS INT
,@variable_C AS INT
,@variable_D AS VARCHAR(255)

DECLARE Process_Name CURSOR LOCAL FAST_FORWARD FOR 
            SELECT 
                        T.Col_A,T.Col_B,T.Col_C,T.Col_D
            FROM 
                        tab.my_table AS T;


OPEN Process_Name 
FETCH NEXT FROM Process_Name INTO @variable_A,@variable_B,@variable_C,@variable_D

WHILE @@FETCH_STATUS = 0
BEGIN


--Actions to Loop Here


FETCH NEXT FROM Process_Name INTO @variable_A,@variable_B,@variable_C,@variable_D
END

CLOSE Process_Name 
DEALLOCATE Process_Name 

答案 1 :(得分:0)

您尝试在一个语句中声明游标,然后在第二个语句中将查询与其关联。虽然有些数据库允许这样做,但我相当确定MySQL不是其中之一。此外,MySQL在声明所有变量之后才宣布游标是非常严格的。

这是我将如何做到的:

BEGIN  -- note all declarations are inside the BEGIN/END
  DECLARE done INT DEFAULT FALSE;  -- Good practice is to avoid global variables whenever possible
  DECLARE MyField varchar(255); -- varchar2 is Oracle, not MySQL

  DECLARE MyCursor CURSOR FOR
    SELECT codeMaint
      FROM affectationmc
      WHERE iduser = 29;

  DECLARE CONTINUE HANDLER FOR NOT FOUND
    SET done = TRUE;  -- this will detect end-of-result-set

  OPEN MyCursor;
  read_loop: LOOP
    FETCH NEXT
      FROM MyCursor 
      INTO MyField;
    IF done THEN
      LEAVE read_loop;
    END IF;

    DELETE FROM mcorr
      WHERE codemaint = MyField ;
  END LOOP;

  CLOSE MyCursor;
END;