Skip to Main Content
  • Questions
  • Tricky Sequence value requirement thru Trigger

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question.

Asked: July 18, 2016 - 8:10 pm UTC

Last updated: September 02, 2016 - 3:13 pm UTC

Version: 12c

Viewed 1000+ times

You Asked

Hi Wonderful Team,

I have an oracle sequence say s.

I have table t ( id number , n number );

I need to insert the Id column with the sequence s such that the value is the same for the entire transaction thru a "Trigger"

So this Id changes only for new batch inserts.

If I use s.nextval it will insert a new value for each row. I want the same value for that insert.

I cant use s.currval as value is not initialized.

I dont want pl/sql solution( declare v number := s.nextval ; begin insert into t(id, n) select v,object_id from user_objects ;commit;)

This has to happen in trigger

How to do it ?

create sequence s ;
create table t( id number , n number ) ;

Thanks

and Chris said...

This has to happen in trigger

Why? Why does this have to happen in a trigger? You have a perfectly good PL/SQL solution available!

If you really must use a trigger, from 11g up you can use a compound trigger. This enables you to initialize a variable holding the current sequence value once. Then assign it for each row:

create sequence s ;
create table t( id number not null, n number ) ;

create or replace trigger trg 
for insert on t compound trigger

  t_id t.id%type := s.nextval;
  
  before each row is 
  begin
    :new.id := t_id;
  end before each row;
end;
/
insert into t(n) select object_id from user_objects ;

select * from t
where  rownum < 6;

ID  N        
1   131,679  
1   97,493   
1   131,678  
1   131,680  
1   131,681

Rating

  (3 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Excellant - Why The Trigger soln

A reader, July 19, 2016 - 1:25 pm UTC

Thought of using Trigger because this insert - load will happen thru informatica ETL tool. I dont want to use those ETL Auto generator.

So thought Trigger could help. What are the other options to feed this in if using third party software to insert.

Dont want to call pl/sql proc from ETL. They load thru mappings.

I hope this trigger solution is not an overkill

last user input NOT inswered

A reader, September 02, 2016 - 1:51 pm UTC


Chris Saxon
September 02, 2016 - 3:04 pm UTC

last user input NOT inswered

what's not inswered?

A reader, September 02, 2016 - 3:10 pm UTC

"What are the other options to feed this in if using third party software to insert. "
Chris Saxon
September 02, 2016 - 3:13 pm UTC

If you can't change the code, there aren't really any other options.

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library