触发器声明中局部变量中的语法错误

时间:2013-07-16 18:34:27

标签: mysql stored-procedures user-variables

我有以下商店程序

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 documentation中的

我可以运行SELECT id, data INTO @x, @y FROM test.t1 LIMIT 1;。 使用FETCH时出现问题吗?或者有什么问题?

1 个答案:

答案 0 :(得分:1)

FETCH(从光标抓取下一条记录并前进光标)SELECT ... INTO相同(仅适用于返回单条记录的查询) )。

FETCH只能 提取到local variables(没有@前缀但在存储的程序开头必须为DECLARE d ),而SELECT ... INTO也可以提取到user-defined variables(前缀@且不是DECLARE d)。

因此,您必须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

所有这一切,你的sproc是非常不安全的(第一个INSERT语句和随后的SET之间存在种族危险)以及一种非常笨拙的方式来做一些应该简单得多的事情