Forum Stats

  • 3,838,732 Users
  • 2,262,395 Discussions
  • 7,900,743 Comments

Discussions

newbie Trigger with Insert Record

Steve42
Steve42 Member Posts: 142
edited Sep 17, 2008 5:09PM in SQL & PL/SQL
Here's what I want the table to look like

orgn Eventid
3601 1
3601 2
3601 3
3601 ...
4014 1
4014 2
4014 3
4014 ...

I want ALL Eventid to start with 1 for EACH ORGN.
All Eventid MUST be UNIQUE.
When a USER inserts a record, I need it to calculate the next EVENTID #.


CREATE OR REPLACE
TRIGGER EVENT_TGR
Before INSERT ON TESTSEQUENCE
referencing new as new old as old
for each row
declare
v_Eventnum_nr number;
BEGIN
NULL;
select event_seq.nextval INTO :new.Eventnum from testSequence
where :new.fiscalyear=2008 and :new.orgn='3601' and rownum<=1;

END;
I have not been able to figure out how to pass ORGN and FiscalYear to trigger.

Suggestions? Comments?

Thanks.
Steve

Answers

  • JustinCave
    JustinCave Member Posts: 30,293 Gold Crown
    I want ALL Eventid to start with 1 for EACH ORGN.
    All Eventid MUST be UNIQUE.

    These statements contradict each other. If each event_id has to be unique, by definition, you cannot restart at 1. Restarting at 1 inherently makes event_id non-unique. I am assuming that you don't really want event_id to be unique based on the rest of your question.

    A trigger based approach is not going to work... A trigger on table A cannot query table A (barring some exceptional situations that are rarely practical). Triggers in general would also be inappropriate in a multi-user environment.

    Normally, you would solve this problem by

    - Not creating an Event_ID column in the table
    - Not creating an Event_Seq sequence
    - Adding (or using) a Create_Date column (as a DATE or TIMESTAMP depending on the frequency of updates)
    - Creating a view that does something like
    SELECT orgn, rank() over (partition by orgn order by create_date) event_id
      FROM your_table
    Justin
  • 245482
    245482 Member Posts: 1,254
    It's a relational database. Put those in separate tables with a foreign key between them.
This discussion has been closed.