繁体   English   中英

Oracle 12c:如何将现有主键列修改为标识列?

[英]Oracle 12c: How can I modify an existing primary key column to an identity column?

我有一个表,其中包含一个主键列,该列从应用程序自动递增。 如何将列修改为Oracle 12c中的标识列

以下提供样本案例 -

create table tmp_identity (
   id number(100) primary key,
   value varchar2(100)
);

假设我们使用以下数据填充表格 -

ID        VALUE
---------------
1         Sample 1
2         Sample 2
3         Sample 3

我们计划做的是将此id列转换为一个标识列 ,该将 -

  • 自动递增1
  • 从4开始

我该怎么做? 如果不可能,那么有没有可用的解决办法?

您不能将现有列转换为真实标识列,但可以通过使用序列作为列的默认值来获得类似的行为。

create sequence seq_tmp_identity_id
  start with 4
  increment by 1;

然后使用:

alter table tmp_identity 
   modify id 
   default seq_tmp_identity_id.nextval;

使列使用序列作为默认值。 如果需要,可以使用default on null来覆盖插入期间提供的显式null值(这与您可以访问标识列一样接近)

如果需要真实标识列,则需要删除当前id列,然后将其重新添加为标识列:

alter table tmp_identity drop column id;

alter table tmp_identity 
     add id number(38) 
     generated always as identity;

请注意,在这种情况下,不应将start with 4添加为start with 4 ,以便所有行都获得一个新的唯一编号

您可以使用以下查询将列从id重命名为identity

ALTER TABLE tmp_identity
RENAME COLUMN id TO identity; 

要自动递增1并从4开始,我们可以使用序列。

CREATE SEQUENCE identity_incre
MINVALUE 4
START WITH 4
INCREMENT BY 1;

在查询中使用identity_incre序列

INSERT INTO suppliers
(identity, VALUE)
VALUES
(identity_incre.NEXTVAL, 'sample4');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM