简体   繁体   中英

How to update oracle list column with sequence number

Hi I have the oracle data table like that

seq_no name place
1 Rian Us
1 Moli Us
1 Molina Us

and i want to update automaticly the seq_no to be like that

seq_no name place
1 Rian Us
2 Moli Us
3 Molina Us

If you have a table:

CREATE TABLE table_name (seq_no, name, place) AS
SELECT 1, 'Rian',   'Us' FROM DUAL UNION ALL
SELECT 1, 'Moli',   'Us' FROM DUAL UNION ALL
SELECT 1, 'Molina', 'Us' FROM DUAL;

and a sequence:

CREATE SEQUENCE your_sequence;

Then you can update the existing rows to the sequence values using:

UPDATE table_name
SET seq_no = your_sequence.NEXTVAL;

Then the table would contain:

SEQ_NO NAME PLACE
1 Rian Us
2 Moli Us
3 Molina Us

Then when you want to INSERT more rows, you can use:

INSERT INTO table_name (seq_no, name, place)
VALUES (your_sequence.NEXTVAL, 'New Name', 'New Place');

and the row:

SEQ_NO NAME PLACE
4 New Name New Place

Would be added with the next sequence number.

Alternatively, you could write a trigger to get the next sequence number or, from Oracle 12, use an IDENTITY column.

db<>fiddle here

What does "automatically" mean?

You could have created table so that SEQ_NO is automatically populated by a database trigger (can't use an identity column as you're on 11g).

Or, if you want to update the table, a simple option is

update your_table set seq_no = rownum;

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