Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 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 Reply

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...