如何使用 phpmyadmin 在存储过程中创建一段时间,错误 #1064

How to make a while in a stored procedure with phpmyadmin, error #1064

我尝试在 phpmyadmin 中创建存储过程,但在第 12 行(WHILE 所在的位置)出现错误 1064。这是我第一次尝试创建存储过程。

BEGIN

DECLARE product_id INT;
DECLARE  product_min_age nvarchar(500);
DECLARE  cur CURSOR for
SELECT product_min_age, product_id FROM _vm_product;

open cur;

fetch next from cur into product_min_age, product_id;

while FETCH_STATUS = 0 BEGIN

    INSERT INTO _virtuemart_product_customfields (virtuemart_product_id, virtuemart_custom_id, customfield_value, customfield_params) VALUES
    ( product_id, 5, product_min_age, 'addEmpty=0|selectType=0|');

    fetch next from cur into product_min_age,product_id;
END;

close cur;

END

谢谢

您应该将其更改为以下内容。有关详细信息,请参阅 Documentation

open cur;

read_loop: LOOP
fetch cur into product_min_age, product_id;

    INSERT INTO _virtuemart_product_customfields (virtuemart_product_id, virtuemart_custom_id, customfield_value, customfield_params) VALUES
    ( product_id, 5, product_min_age, 'addEmpty=0|selectType=0|');

END LOOP;

close cur;

如果有人想看我的最终结果:

BEGIN

DECLARE _product_id INT;
DECLARE  _product_min_age nvarchar(500);
DECLARE done INT DEFAULT 0;
DECLARE  cur CURSOR for SELECT product_min_age, product_id FROM _vm_product;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

open cur;
read_loop: LOOP
fetch cur into _product_min_age, _product_id;
    IF done = 1 THEN
        LEAVE read_loop;
    END IF;

    INSERT INTO _virtuemart_product_customfields (virtuemart_product_id, virtuemart_custom_id, customfield_value, customfield_params) VALUES
    ( _product_id, 5, _product_min_age, 'addEmpty=0|selectType=0|');

END LOOP;

close cur;

END

接受的答案确实是正确的,你自己的答案也是正确的。不幸的是,这个方法是完全错误的!

除非万不得已,否则通常不会在循环内执行 sql 查询。 Select / loop / insert 实际上是人们编写第一个存储过程时经常遵循的模式。但是有更好的方法,更好的方法。那就是 INSERT .. SELECT

With INSERT ... SELECT, you can quickly insert many rows into a table from one or many tables. For example:

您的复杂存储过程减少为:

INSERT INTO _virtuemart_product_customfields (virtuemart_product_id, virtuemart_custom_id, customfield_value, customfield_params) 
SELECT product_id, 5, product_min_age, 'addEmpty=0|selectType=0|' 
FROM _vm_product

就是这样,只是一个简单的select,没有存储过程!

第二个问题是您在列中存储了带分隔符的文本。

  addEmpty=0|selectType=0|

我不太清楚你为什么要这样做,但这是最不寻常的。