【问题标题】:PLSQL condition statement in trigger involving 2 tables涉及2个表的触发器中的PLSQL条件语句
【发布时间】:2015-12-01 19:56:09
【问题描述】:

我有两个表购买和客户,如果购买表中的购买时间 ptime(日期)与客户表中已经存在的 last_visit(日期)不同,我需要更新客户中的visits_made(数量)。 这是我正在尝试的触发器,我正在做一些非常可耻的错误。

create or replace trigger update_visits_made
after insert on purchases
for each row
declare new_date purchases.ptime%type;

begin
  select ptime into new_date
    from purchases
  where purchases.ptime = :new.ptime;

  if new_date = customers.last_visit then
    new.last_visit=old.last_visit;
  else
    update customers 
      set visits_made=visits_made+1
    where purchases.ptime=:new.ptime;
  end if;
end;
/
show errors

谁能告诉我哪里出错了?

我收到以下错误 行/列错误


10/15 PLS-00103:在期待其中一个时遇到符号“=” 下列的: := 。 (@%;

11/1 PLS-00103:遇到符号“ELSE”

16/1 PLS-00103:遇到符号“END”

【问题讨论】:

  • 请不要编辑问题来纠正其他人建议您的错误。否则,它会使问题看起来毫无意义。谢谢。

标签: sql oracle plsql triggers


【解决方案1】:

这是 PL/SQL 中的标量赋值:

new.last_visit = old.last_visit;

这不仅应该使用:=,而且newold 的名称前应该有冒号:

:new.last_visit := :old.last_visit;

一旦你解决了这个问题,update 就会出现问题:

update customers 
    set visits_made=visits_made+1
    where purchases.ptime = :new.ptime;

我不清楚这应该做什么,所以除了指出 purchases 没有定义之外,我无法提出任何建议。

【讨论】:

  • 谢谢,如果购买表中的购买时间 ptime 与客户当前的 last_visit 日期不同,我需要将客户中的visits_made 列更新 1。我尝试了你的建议,现在我收到以下错误 LINE/COL ERROR -------- -------------- --------------------------------------- 10/1 PLS-00049:错误的绑定变量' NEW.LAST_VISIT' 10/20 PLS-00049:错误的绑定变量'OLD.LAST_VISIT'@Gordon Linoff
  • 如果客户在同一天访问不止一次,那么 visit_made 不应该改变@Gordon Kinoff
【解决方案2】:
I think somehow i get your requirement. Basically its a ticker which count the vists of user based on Login dates. I have written a snippet below which replicates the same scenario as mentioned Above. Let me know if this helps.

-- Table creation and insertion script
CREATE TABLE PURCHASES
(
P_ID NUMBER,
P_TIME DATE
);

INSERT INTO PURCHASES
SELECT LEVEL,SYSDATE+LEVEL FROM DUAL
CONNECT BY LEVEL < 10;

CREATE TABLE CUSTOMERS
(
P_ID NUMBER,
P_VISITS NUMBER
);

INSERT INTO CUSTOMERS
SELECT LEVEL,NULL FROM DUAL
CONNECT BY LEVEL < 10;

-- Table creation and insertion script

--Trigger Script

CREATE OR REPLACE TRIGGER update_purchase BEFORE
  INSERT ON purchases FOR EACH row 
  DECLARE 
  new_date purchases.p_time%type;
  BEGIN
  BEGIN
  SELECT A.P_TIME
    INTO new_date
    FROM
  (SELECT p_time,
    ROW_NUMBER() OVER(PARTITION BY P_ID ORDER BY P_TIME DESC) RNK
    --    INTO new_date
  FROM purchases
  WHERE purchases.p_id = :new.p_id
  )a
WHERE A.RNK =1;
    EXCEPTION WHEN OTHERS THEN
    RETURN;
    END;
IF :NEW.P_TIME <> new_date THEN
  UPDATE customers
  SET P_VISITS        =NVL(P_VISITS,0)+1
  WHERE p_id=:new.p_id;
END IF;
END;

--Trigger Script


--Testing Script
INSERT INTO PURCHASES VALUES
(9,TO_DATE('12/11/2015','MM/DD/YYYY'));

--Testing Script

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多