簡體   English   中英

如何在存儲過程中使用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

謝謝

您應該將其更改為以下內容。 有關更多信息,請參見文檔

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;

接受的答案確實是正確的,您自己的答案也是如此。 不幸的是,這種方法是完全錯誤的!

除非作為最后的手段,否則通常不會在循環內執行sql查詢。 選擇/循環/插入實際上是一種常見的模式,隨后人們編寫了他們的第一個存儲過程。 但是有更好的方法,也有更好的方法。 那就是INSERT .. SELECT

使用INSERT ... SELECT,您可以將一個或多個表中的許多行快速插入到一個表中。 例如:

您的復雜存儲過程可以簡化為:

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

就是這樣,只需簡單選擇,就無需存儲過程!

第二個問題是您將分隔文本存儲在列中。

  addEmpty=0|selectType=0|

我不太確定為什么要這么做,但這是最不尋常的。

如果有人想查看我的最終結果:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM