【发布时间】: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