简体   繁体   English

在oracle 10g中添加自动增量和自动减量列

[英]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. 我想在oracle数据库中添加一个列,该列在插入记录后自动递增。删除记录时应该自动递减。该字段用于存储表标题的序列号,标题应该能够重新生成因此,数字序列之间不应该有任何差距。我尝试过TRIGGER和SEQUENCE但它没有用。有没有办法使用PL / SQL来实现。实际上我想要的是移动序列号删除记录时

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.. 例如:第1行,第2行,第3行,第4行,第5行,如果我们删除第3行,则序列应该是第1行,第2行,第3行,第4行和第4行的记录应该是第3行所以上..

I am using jsp-servlet technology.If there any way to do this by using java that's also good. 我正在使用jsp-servlet技术。如果有任何方法可以通过使用java来做到这一点也很好。

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 . 无论你如何使用序列,它们都不会产生无间隙的数字序列 ,完美的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. 简单地说,如果删除第3行,则需要更新序列号大于3的所有记录。这显然是荒谬的。

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() . 对于那些需要此列的查询,使用分析函数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. 这将按照ORDER BY子句中给出的顺序为每一行分配一个唯一编号。

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. 您也可以将它放在视图中,这样您甚至不需要记住将它放在查询中,并且您确定每次都以完全相同的方式生成它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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