首页 > 解决方案 > DB2(v10.5.0.5) 如何将自增列添加到已存在的表中

问题描述

我正在尝试在现有表中添加一个自动增量列DB2

DB2 版本是v10.5.0.5.

以下是我的查询:

alter table DB2INST1.AAA_BJ_BOND 
ADD COLUMN id INTEGER NOT NULL DEFAULT 0;

ALTER TABLE DB2INST1.AAA_BJ_BOND ALTER COLUMN id 
set generated always as identity (start with 1);

但我收到以下错误:

"com.ibm.db2.jcc.am.SqlSyntaxErrorException: ALTER TABLE "DB2INST1.AAA_BJ_BOND" 
specified attributes for column "ID" that are not compatible with the existing 
column.. SQLCODE=-190, SQLSTATE=42837, DRIVER=4.13.127"

我能做些什么来解决这个问题?

标签: sqldb2

解决方案


您必须先删除列 DEFAULT 值。这在SQL0190N的描述中提到:

如果指定了 SET GENERATED ALWAYS AS (expression),但该列已经定义了一种生成形式(默认、标识或表达式),并且在同一语句中没有相应的 DROP。

ALTER TABLE DB2INST1.AAA_BJ_BOND 
ALTER COLUMN id drop default;

ALTER TABLE DB2INST1.AAA_BJ_BOND ALTER COLUMN id 
set generated always as identity (start with 1);

推荐阅读