我尝试按照Tony Andrews example实现表函数。但我的Sql语句将是几行(> 20)并且还将包含参数。是否可以在其他地方封装Sql语句并从main函数引用它以使所有内容更具可读性?
在传统的编程语言中,我会将原始Sql分配给一个字符串,并根据需要替换参数。
答案 0 :(得分:3)
是的,你可以:
--declare variables
TYPE curref is REF CURSOR;
c1 curref;
q VARCHAR2(2000);
--save query to string variable
q:='<insert 20 line query here>';
--open cursor
OPEN c1 FOR q;
--then, work on cursor rows, one by one
请注意,'q'可能非常复杂,具有连接的参数值(或可以作为单独的varchar变量存储的子查询):
q:='
select distinct
fn.BASENAME as name
,h.PARENT_ID as "admin_place_id"
,h.lev as "admin_level"
FROM (
SELECT CHILD_ID, PARENT_ID, level lev
from '||schema||'.NT_ADMIN_GRAPH
START WITH CHILD_ID='||q_sub2||'
CONNECT BY CHILD_ID=PRIOR PARENT_ID
UNION ALL
SELECT null, '||q_sub2||', 0
FROM DUAL
) h
'
||q_sub||
'
ORDER BY h.lev asc
';
有关如何实现此目的的更多示例,请参阅Oracle's documentation。
答案 1 :(得分:1)
受drapkin11启发我found使用游标的解决方案:
CREATE OR REPLACE Function TotalIncome( name_in IN varchar2 )
RETURN varchar2
IS
total_val number(6);
cursor c1 is
select monthly_income
from employees
where name = name_in;
BEGIN
total_val := 0;
FOR employee_rec in c1
LOOP
total_val := total_val + employee_rec.monthly_income;
END LOOP;
RETURN total_val;
END;