有时事情就像你希望的那样简单。
首先,一个有默认值的表……
SQL> create table t23 (
2 id number not null primary key
3 , col_d date default sysdate not null )
4 /
Table created.
SQL> insert into t23 values (1, trunc(sysdate, 'yyyy'))
2 /
1 row created.
SQL> select * from t23
2 /
ID COL_D
---------- ---------
1 01-JAN-10
SQL>
接下来是更新默认列的过程...
SQL> create or replace procedure set_t23_date
2 ( p_id in t23.id%type
3 , p_date in t23.col_d%type )
4 is
5 begin
6 update t23
7 set col_d = p_date
8 where id = p_id;
9 end;
10 /
Procedure created.
SQL>
...但它并没有像我们想要的那样工作:
SQL> exec set_t23_date ( 1, null )
BEGIN set_t23_date ( 1, null ); END;
*
ERROR at line 1:
ORA-01407: cannot update ("APC"."T23"."COL_D") to NULL
ORA-06512: at "APC.SET_T23_DATE", line 6
ORA-06512: at line 1
SQL>
所以,让我们尝试添加一个 DEFAULT 选项...
SQL> create or replace procedure set_t23_date
2 ( p_id in t23.id%type
3 , p_date in t23.col_d%type )
4 is
5 begin
6 if p_date is not null then
7 update t23
8 set col_d = p_date
9 where id = p_id;
10 else
11 update t23
12 set col_d = default
13 where id = p_id;
14 end if;
15 end;
16 /
Procedure created.
SQL>
...瞧!
SQL> exec set_t23_date ( 1, null )
PL/SQL procedure successfully completed.
SQL>
SQL> select * from t23
2 /
ID COL_D
---------- ---------
1 28-FEB-10
SQL>
我在 11g 数据库上运行了这个示例。我不记得 Oracle 何时引入了对 DEFAULT 的确切支持,但已经有一段时间了(9i ???)
编辑
cmets 真的很郁闷。构建 PL/SQL API 的全部目的是让应用程序开发人员更容易与数据库交互。这包括在必要时足够明智地重写存储过程。使用软件构建某些东西与将铸铁大梁焊接在一起之间的最大区别在于,软件具有延展性并且易于更改。特别是当更改不会改变现有过程的签名或行为时,就是这种情况。