将查询语句[insert,update]传递给函数作为参数并执行它

时间:2013-04-08 09:35:56

标签: oracle oracle10g oracle11g

如果我想将insert语句作为参数传递给此函数并在函数中执行并返回值

,我该怎么办?
create or replace function new_record (p_name your_table.first_name%type)
    return your_table.id%type
is
    return_value your_table.id%type;
begin
    begin
        insert into your_table (id, first_name)
            values (your_seq.nextval, p_first_name)
        returning id into return_value;
    exception
        when dup_val_on_index then
             return_value := 0;
    end;
    return return_value;
end;

1 个答案:

答案 0 :(得分:1)

使用“execute immediate”声明:

这是一个简单的例子,只需执行这个sql,你就会看到它是如何工作的:

declare
  p_param   number := 123;
  l_res varchar2(10);
  l_sqltext varchar(100);
begin
  l_sqltext := 'begin select t.dummy into :1 from dual t where 123 = :2; end;';
  execute immediate l_sqltext using out l_res, in p_param;
  dbms_output.put_line(l_res);
end;