gpt4 book ai didi

java - 如何使用传递的参数等列对oracle select进行排序

转载 作者:行者123 更新时间:2023-11-30 06:34:01 26 4
gpt4 key购买 nike

我在oracle中有一个函数,返回sys_refcursor,它是为 select 打开的。我将参数传递给这个 oracle 函数,并且我将使用等于该参数的列来排序我的选择。在示例中,我的选择中有 10 列,我的参数可能等于它们中的每一个。一个条件是写入 10 if像这样的子句

if myParam = 'name' then

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

还有其他条件可以让我的代码更短吗?

最佳答案

使用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"

关于java - 如何使用传递的参数等列对oracle select进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45510009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com