sql - 无法使用 SQL 中的触发器生成或更新表行
问题描述
我正在尝试在 Oracle SQL 12c 中创建触发器。
这个概念是我有两个表,一个存储表(Storage)
保存项目和一个交付表(Supplier_Orders)
记录有多少项目(Units)
被交付到存储。触发器应该检测是否有一个项目被交付到存储( new_product_id
) 已经存在于 storage( product_id
) 中,如果不存在,它会自动添加它并要求用户输入一些强制值 (barcode
和sell_price
)。如果存在,它会通过将要交付的项目 ( Units
)添加到表中来更新表项目总数(remaining_units
)。
create or replace trigger SL_ORD_ADDER_TR
before insert on Supplier_Orders
for each row
begin
if :new.new_product_id in (select s.product_id from storage s where (:new.new_product_id=s.product_id)) then
update storage
set remaining_units = remaining_units + new.units
where new.new_product_id=product_id;
end if;
if :new.new_product_id not in(select s.product_id from storage s where (:new.new_product_id=s.product_id)) then
insert into storage(product_id,product_name,remaining_units,barcode,sell_price_per_unit) values(new.new_product_id,new.product_name,new.units,'&barcode','&sell price');
end if;
end;
产生的错误如下:
错误(5,5):PL/SQL:语句被忽略
错误(5,31):PLS-00405:此上下文中不允许子查询
错误(10,5):PL/SQL:语句被忽略
错误(10,34):PLS-00405:此上下文中不允许子查询
解决方案
在代码中的 IF 条件之后,PL/SQL 中不允许使用子查询。仅在 SQL 中允许。
您可以使用变量检查“存储”表中的“product_id”并确定其上的 IF 条件。
CREATE OR REPLACE TRIGGER SL_ORD_ADDER_TR
BEFORE INSERT on Supplier_Orders
REFERENCING
NEW AS new
OLD AS old
for each row
DECLARE
-- New variable
v_cnt number;
begin
select count(s.product_id) into v_cnt from storage s where s.product_id=:new.new_product_id;
if v_cnt>0
-- It exists, so updating
then
update storage
set remaining_units = remaining_units + :new.units
where product_id=:new.new_product_id;
end if;
if v_cnt=0
-- It not exists, so inserting
then
insert into storage(product_id,product_name,remaining_units,barcode,sell_price_per_unit)
values(:new.new_product_id,:new.product_name,:new.units,'&barcode','&sell price');
end if;
end;
推荐阅读
- reactjs - 使用 Webpack、typescript、css 模块和 SASS 配置 React 组件库的最佳方法是什么
- python-3.x - 如何解决安装tensorflow时出现的问题:HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out
- geometry - 围绕网格中的一个点缩放:重绘网格并移动“原点”,使光标下的点保持固定
- python - Python:将分钟或秒添加到仅限时间的对象
- java - 我们怎么能在一定范围内,最大次数,一个int能被2整除
- mysql - 从表中删除数据而不创建临时表
- ios - Swift:重构 NSMutableAttributedString
- zk - 如何使用动态文本框创建通信
- mule - Mule 是否支持键中的“-”(连字符)?
- javascript - 带有 JQuery 事件的条码阅读器