如何使用传递的参数等于列

时间:2017-08-04 15:00:27

标签: java oracle

我在oracle中有函数,返回sys_refcursor,为select打开。我将参数传递给这个oracle函数,我将使用等于此参数的列来命令我的select。在示例中,我的select中有10列,我的参数可能等于每个。一个条件是写入10像这样的条款

if myParam = 'name' then

select <selected rows>
from table a 
order by a.name
end if;

还有其他条件要更快我的代码吗?

1 个答案:

答案 0 :(得分:1)

使用OPEN cursor FOR dynamic_query

CREATE OR REPLACE FUNCTION my_fun( ord VARCHAR2 )
RETURN sys_refcursor
IS
   refcur SYS_REFCURSOR;
BEGIN
    OPEN refcur FOR 
        'SELECT level as x, 100-level as y  FROM dual
        CONNECT BY LEVEL <= 10
        ORDER BY ' || ord;
    RETURN refcur;
END;
/

现在:

 VAR x REFCURSOR;
 exec :x := my_fun( 'x' );
 print :x;

         X          Y
---------- ----------
         1         99
         2         98
         3         97
         4         96
         5         95
         6         94
         7         93
         8         92
         9         91
        10         90

10 rows selected.
exec :x := my_fun( 'y' );
 print :x;

         X          Y
---------- ----------
        10         90
         9         91
         8         92
         7         93
         6         94
         5         95
         4         96
         3         97
         2         98
         1         99

10 rows selected.
exec :x := my_fun( 'z' );
 print :x;

ORA-00904: "Z": invalid identifier
ORA-06512: "TEST.MY_FUN", line 7
ORA-06512: line 1
00904. 00000 -  "%s: invalid identifier"