views:

89

answers:

3

I have two tables:

create table Number( num number(5));

create table Entry(id number(3), name varchar(50));

How can I increment the num field of Number table in Oracle whenever I insert something in the Entry table?

+2  A: 

Do you want number.num to continually represent the number of rows iin the Entry table? If so you could just define it as a view:

create view number_view
as
select count(*) from Entry
David Aldridge
Agree. I don't think the relationship between the two tables has been explained fully by the OP.
Dougman
+8  A: 

You should use a SEQUENCE instead. The "Number" table is an inherently bad idea, because when two sessions are inserting rows concurrently, each session only sees the uncommited value in the Number table.

This is what you should do instead:

create sequence entrySeq;

create table Entry(id number(3), name varchar(50));

create trigger tr_entry before insert on Entry for each row
begin
  select entrySeq.nextval into :new.number from dual;
end;
/
ammoQ
That's why there are sequences in Oracle .. use them! (Or avoid using them at your own risk.)
IronGoofy
A: 
create sequence entrySeq;

create table Entry(id number(3), name varchar(50));

insert into Entry value (entrySeq.nextval, 'MyName');

(You don't need a trigger).

A sequence returns a unique and increasing number value but Oracle doesn't guarantuee that it is gapless. When sometimes transactions are rollbacked the values of column id will contain gaps.

tuinstoel