为什么MySQL在CONCAT语句中发现错误?

时间:2015-05-11 22:15:01

标签: mysql stored-procedures

我正在尝试在MySQL中编写存储过程,我需要在游标上循环,然后执行一个SQL语句,该语句使用游标中的一段数据获取到变量中,然后作为SQL执行。光标orders_cur在this_addr上排序;在this_addr记录的给定块中,跳过第一条记录,其余的需要通过设置duplicateorder =“1”来标记。

出于某种原因,我无法使用CONCAT功能来运行而不会给我一个错误:

            OPEN orders_cur;
            order_loop: LOOP
                -- Now loop on orders_cur until this_addr = match_addr
                find_addr_loop: REPEAT
                    FETCH orders_cur INTO this_addr,this_orderid;
                UNTIL this_addr = match_addr
                END REPEAT;
                -- Skip the first order that matched by performing another fetch
                FETCH orders_cur INTO this_addr,this_orderid;
                -- Now start next loop which does the real work; set duplicateorder on the remaining records in cursor,
                -- using the orders_cur.order_id to locate the actual record in the Reservations table. 
                set_dupe_loop: WHILE this_addr = match_addr
                    SET @sql = CONCAT('UPDATE Reservations SET duplicateorder = \'1\' WHERE order_id=',this_orderid);
                    PREPARE runme FROM @sql;
                    EXECUTE runme;
                    FETCH orders_cur INTO this_addr,this_orderid;
                END WHILE set_dupe_loop:;
                DEALLOCATE PREPARE runme;
            END LOOP order_loop;

我已经尝试过各种变化,以逃避我在'1'周围所需的文字无济于事,并且我会睁大眼睛......如果有人看到我的错误所在,我会非常感激..

- rixter

2 个答案:

答案 0 :(得分:1)

CONCAT没有问题,循环没有正确启动/封闭。

set_dupe_loop: WHILE this_addr = match_addr

应该是set_dupe_loop: WHILE this_addr = match_addr DO

答案 1 :(得分:1)

您不需要光标来执行此操作。你可以这样做:

UPDATE Reservations r JOIN
       (SELECT this_addr, MIN(order_id) as minoi
        FROM Reservations r2 
        WHERE this_addr = match_addr
        GROUP BY this_addr
       ) dups
       ON r.this_addr = dups.this_addr and r.order_id > dups.minoi
    SET r.duplicateorder = 1;

通常,您应该避免使用游标,尤其是那些需要动态SQL的游标。当您可以将逻辑表示为集合操作时,通常最好这样做。