[英]Add new column with default value, not for existing rows
alter table report add favourite_film VARCHAR2(100) DEFAULT 'Star Wars';
This adds a new column with default value, but it appears to me it also sets the default value on all pre-existing rows rather than leaving them null which is my preference. 这将添加一个具有默认值的新列,但在我看来,它还在所有现有行上设置了默认值,而不是将它们保留为空(这是我的偏爱)。 We want to add a new column with a default value for convenience, but rows before this column was added should have a null value.
为了方便起见,我们希望添加一个具有默认值的新列,但是添加此列之前的行应具有空值。
Is there a better way to do this than simply setting the value of all rows to null
immediately after adding the new column? 除了将所有行的
null
在添加新列后立即立即设置为null
之外,还有更好的方法吗?
Try doing something like: 尝试做类似的事情:
SQL> create table testtab
(
id number,
col1 varchar2(10)
)
Table created.
SQL> insert into testtab(id, col1) values (1,'TEST1')
1 row created.
SQL> insert into testtab(id, col1) values (2,'TEST2')
1 row created.
SQL> commit
Commit complete.
SQL> alter table testtab add col2 varchar2(10)
Table altered.
SQL> alter table testtab modify col2 default 'DEFAULT'
Table altered.
SQL> select * from testtab
ID COL1 COL2
---------- ---------- ----------
1 TEST1
2 TEST2
2 rows selected.
SQL> insert into testtab(id, col1) values (3,'TEST3')
1 row created.
SQL> select * from testtab
ID COL1 COL2
---------- ---------- ----------
1 TEST1
2 TEST2
3 TEST3 DEFAULT
3 rows selected.
Note that per the Oracle docs , if you use the add column clause of alter table command, it will add the specified default value to existing rows: 请注意,根据Oracle文档 ,如果您使用alter table命令的add column子句,它将为现有行添加指定的默认值:
If you specify the DEFAULT clause for a nullable column, then the default value is added to existing rows as part of this ALTER TABLE statement, and any update triggers defined on the table are fired.
如果为可为空的列指定DEFAULT子句,则默认值将作为此ALTER TABLE语句的一部分添加到现有行中,并且会触发表上定义的所有更新触发器。 This behavior also results if you change a NOT NULL column with a default value to be nullable.
如果将具有默认值的NOT NULL列更改为可为空,也会导致此行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.