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 > Data Access, Manipulation & Batch Languages > ANSI SQL > populating a primary key using a before insert trigger

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 08-22-02, 19:00
hhiggs hhiggs is offline
Registered User
 
Join Date: Jun 2002
Location: Loveland, Colorado
Posts: 1
populating a primary key using a before insert trigger

Hi, I looking for code that will generate sequential values to populate a primary key column. I cannot use a sequence therefore it must be done programatically. There will be continuous inserts and deletes on this table and I want to be able to start the id column with 1 every time the table has been truncated. Any help would be greatly appreciated.
Reply With Quote
  #2 (permalink)  
Old 08-27-02, 07:18
Roelwe Roelwe is offline
Registered User
 
Join Date: Aug 2002
Location: Belgium
Posts: 534
Why don't u use something like

insert into tab1 values max(old.id) + 1

This one will work very fast if you have an index on the id column.
__________________
rws
Reply With Quote
  #3 (permalink)  
Old 08-29-02, 12:31
DavidLGraham DavidLGraham is offline
Registered User
 
Join Date: Aug 2002
Location: Monterey, CA
Posts: 2
Re: populating a primary key using a before insert trigger

select id + 1
into v_id
from table
where id = (select max(id)
from table)
for update;
insert into table (id) values (v_id);

the select locks the table so no other user gets the same value.
the insert and subsequent commit releases the lock.

If you are doing 8.1.6 or higher you can use an anonymous transaction.



Quote:
Originally posted by hhiggs
Hi, I looking for code that will generate sequential values to populate a primary key column. I cannot use a sequence therefore it must be done programatically. There will be continuous inserts and deletes on this table and I want to be able to start the id column with 1 every time the table has been truncated. Any help would be greatly appreciated.
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