针对已有的列,如何修改为非空,并且指定默认值?
熟悉Oracle的DBA都知道,如果在将列从可空修改为非空时,必须确保已有的列不含有空值,如:
SQL> create table tab01(id integer,name varchar(100),city varchar(100));
Table created.
SQL> insert into tab01(id) values(1);
1 row created.
SQL> commit;
Commit complete.
SQL> alter table tab01 modify city default 'FUZHOU' not null;
alter table tab01 modify city default 'FUZHOU' not null
*
ERROR at line 1:
ORA-02296: cannot enable (SYS.) - null values found
KingbaseES 同样也不允许将含有空值的列改为非空,如:
test=# ALTER TABLE tab01 alter column city set default 'Fuzhou', alter column city set not null ;
错误: 字段 "city" 包含空值
那如何修改已有的列为非空?只能手动将已有为空的数据先进行update,再进行alter table操作。
KingbaseES 还提供 using 选项,用于将列已有的数据修改为指定的值。
注意:不管已有数据的列是否为空,所有数据都会被修改。如:
test=# update tab01 set city='ABC' WHERE id=123;
UPDATE 1
test=# ALTER TABLE tab01
test-# alter column city set default 'Fuzhou',
test-# alter column city set not null,
test-# alter column city set data type varchar(100) using ('Fuzhou');
ALTER TABLE
test=# \d tab01
数据表 "public.tab01"
栏位 | 类型 | 校对规则 | 可空的 | 预设
------+-----------------------------+----------+----------+-------------------
id | integer | | |
name | character varying(100 char) | | |
city | character varying(100 char) | | not null | 'Fuzhou'::varchar
索引:
"idx_tab01_city" btree (city)
test=# select * from tab01 where city='ABC';
id | name | city
----+------+------
(0 行记录)
在使用该命令时,务必注意,避免修改了已有记录,导致数据丢失。