0

我有以下存储过程

CREATE PROCEDURE `update_ordenes`()
BEGIN
    DECLARE record CURSOR FOR 
        SELECT ordenes.idorden, ordenes.idafiliado 
            FROM ordenes, afiliados 
            WHERE afiliados.idafiliado = ordenes.idafiliado;

    OPEN record;
    REPEAT
        FETCH record INTO @id_orden, @id_afil_viejo;

        INSERT INTO afil2(nombre, apellido, documento) 
            (SELECT nombre, apellido, documento
                FROM afiliados 
                WHERE idafiliado = @id_afil_viejo);

        SET @last_id = (SELECT id FROM afil2 ORDER BY id DESC LIMIT 1);

        UPDATE ordenes 
        SET afil2 = @last_id,
            ordenes.idafiliado = NULL
        WHERE ordenes.idafiliado = @id_afil_viejo
              AND ordenes.idorden = @orden_id;
    UNTIL done END REPEAT;
END

出于某种原因,我在行出现语法错误FETCH record INTO @id_orden, @id_afil_viejo;

mysql 文档中我可以运行SELECT id, data INTO @x, @y FROM test.t1 LIMIT 1;. 是使用中的问题FETCH吗?或有什么问题?

4

1 回答 1

1

FETCH(从游标中获取下一条记录并前进)与SELECT ... INTO仅适用于返回单个记录的查询)不同。

FETCH只能提取到局部变量(没有前缀但必须在存储程序的开头为 d),而也可以提取到用户定义的变量(有前缀但不是d)。@DECLARESELECT ... INTO@DECLARE

因此,您必须DECLARE使用一个局部变量来FETCH编辑您的记录:

CREATE PROCEDURE `update_ordenes`()
BEGIN

    DECLARE id_orden BIGINT UNSIGNED DEFAULT 5;  -- as appropriate
    DECLARE id_afiv_viejo VARCHAR(15) NOT NULL;  -- as appropriate

    DECLARE record CURSOR FOR 
        SELECT ordenes.idorden, ordenes.idafiliado 
            FROM ordenes, afiliados 
            WHERE afiliados.idafiliado = ordenes.idafiliado;

    OPEN record;
    REPEAT
        FETCH record INTO id_orden, id_afil_viejo;

        INSERT INTO afil2(nombre, apellido, documento) 
            (SELECT nombre, apellido, documento
                FROM afiliados 
                WHERE idafiliado = id_afil_viejo);

        SET @last_id = (SELECT id FROM afil2 ORDER BY id DESC LIMIT 1);

        UPDATE ordenes 
        SET afil2 = @last_id,
            ordenes.idafiliado = NULL
        WHERE ordenes.idafiliado = id_afil_viejo
              AND ordenes.idorden = id_orden;
    UNTIL done END REPEAT;
END

INSERT综上所述,您的存储过程非常不安全(在第一条语句和随后的语句之间存在竞争危险SET),并且是一种非常笨拙的方式来做一些应该更简单的事情。

于 2013-07-16T18:43:47.820 回答