如何将序列列添加到包含记录的现有表中 [英] How to add a sequence column to an existing table with records
问题描述
我创建了一个名为 USERLOG 的新表,其中包含来自先前 VIEW 的两个字段.该表已经包含大约 9000 条记录.取自VIEW的两个字段,即weblog_views由IP(由IP地址组成)和WEB_LINK(由URL组成)组成.这是我使用的代码,
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;
我想向该表中添加另一列名为 USER_ID 的列,该列由以 1 到 9000 条记录开头的序列组成,以便为每个现有行创建唯一 ID.我需要这部分的帮助.我使用的是 Oracle SQL Developer:ODMiner 3.0.04 版.我尝试使用 AUTO-INCREMENT 选项,
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!
推荐答案
您需要添加一列
ALTER TABLE userlog
ADD( user_id number );
创建序列
CREATE SEQUENCE user_id_seq
START WITH 1
INCREMENT BY 1
CACHE 20;
更新表中的数据
UPDATE userlog
SET user_id = user_id_seq.nextval
假设您希望 user_id
作为主键,那么您将添加主键约束
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 );
如果您想在执行 INSERT
时使用序列自动添加 user_id
(另一种选择是专门引用 user_id_seq.nextval
在您的 INSERT
语句中,您还需要一个触发器
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;
这篇关于如何将序列列添加到包含记录的现有表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!