i need to create a procedure that take as a parameter a query and the result of that query should be exported in a csv file but i can't find a solution, can you help me please?
As you're passing any query to a stored procedure (though, I'd rather suggest a function), you can't know which columns will be involved so that you could "prepare" local variables or something like that. Certainly, what comes in mind is ref cursor that's being returned from the function I previously mentioned.
Here's an example; see if it helps.
Function; par_query
is a query you'll pass as function's parameter. It (the function) then returns ref cursor.
SQL> create or replace function f_test (par_query in varchar2)
2 return sys_refcursor
3 is
4 rc sys_refcursor;
5 begin
6 open rc for par_query;
7 return rc;
8 end;
9 /
Function created.
Let's test it:
SQL> var l_rc refcursor
SQL> begin
2 :l_rc := f_test('select d.dname, e.ename, e.job, e.sal from emp e join dept d ' ||
3 'on e.deptno = d.deptno where d.deptno = 10 ' ||
4 'order by d.deptno, e.ename');
5 end;
6 /
PL/SQL procedure successfully completed.
l_rc
now contains result of the query that was passed to the function. Let's store it into the file. How? Spool, File will be stored on your own PC (therefore. you don't have to have access to the database server).
SQL> spool test.txt
SQL> print l_rc
DNAME ENAME JOB SAL
-------------- ---------- --------- ----------
ACCOUNTING CLARK MANAGER 2450
ACCOUNTING KING PRESIDENT 5000
ACCOUNTING MILLER CLERK 1300
SQL> spool off
That's it. What's the file contents?
SQL> $type test.txt
SQL> print l_rc
DNAME ENAME JOB SAL
-------------- ---------- --------- ----------
ACCOUNTING CLARK MANAGER 2450
ACCOUNTING KING PRESIDENT 5000
ACCOUNTING MILLER CLERK 1300
SQL> spool off
Kind of works . Make it pretty if you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.