增加字段,对原有记录的影响

来源:互联网 发布:合肥黑马程序员 编辑:程序博客网 时间:2024/04/27 14:38

前两天看到别人脚本,有个增加字段并且提供默认值的操作发生了变化。以前是分两步写的,这次放在一个语句中,于是就触发了当前表上面的触发器。(表中已经有数据)

 

一个语句:

alter table test_ddl add (add_c1 number(2) default 0);

其实这个语句,不论新增字段是否非空,都会对原有记录进行update,从而触发器被触发。

 

两步执行:

alter table test_ddl add (add_c1 number(2));

alter table test_ddl modify (add_c1 default 0);

这个操作就不会修改原有记录。

 

找了一下文档,只发现了对第一个操作的说明。

 

If you add a column, then the initial value of each row for the new column is null unless you specify the DEFAULT clause. In this case, Oracle Database updates each row in the new column with the value you specify for DEFAULT. This update operation, in turn, fires any AFTER UPDATE triggers defined on the table.

 

而且还有关于修改默认值,会在字典中保留错误信息的提示。

Note:

If a column has a default value, then you can use the DEFAULT clause to change the default to NULL, but you cannot remove the default value completely. That is, if a column has ever had a default value assigned to it, then the DATA_DEFAULT column of the USER_TAB_COLUMNS data dictionary view will always display either a default value or NULL.

 

验证了一下,确实如此。

alter table test_ddl modify (add_c1 default null);

 

SQL> select t.column_name, t.default_length, t.data_default from user_tab_cols t where t.table_name = 'TEST_DDL';
 
COLUMN_NAME                    DEFAULT_LENGTH DATA_DEFAULT
------------------------------ -------------- --------------------------------------------------------------------------------
ID#                                          
VAL                                           
ADD_C1                                      4 null
 
SQL>

 

摆明了是错误信息啊。

 

但是关于modify默认值的说明,没有看到。不知道哪位能够提供一下。