【问题标题】:Oracle 12c: How can I modify an existing primary key column to an identity column?Oracle 12c:如何将现有的主键列修改为标识列?
【发布时间】:2016-01-03 18:29:57
【问题描述】:

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

下面提供了一个示例案例-

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开始

我该怎么做? 如果不可能,那么是否有任何解决方法可以解决这个问题?

【问题讨论】:

  • id number(100) 列真的有精度 100 吗?在 Oracle 上,精度可以从 1 到 38,仅此而已。

标签: sql oracle oracle12c


【解决方案1】:

您可以使用以下查询将列从 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');

【讨论】:

  • 将列重命名为 identity 不会使其成为“身份”列:
  • 重命名表与标识列到底有什么关系?
【解决方案2】:

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

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,以便所有行都获得一个新的唯一编号

【讨论】:

  • 通过修复,我的意思是摆脱这个解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 2016-04-11
  • 2013-03-17
相关资源
最近更新 更多