【问题标题】:Assigning function results to a variable in a MySql stored procedure将函数结果分配给 MySql 存储过程中的变量
【发布时间】:2023-01-14 00:26:47
【问题描述】:

我正在尝试编写一个存储过程来遍历价格表和产品表。如果价格与产品表中的 ID 匹配,则应将生效日期早于今天的最新价格应用于产品表中的“当前价格”列。因此,“currentPrice”列包含最新的活动价格,并且可以通过将未来日期插入价格表来安排价格更改。

目前我有这个:

DELIMITER $$
 create procedure updatePrice()
 begin
 declare loopLeng int default 1000;
 declare loopMax int default 1099;
 declare newPrice decimal(10,2);
 --select min(idProduct) into loopLeng from product;
--select count(idProduct) into loopMax from product;
set loopLeng  = 1000;
set loopMax = 1099;
 updateLoop : LOOP
    if loopLeng > loopMax  then 
    leave updateLoop;
    end if;
    select price into newPrice from price where idProduct = loopLeng and dateApplicableFrom = (select max(dateApplicableFrom) from price where idProduct = loopLeng and dateApplicableFrom <= current_timestamp());
    update product set currentPrice = newPrice where idProduct = loopLeng;
    set loopLeng = loopLeng + 1; 
    end loop;
    end
    $$ DELIMITER ;

这工作正常......但显然包含 loopLeng 和 loopMax 的硬编码值(定义产品循环的大小),因此如果产品数量发生变化,它就不灵活。我想根据 idProduct 的实际最小值和产品数量动态设置这些值,就像在注释的第 7 行和第 8 行中一样。这似乎对我有用并且不会给出任何错误,但是每当我执行该过程时这些定义无法执行必要的更新。

我还尝试创建临时变量,将函数结果选择到这些变量中,然后分配那些loopLeng 和 loopMax 的值,但这有相同的结果。到目前为止,我只能使用硬编码值使其按预期执行。有人可以建议我哪里出错了吗?

【问题讨论】:

    标签: mysql sql database mysql-workbench rdbms


    【解决方案1】:

    尝试使用准备好的语句如下:

    set @sql = 'select count(idProduct) into loopMax from product';
    PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
    
    set @sql = 'select count(idProduct) into loopMax from product;';
    PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
    

    【讨论】:

    • 谢谢,这似乎解决了问题:)
    【解决方案2】:

    解决方案是使用准备好的语句来分配值,如 SelVazi 的回答

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多