仅对于新插入为NULL时,将表属性更改为默认值

时间:2018-11-30 05:19:48

标签: oracle oracle11g

在Oracle中,有什么方法可以只为New插入设置NULL时设置Default列值?如果它们有NULL,我不想更改它们。

我想在表级别执行此操作。不适用于NVL插入逻辑。

3 个答案:

答案 0 :(得分:2)

据我所知,如果您更改表并为列设置默认值,它只会影响通过插入插入的 new 记录,而不会影响现有记录。

>
ALTER TABLE yourTable MODIFY (col VARCHAR(100) DEFAULT 'some value');

使用上述方法,至少从插入的角度来看,{em){em> {em} {em} {em} {em} {em} {em} col应该保持NULL {1}}个值。并且未为NULL指定值的新插入的记录应收到默认值NULL

答案 1 :(得分:0)

这是一个演示正在发生的事情的演示。

首先,一个测试表和一些插入物:

SQL> create table test (id number, col varchar2(10));

Table created.

SQL> insert into test (id, col) values (1, null);

1 row created.

SQL> insert into test (id, col) values (2, 'Littlefoot');

1 row created.

SQL> select * from test;

        ID COL
---------- ----------
         1
         2 Littlefoot

更改表,以使新添加的行的COL列包含“某些值”:

SQL> alter table test modify col default 'some value';

Table altered.

好;现在,这个故事的重要部分:请注意以下几点:

SQL> -- this won't work as you wanted, because I explicitly inserted NULL into COL
SQL> insert into test (id, col) values (3, null);

1 row created.

SQL> -- this will work, because COL is omitted from the INSERT statement
SQL> insert into test (id) values (4);

1 row created.

SQL> select * From test;

        ID COL
---------- ----------
         1
         2 Littlefoot
         3
         4 some value

SQL>

看到了吗?如果您明确将NULL放入列中,则不会获得默认值。


但是,如果您使用的是12c(我知道,您不是-只是在说,以供将来参考),还有另一种选择:DEFAULT ON NULL。它是这样的:

SQL> alter table test modify col default on null 'some value';
alter table test modify col default on null 'some value'
*
ERROR at line 1:
ORA-02296: cannot enable (SCOTT.) - null values found

糟糕!如果该列中有NULL,将不起作用。我知道#2您不想修改现有行,但是-在本演示中,我将这样做:

SQL> update test set col = 'x' where col is null;

2 rows updated.

SQL> alter table test modify col default on null 'some value';

Table altered.

好;让我们看看它的行为:我将NULL明确插入列中。在前面的示例中,它没有在其中添加“某些值”,但将其保留为NULL。现在呢?

SQL> insert into test (id, col) values (5, null);

1 row created.

SQL> select * From test;

        ID COL
---------- ----------
         1 x
         2 Littlefoot
         3 x
         4 some value
         5 some value

好;我们在该列中具有“某些价值”。


现在,您有关于此问题的更多信息;看看是否有帮助。

答案 2 :(得分:0)

就像Littlefoot所说的那样,如果您将NULL明确地放在一列中,它将不会获得默认值

如果在插入查询中未为该列提及任何值,则使用DEFAULT。但是,显式NULL会覆盖默认表达式。

对于12c及更高版本,您可以使用DEFAULT ON NULL选项。 对于以前的版本,据我所知,唯一的方法是通过TRIGGER

复制该功能。
CREATE TABLE YOURTABLE (  yourcolumn VARCHAR(100) );


CREATE OR REPLACE TRIGGER trg_mod_yourtabcol BEFORE
     INSERT ON yourtable
     FOR EACH ROW
     WHEN ( new.yourcolumn IS NULL )

BEGIN
     :new.yourcolumn := 'SOME DEFAULT VALUE';
END;
/


INSERT INTO YOURTABLE(yourcolumn) VALUES(NULL);

select * from YOURTABLE;

Table YOURTABLE created.


Trigger TRG_MOD_YOURTABCOL compiled


1 row inserted.


YOURCOLUMN                                                                                          
----------------------------------------------------------------------------------------------------
SOME DEFAULT VALUE

1 row selected.