如果在Oracle SQL中触发器的Else Condition

时间:2012-12-25 14:44:27

标签: sql database oracle triggers

我有两张桌子。他们是

CARD(cardid, credit, usertype,charge)

PAYMENTDEVICE(paydevid, paydevip,paydevdate, paydevtime, chargedcardid, mealtype). 

膳食类型可以是“客人”或“标准”。我想在支付设备中插入新行时更新卡表中的信用。费用取决于使用类型。但如果用餐类型是客人,每个人都需要支付5美元。我尝试使用以下代码

CREATE OR REPLACE TRIGGER  "TRG_PAYMONEY" 
AFTER INSERT
ON PAYMENTDEVICE FOR EACH ROW

BEGIN
UPDATE CARD
WHERE CARDID = :NEW.CHARGEDCARDID
SET CREDIT = 
(CASE MEALTYPE

WHEN "STANDARD" THEN CREDIT - CHARGE
WHEN "GUEST" THEN CREDIT - 5
END);
END;

但我收到此错误: PL/SQL: ORA-00971: missing SET keyword, PL/SQL: SQL Statement ignored。你能帮帮我吗?

4 个答案:

答案 0 :(得分:5)

请按照以下语法进行更新,

update table_name set field1='value' where field2='value'

(即)

UPDATE CARD
SET CREDIT = 
(CASE MEALTYPE
WHEN "STANDARD" THEN CREDIT - CHARGE
WHEN "GUEST" THEN CREDIT - 5
END)
 WHERE CARDID = :NEW.CHARGEDCARDID;

有关更多信息,'update'语句的工作原理请参阅此文档,

http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/update_statement.htm

对于你的第二个错误,试试这个,

UPDATE CARD
SET CREDIT = 
(CASE 
WHEN MEALTYPE="STANDARD" THEN CREDIT - CHARGE
WHEN MEALTYPE="GUEST" THEN CREDIT - 5
END MEALTYPE) 
 WHERE CARDID = :NEW.CHARGEDCARDID;

像这样,

update card c
set c.credit=(select case when p.mealtype='STANDARD' then c.credit-c.charge
                 when p.mealtype='GUEST' then c.credit-5
            end credit from PAYMENTDEVICE p
           where c.cardid=p.chargedcardid)

fiddle_demo

答案 1 :(得分:1)

您的更新声明应为(WHERE应在SET之后)

UPDATE CARD
SET CREDIT = 
(CASE MEALTYPE

WHEN "STANDARD" THEN CREDIT - CHARGE
WHEN "GUEST" THEN CREDIT - 5
WHERE CARDID = :NEW.CHARGEDCARDID

答案 2 :(得分:0)

请运行此代码..

CREATE OR REPLACE TRIGGER TRG_PAYMONEY1
AFTER INSERT ON PAYMENTDEVICE 
FOR EACH ROW
BEGIN
UPDATE CARD c
SET c.credit=(select case when p.mealtype='STANDARD' then c.credit-c.charge
                 when p.mealtype='GUEST' then c.credit-5
            end result from PAYMENTDEVICE p,card c
           where c.cardid=p.chargedcardid)
WHERE CARDID = :NEW.CHARGEDCARDID;
END;

答案 3 :(得分:0)

嗯,经过一些研究并感谢Oracle Documentation,我们解决了这个实现的问题:

CREATE OR REPLACE TRIGGER  "TRG_PAYMONEY" 
AFTER INSERT
ON PAYMENTDEVICE FOR EACH ROW

BEGIN
IF :NEW.MEALTYPE='GUEST' THEN
UPDATE CARD
SET CREDIT = CREDIT - 5
WHERE CARDID = :NEW.CHARGEDCARDID;
ELSE
UPDATE CARD
SET CREDIT = CREDIT - CHARGE
WHERE CARDID = :NEW.CHARGEDCARDID;
END IF;
END;

谢谢你的帮助&建议。