alter table 添加自增列报错

某用户询问,通过Alter table添加自增列(SERIAL、SERIAL8或BIGSERIAL)时报错,该如何处理?

> alter table t7 add id int;

Table altered.

> alter table t7 add cid serial;

  287: Cannot add serial column (cid) to table.
Error in line 1
Near character position 28
> 

1、首先,不能直接通过alter table语句添加自增列(SERIAL、SERIAL8或BIGSERIAL)到现有表中。因为这些类型的列不能有空值。

2、如果想在现有表中添加自增列,可以通过以下步骤进行处理:

  • 先用alter table语句添加一个 int 列;
  • 然后使用非空唯一值更新该列的每一行;
  • 最后,再用alter table modify将列的数据类型更改为SERIAL、SERIAL8或BIGSERIAL。
[informix@vm84145 ~]$dbaccess testdb -

Database selected.

> alter table t7 add tid int;

Table altered.

> select rowid,* from t7;


      rowid           c1         tid 

        257        0.000            
        258        5.000            
        259        9.000            
        260       14.000            

4 row(s) retrieved.

> update t7 set tid=rowid-256;

4 row(s) updated.

> select rowid,* from t7;


      rowid           c1         tid 

        257        0.000           1
        258        5.000           2
        259        9.000           3
        260       14.000           4

4 row(s) retrieved.

> alter table t7 modify tid serial;

Table altered.

> insert into t7(c1) values (6);

1 row(s) inserted.

> select * from t7;


          c1         tid 

       0.000           1
       5.000           2
       9.000           3
      14.000           4
       6.000           5

5 row(s) retrieved.

>