简体   繁体   中英

Add auto increment and auto decrement column in oracle 10g

I would like to add a column to oracle database which increment automatically after inserting a record.And it should be decrement automatically when deleting a record.This field is used for store a sequence number of a table headings and that headings should be able to re-order therefore there shouldn't have any gaps between number sequence.I have tried with TRIGGER and SEQUENCE but it didn't work.Are there any way to use PL/SQL to this.Actually what I want is to shift the sequence numbers when deleting a record.

eg:row 1,row 2,row 3,row 4,row 5 if we delete row 3, the sequence should be row 1,row 2,row 3,row 4 and record which was at row4 should come to row 3 and so on..

I am using jsp-servlet technology.If there any way to do this by using java that's also good.

Thank you!

No; there is no easy way.

Whatever you do with sequences they'll never generate a gap free sequence of numbers , a perfect 1, 2 .. n . Even if they did there's no way of automatically re-generating a sequence for an entire table, or set of rows within a table, without re-generating it from scratch. Simply put if you delete row 3, you need to update all records with a sequence number higher than 3. This is obviously ridiculous.

I do not see why you want to do this, however, assuming you do my "answer" would be to not store this information in your table at all. For those queries that require this column generate it on the fly using the analytic function row_number() . For instance:

select column1, column2, row_number() over ( order by <whatever> ) as my_sequence
  from my_table

This assigns a unique number to each row in the order given in the ORDER BY clause.

You could also put this in a view so you don't even need to remember to put it in the query and you're certain that it's been generated in the exact same manner each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM