我有以下商店程序
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;
行
我可以运行SELECT id, data INTO @x, @y FROM test.t1 LIMIT 1;
。
使用FETCH
时出现问题吗?或者有什么问题?
答案 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
之间存在种族危险)以及一种非常笨拙的方式来做一些应该简单得多的事情