【问题标题】:Using if statement in Oracle triggers在 Oracle 触发器中使用 if 语句
【发布时间】:2012-12-18 17:29:14
【问题描述】:
  1. 表 1:客户

    cust_no | cust_credbal |信用状态

  2. 表 2:customer_credittopup

    cust_no |交易金额

我有上面两张表,我在插入Table2后写了一个更新触发器来更新Table1。因此,Table1cust_credbal 中的金额在 Tabl1 中添加 cust_credbal + Table2trans_amount 中的新值后更新。如何在更新后添加 if 语句以检查 cust_credbal 是否大于 20,然后 cred_status 设置为“有效”,否则为“已用完”

我的触发器显示此错误:第 8 行错误:PLS-00049: bad bind variable 'NEW.CUST_CREDITBAL'

CREATE OR REPLACE TRIGGER after_insert_credittopup
AFTER INSERT ON customer_credittopup
FOR EACH ROW 
DECLARE 
  credit number(11);
BEGIN
  UPDATE customers
     SET cust_creditbal=cust_creditbal +:new.trans_amount
   WHERE cust_no=:new.cust_no;

  SELECT Cust_creditbal INTO credit 
    FROM customers WHERE cust_no=:new.cust_no;

  IF(:new.cust_creditbal>0) THEN
    UPDATE customers
       SET Cust_credstatus='Valid'
     WHERE cust_no=:new.cust_no;
  end if;
end;
/

【问题讨论】:

  • 哪个表有 'cust_creditbal' 字段?如果它在customers 中,则:new.cust_creditbal 仅在customers 表上的触发器内才有意义。

标签: sql database oracle triggers


【解决方案1】:

您似乎只需要 1 条更新语句:

UPDATE customers
SET cust_creditbal=cust_creditbal +:new.trans_amount,
Cust_credstatus = CASE WHEN cust_creditbal +:new.trans_amount > 0 THEN 'Valid'
 ELSE 'Invalid' 
 --or if you don't want to change status in such case just put 
 --ELSE Cust_credstatus 
 END
 WHERE cust_no=:new.cust_no;
 --SELECT Cust_creditbal INTO credit FROM customers WHERE cust_no=:new.cust_no;
 --IF(:new.cust_creditbal>0) THEN
 --UPDATE customers
 --SET Cust_credstatus='Valid'
 --WHERE cust_no=:new.cust_no;

【讨论】:

  • 这在 2 个条件下就像一个魅力,如果我有 4 个条件,例如 cust_credbal > 20 是有效的,小于 0 超限,等于 0 用 else if 耗尽
  • 您可以在 CASE 内部进行操作:例如 WHEN cust_creditbal +:new.trans_amount >0 THEN 'Valid' WHEN cust_creditbal +:new.trans_amount <0 THEN 'Overlimit' ELSE 'Exhausted' END
【解决方案2】:

NEW.CUST_CREDITBAL 不匹配 cust_credbal

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多