我有两张桌子购买和客户,如果购买表中的购买时间(日期)与customers表中已有的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
有人可以告诉我哪里出错了吗?
我收到以下错误 LINE / COL ERROR
10/15 PLS-00103:当期待其中一个时遇到符号“=” 以下: :=。 (@%;
11/1 PLS-00103:遇到符号“ELSE”
16/1 PLS-00103:遇到符号“END”
答案 0 :(得分:1)
这是PL / SQL中的标量赋值:
new.last_visit = old.last_visit;
不仅应该使用:=
,而且new
和old
应该在其名称前加冒号:
:new.last_visit := :old.last_visit;
修复该问题后,update
会出现问题:
update customers
set visits_made=visits_made+1
where purchases.ptime = :new.ptime;
我不清楚这应该是做什么的,所以我不能提出任何建议,除了指出purchases
没有被定义。
答案 1 :(得分:0)
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