If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > Oracle > auto number??

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 03-03-03, 12:49
rhs98 rhs98 is offline
Super Moderator
 
Join Date: Feb 2002
Location: Hampshire, UK
Posts: 441
Question auto number??

Is there an oracle equivelent of an Access "auto number" field - i.e a number that is unique and automatically generated?

Or do i have to write a trigger or something???
Reply With Quote
  #2 (permalink)  
Old 03-03-03, 13:17
andrewst andrewst is offline
Moderator.
 
Join Date: Sep 2002
Location: UK
Posts: 5,171
Re: auto number??

You have to create a SEQUENCE:

CREATE SEQUENCE myseq;

Then you can use the sequence in insert statements like:

INSERT INTO t (id) VALUES ( myseq.NEXTVAL );

Or of course you can create a trigger to set :NEW.id := myseq.NEXTVAL
__________________
Tony Andrews
http://tinyurl.com/tonyandrews
Reply With Quote
  #3 (permalink)  
Old 03-03-03, 13:34
rhs98 rhs98 is offline
Super Moderator
 
Join Date: Feb 2002
Location: Hampshire, UK
Posts: 441
yeah I was just looking squences. Would this be the correct syntax for a trigger???
Code:
CREATE TRIGGER mk_pk BEFORE INSERT ON blah
FOR EACH ROW
BEGIN
:NEW.code_name := myseq.NEXTVAL ;
END;
assuming the trigger was created ok.

also, if i just do
Code:
CREATE SEQUENCE myseq;
what kind of squence will this give me? It doesn't really matter what numbers; but what datatype do the fields in the table (the primary key) need to be? INT?
Reply With Quote
  #4 (permalink)  
Old 03-03-03, 15:24
andrewst andrewst is offline
Moderator.
 
Join Date: Sep 2002
Location: UK
Posts: 5,171
Yes, your trigger is correct.

Sequences always return integer values - by default, starting from 1 and incrementing by 1 (though there may be gaps). You can modify the starting and increment values if you need to. The column in the table should just be a NUMBER, or you can specify NUMBER(size,0) if you like, as long as size is big enough.
__________________
Tony Andrews
http://tinyurl.com/tonyandrews
Reply With Quote
  #5 (permalink)  
Old 03-03-03, 17:13
rhs98 rhs98 is offline
Super Moderator
 
Join Date: Feb 2002
Location: Hampshire, UK
Posts: 441
Thumbs up

I don't mind gaps...the users will just have to cope

Thanks! Will give it all a try in the morning...
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On