ORACLE触发打印相关行

时间:2014-12-02 21:29:19

标签: oracle triggers

我有一个触发器,其目的是检查新插入的行的活动,如果活动已经在表中,则打印出一条消息。该消息将打印正在添加的新行以及已有该活动的行。我能够打印行并且有重复但无法弄清楚如何初始化重复行的值然后打印它。

触发:

create or replace trigger insertActivities
before insert
on ACTIVITIES
for EACH row
declare
n int;
otherName varchar(30);
otherActivity varchar(30);
otherMinutes varchar(30);

begin
select Count(*)
into n
from ACTIVITIES
where Activity = :NEW.Activity;

if n>0 then 
dbms_output.put_line('Duplicate activity. New Name: ' || :NEW.Name || ' New Activity: '||    :NEW.Activity
|| ' New Minutes: '|| :NEW.Minutes || ' Other Name: ' || otherName || ' Other Activity: ' ||  otherActivity
|| 'Other Minutes: '|| otherMinutes);
end if;

END;

我知道'其他'变量是错误的,它们是一种占位符,直到我能弄清楚如何正确地做到这一点。感谢。

2 个答案:

答案 0 :(得分:0)

假设"唯一性"您的活动

select Count(*),max(name),max(minutes)
into n, otherName, otherMinute
from ACTIVITIES
where Activity = :NEW.Activity; -- <-- is this an unique key ???

使用聚合函数MAX将允许您在计数的同时查询列。

您可以使用GROUP BY子句而不是使用聚合函数。我不知道哪一个会是最好的。

如果您的活动唯一,那么如果您要记录所有&#34;重复项&#34;,则必须循环使用游标。


然而,正如我在评论中所说,如果同时插入&#34;相同的&#34;这可能不会像你预期的那样表现。活动。在这种情况下,很可能(取决于您的隔离级别),两个插入都将被执行,而不会检测到&#34;重复&#34;。

答案 1 :(得分:0)

也许我的问题出错了,但你的意思是

select *
from ACTIVITIES
where Activity = :NEW.Activity
  and rowid!=:new.rowid;