How to set a conditional DEFAULT value to a column

2019-08-01 10:47发布

How to set a conditional DEFAULT value to a column in oracle without using triggers? I want to achieve following needs:

  1. If "flag1"=1 then Default value to column Newfield must be "4".
  2. If "flag1"=2 then Default value to column Newfield must be "5".

4条回答
男人必须洒脱
2楼-- · 2019-08-01 11:17

If 'flag' is something session (or statement) level then SYS_CONTEXT may be a way through. Possibly a BEFORE STATEMENT trigger if the issue is avoiding a context switch for every row inserted

查看更多
对你真心纯属浪费
3楼-- · 2019-08-01 11:19

If column Newfield does not need to be updateable, then you could simply implement it in a view, as Tony showed, or in 11g you could make it a virtual column.

查看更多
劳资没心,怎么记你
4楼-- · 2019-08-01 11:33

That's what triggers are for. Use them.

查看更多
smile是对你的礼貌
5楼-- · 2019-08-01 11:39

A column DEFAULT is not allowed to reference another column, so this is not possible.

You could perhaps just let the default remain as NULL, and then have a view to adjust it like:

create view mytable_view as
select flag1, nvl(newfield, case flag1 when 1 then 4
                                       when 2 then 5
                            end) as newfield
from mytable;
查看更多
登录 后发表回答