问题描述
这是一个简单的功能,可将供应库存从一个仓库转移到另一个仓库。它将所有原始库存向上插入目标仓库,然后从原始仓库中删除库存。
这可能是一个愚蠢的语法错误,但由于on conflict (..) update
子句无法识别错误为tsrc.stock
的{{1}},我正在努力解析此函数。
ERROR: missing FROM-clause entry for table "tsrc"
即使使用create or replace function move_stock_to_another_warehouse (
_src_warehouse_id int,_dst_warehouse_id int,_supply_id int
)
returns int
volatile language sql as $$
-- try to insert a new row into table warehouse_supply for the destination warehouse
insert into warehouse_supply as tdst (
warehouse_id,supply_id,stock
)
select
_dst_warehouse_id,_supply_id,stock
from
warehouse_supply as tsrc
where
warehouse_id = _src_warehouse_id and
supply_id = _supply_id
on conflict (warehouse_id,supply_id) do update
-- a row in table warehouse_supply existed for the destination warehouse,just increase the stock
set
stock = tdst.stock + tsrc.stock;
-- zero the stocks in the source warehouse
update
warehouse_supply as tnew
set
stock = 0
from
warehouse_supply as told
where
tnew.warehouse_id = _src_warehouse_id and
tnew.supply_id = _supply_id and
told.id = tnew.id
returning
coalesce(told.stock,0); -- returns 0 even if the supply did not exist in the source warehouse
$$;
,我也尝试了多种方法,但是找不到找到第一个with
子句的源数据是update
的子句的方法。
有什么主意吗?
解决方法
您可以使用伪表excluded
,其中包含建议插入的行:
...
on conflict (warehouse_id,supply_id) do update
set stock = tdst.stock + excluded.stock