2017-08-04 40 views
1

我在oracle中有函數,返回sys_refcursor,這個函數打開select。我將參數傳遞給這個oracle函數,我將命令我的選擇與這個參數相等的列。例如我在我的選擇中有10列,我的參數可能是等於他們每一個。一個條件是寫10 if像這樣的子句如何訂購oracle select與傳遞的參數等於列

if myParam = 'name' then 

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

是否還有其他條件可以更快地進行我的代碼?

回答

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"