如何使用EXECUTE IMMEDIATE获取记录?

时间:2022-09-08 22:38:18

I have a bunch of functions with signatures like:

我有一堆带有签名的函数,例如:

FUNCTION func1 (par1 IN VARCHAR2, par2 IN NUMBER) RETURN my_rec;  

and I have a function for retrieving data from this bunch of functions:

我有一个从这一系列函数中检索数据的函数:

FUNCTION get_result (func_name IN VARCHAR2, par1 IN VARCHAR2, par2 IN NUMBER) RETURN my_rec;
IS
    rec1 my_rec;
BEGIN
    EXECUTE IMMEDIATE 'SELECT ' || func_name || '(:par1, :par2) FROM DUAL'
    INTO rec1
    USING IN par1, IN par2;

    RETURN rec1;
END;

but this code fails with ORA-01007 'variable not in select list'.
How can I rewrite statement?

但是这个代码失败,ORA-01007'变量不在选择列表中'。我怎样才能重写声明?

2 个解决方案

#1


It all works fine for me (Oracle 10G), one I correct the syntax error in your function definition (the unwanted semi-colon on the first line):

这一切对我来说都很好(Oracle 10G),我纠正了函数定义中的语法错误(第一行不需要的分号):

SQL> create type my_rec is object (id integer, name varchar2(30))
  2  /

Type created.

SQL> create FUNCTION func1 (par1 IN VARCHAR2, par2 IN NUMBER) RETURN my_rec
  2  is
  3    l_rec my_rec := my_rec (1, 'x');
  4  begin
  5     return l_rec;
  6  end;
  7  /


Function created.

SQL> CREATE OR REPLACE
  2  FUNCTION get_result (func_name IN VARCHAR2, par1 IN VARCHAR2, par2 IN NUMBER) RETURN my_rec
  3  IS
  4      rec1 my_rec;
  5  BEGIN
  6      EXECUTE IMMEDIATE 'SELECT ' || func_name || '(:par1, :par2) FROM DUAL'
  7      INTO rec1
  8      USING IN par1, IN par2;
  9      RETURN rec1;
 10  END;
 11  /

Function created.

SQL> select get_result ('func1',1,2) from dual;

GET_RESULT('FUNC1',1,2)(ID, NAME)
-------------------------------------------------
MY_REC(1, 'x')

#2


I think you can concatenate to the query like you did with func_name.

我认为您可以像使用func_name一样连接到查询。

#1


It all works fine for me (Oracle 10G), one I correct the syntax error in your function definition (the unwanted semi-colon on the first line):

这一切对我来说都很好(Oracle 10G),我纠正了函数定义中的语法错误(第一行不需要的分号):

SQL> create type my_rec is object (id integer, name varchar2(30))
  2  /

Type created.

SQL> create FUNCTION func1 (par1 IN VARCHAR2, par2 IN NUMBER) RETURN my_rec
  2  is
  3    l_rec my_rec := my_rec (1, 'x');
  4  begin
  5     return l_rec;
  6  end;
  7  /


Function created.

SQL> CREATE OR REPLACE
  2  FUNCTION get_result (func_name IN VARCHAR2, par1 IN VARCHAR2, par2 IN NUMBER) RETURN my_rec
  3  IS
  4      rec1 my_rec;
  5  BEGIN
  6      EXECUTE IMMEDIATE 'SELECT ' || func_name || '(:par1, :par2) FROM DUAL'
  7      INTO rec1
  8      USING IN par1, IN par2;
  9      RETURN rec1;
 10  END;
 11  /

Function created.

SQL> select get_result ('func1',1,2) from dual;

GET_RESULT('FUNC1',1,2)(ID, NAME)
-------------------------------------------------
MY_REC(1, 'x')

#2


I think you can concatenate to the query like you did with func_name.

我认为您可以像使用func_name一样连接到查询。