Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

sql - How to add a sequence column to an existing table with records

I had created a new table named USERLOG with two fields from a previous VIEW. The table already consist of about 9000 records. The two fields taken from the VIEW, i.e. weblog_views consist of IP (consists of IP address), and WEB_LINK (consists of URL). This is the code I used,

    CREATE TABLE USERLOG
    AS
    SELECT C_IP, WEB_LINK FROM weblog_views;

I want to add another column to this table called the USER_ID, which would consists of a sequence starting with 1 to 9000 records to create a unique id for each existing rows. I need help with this part. I'm using Oracle SQL Developer: ODMiner version 3.0.04. I tried using the AUTO-INCREMENT option,

    ALTER TABLE USERLOG
    ADD USER_ID INT UNSIGNED NOT NULL AUTO_INCREMENT;

But I get an error with this,

    Error report:
    SQL Error: ORA-01735: invalid ALTER TABLE option
    01735. 00000 -  "invalid ALTER TABLE option"

So, I would really appreciate any help that I can get!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You would need to add a column

ALTER TABLE userlog
  ADD( user_id number );

create a sequence

CREATE SEQUENCE user_id_seq
  START WITH 1
  INCREMENT BY 1
  CACHE 20;

Update the data in the table

UPDATE userlog
   SET user_id = user_id_seq.nextval

Assuming that you want user_id to be the primary key, you would then add the primary key constraint

ALTER TABLE userlog
  ADD CONSTRAINT pk_user_id PRIMARY KEY( user_id );

If you want to use the sequence to automatically add the user_id when you do an INSERT (the other option would be to specifically reference user_id_seq.nextval in your INSERT statements, you would also need a trigger

CREATE OR REPLACE TRIGGER trg_userlog_user_id
  BEFORE INSERT ON userlog
  FOR EACH ROW
BEGIN
  :new.user_id := user_id_seq.nextval;
END;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...