Add auto increment and auto decrement column in oracle 10g

让人想犯罪 __ 提交于 2019-12-11 07:40:07

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/12384362/add-auto-increment-and-auto-decrement-column-in-oracle-10g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!