72

我想将一个新的自动增量主列添加到具有数据的现有表中。我怎么做?

我首先添加了一个列,然后尝试添加一个序列,我失去了如何插入该列并将该列作为主键。

4

4 回答 4

52

假设你的表被调用t1并且你的主键被调用id
首先,创建序列:

create sequence t1_seq start with 1 increment by 1 nomaxvalue; 

然后创建一个在插入时递增的触发器:

create trigger t1_trigger
before insert on t1
for each row
   begin
     select t1_seq.nextval into :new.id from dual;
   end;
于 2012-07-13T05:11:29.813 回答
32

如果您有列和序列,则首先需要为所有现有行填充一个新键。假设您不在乎哪个键分配给哪一行

UPDATE table_name
   SET new_pk_column = sequence_name.nextval;

完成后,您可以创建主键约束(这假设没有现有的主键约束或者您已经删除了现有的主键约束)

ALTER TABLE table_name
  ADD CONSTRAINT pk_table_name PRIMARY KEY( new_pk_column )

如果要自动生成密钥,则需要添加触发器

CREATE TRIGGER trigger_name
  BEFORE INSERT ON table_name
  FOR EACH ROW
BEGIN
  :new.new_pk_column := sequence_name.nextval;
END;

如果您使用的是旧版本的 Oracle,则语法会比较麻烦

CREATE TRIGGER trigger_name
  BEFORE INSERT ON table_name
  FOR EACH ROW
BEGIN
  SELECT sequence_name.nextval
    INTO :new.new_pk_column
    FROM dual;
END;
于 2012-07-13T05:09:55.930 回答
19

来自Oracle OTN 论坛

使用 alter table 添加列,例如:

alter table tableName add(columnName NUMBER);

然后创建一个序列:

CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;

并且,用于update在这样的列中插入值

UPDATE tableName SET columnName = seq_test_id.NEXTVAL
于 2012-07-13T05:10:23.563 回答
5

You can use the Oracle Data Modeler to create auto incrementing surrogate keys.

Step 1. - Create a Relational Diagram

You can first create a Logical Diagram and Engineer to create the Relational Diagram or you can straightaway create the Relational Diagram.

Add the entity (table) that required to have auto incremented PK, select the type of the PK as Integer.

Step 2. - Edit PK Column Property

Get the properties of the PK column. You can double click the name of the column or click on the 'Properties' button.

Column Properties dialog box appears.

Select the General Tab (Default Selection for the first time). Then select both the 'Auto Increment' and 'Identity Column' check boxes.

Step 3. - Additional Information

Additional information relating to the auto increment can be specified by selecting the 'Auto Increment' tab.

  • Start With
  • Increment By
  • Min Value
  • Max Value
  • Cycle
  • Disable Cache
  • Order
  • Sequence Name
  • Trigger Name
  • Generate Trigger

It is usually a good idea to mention the sequence name, so that it will be useful in PL/SQL.

Click OK (Apply) to the Column Properties dialog box.

Click OK (Apply) to the Table Properties dialog box.

Table appears in the Relational Diagram.

于 2013-04-04T03:33:29.357 回答