【问题标题】:oracle sql dynamic insert statementoracle sql动态插入语句
【发布时间】:2013-07-26 04:48:26
【问题描述】:

我有一个 oracle 函数,该函数有一个参数,该参数定义应该在哪一列中插入值,例如

 function something(p_value, p_nr) 
 is 
   ...
 begin
   if p_nr = 1 then
       insert into A (column1) (p_value);
   else if p_nr = 2 then
       insert into A (column2) (p_value);
   ...
   end if; 

我有几个值要输入到表中,只有这个值应该动态插入。有没有更简单的方法来做到这一点?

【问题讨论】:

    标签: oracle function insert


    【解决方案1】:

    如果你的表结构定义了列的默认值,你也可以考虑条件插入:

    insert all
    when :p_nr = 1 then into A( col1 ) values( p_value )
    when :p_nr = 2 then into A( col2 ) values( p_value )
    when :p_nr = 3 then into A( col3 ) values( p_value )
    select :p_value as p_value from dual
    ;
    

    优点是这个查询尊重默认值,看一个例子:

    create table A(
      col1 varchar2( 10 ) default 'default 1',
      col2 varchar2( 10 ) default 'default 2',
      col3 varchar2( 10 ) default 'default 3'
    );
    
    variable p_nr number
    variable p_value varchar2( 100 )
    
    exec :p_nr:=2
    exec :p_value:='value'
    
    insert into A (col1, col2, col3)
    values (case when :p_nr = 1 then :p_value end,
            case when :p_nr = 2 then :p_value end,
            case when :p_nr = 3 then :p_value end);
    
    select * from A;
    
    COL1       COL2       COL3     
    ---------- ---------- ----------
               value             
    

    和:

    rollback;
    
    insert all
    when :p_nr = 1 then into A( col1 ) values( p_value )
    when :p_nr = 2 then into A( col2 ) values( p_value )
    when :p_nr = 3 then into A( col3 ) values( p_value )
    select :p_value as p_value from dual
    ;
    select * from A;
    
    COL1       COL2       COL3     
    ---------- ---------- ----------
    default 1  value      default 3 
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      insert into A (column1, column2)
      values (case when p_nr = 1 then p_value end,
          case when p_nr = 2 then p_value end);
      

      这会将值放在两列之一中,而将 null 放在另一列中;哪种方式取决于标志值。 (我在这两种情况下都省略了隐含的else null,但使用它的意图可能会更清楚)。

      由于现在是纯 SQL,它甚至可能不需要包装在函数(或过程)中,这取决于您在做什么。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-19
        • 1970-01-01
        相关资源
        最近更新 更多