How to set a conditional DEFAULT value to a column in oracle without using triggers?

被刻印的时光 ゝ 提交于 2019-12-13 18:07:15

问题


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".

回答1:


That's what triggers are for. Use them.




回答2:


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;



回答3:


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:


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



来源:https://stackoverflow.com/questions/6857715/how-to-set-a-conditional-default-value-to-a-column-in-oracle-without-using-trigg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!