Using WITH FUNCTION in Oracle FOR LOOP CURSOR - oracle

I'm using Oracle Database 19c Enterprise Edition.
For various reasons, our core database devs write almost everything using procedures and not functions.
I thought it would be fun to wrap a procedure or two into a function that returns the one or two data items we need in our SQL.
Instead of creating a regular function like a normal person would do, I found that I could declare functions using the WITH statement right in my SQL.
This works great as I'll show in my first example below, but when I try to use it in a FOR LOOP cursor it gives me an ORA-06550 error (missing keyword) right after the WITH keyword.
Working SQL
with
function foobar(in_txt1 varchar2, in_txt2 varchar2) return varchar2 as
begin
return in_txt1 || in_txt2;
end foobar;
select foobar('foo','bar') mytxt from dual;
Broken SQL
begin
for cur in (
with
function foobar(in_txt1 varchar2, in_txt2 varchar2) return varchar2 as
begin
return in_txt1 || in_txt2;
end foobar;
select foobar('foo','bar') mytxt from dual
)
loop
dbms_ouput.put_line(cur.mytxt);
end loop;
end;
Oracle SQL Developer doesn't seem show any errors before I run the code. Does anyone know how to get this to work?
Yes, I know that I could just run the procedure inside the loop, but this is more for a learning experience rather than production code.
Edit: It works if I use dynamic SQL, but that's not something I like to use. I think this just isn't supported at this time. I'll close this question if others agree this can't be done yet.
Thanks!

Related

Oracle 11g - sys_refcursor

I am working on a system where Oracle 11g is the back end database.
I have very limited permissions on the database and as such all I can do is call procedures that reside in packages.
Gerally, these procedure return their result set via an OUT parameter of type sys_refcursor.
I can call them fine in C# and get data from the cursor via the C# OracleDataset type.
Here is my question.
I want to be able to run these procedures and see the results via SQL Developer.
I can execute the procedure fine, but seeing the contents of the sys_refcursor OUT parameter is boggling me.
I've done some gooling and people ar saying about creating type and other solutions I simply do not have the permissions to persue.
So, how can I possibly see the result set contained in a sys_refcursor?
So say I have a procedure with this signature....
procedure an_oracle_Proc(p_ref IN varchar2,
p_result_set OUT sys_refcursor);
I call it like this....
DECLARE
l_ref VARCHAR2(10);
l_result_set sys_refcursor;
BEGIN
oracle_pkg.an_oracle_Proc(p_ref => l_ref,
p_result_set => l_result_set);
--How to select from l_result_set with limited permissions
END
How can I look at the contents of l_result_Set?
This is repeating the answer I linked to before really but specifically for your code:
VARIABLE result_set refcursor;
DECLARE
l_ref VARCHAR2(10);
BEGIN
l_ref := 'whatever';
oracle_pkg.an_oracle_Proc(p_ref => l_ref,
p_result_set => :result_set);
END;
/
PRINT result_set
... and run all of that as a script from an SQL Worksheet. The contents of the ref cursor will be shown in the script output window.
Thought I'd have another look and found this - amazing what stepping away from the computer can do. ;)
I just have to select the appropriate variable on the left pane.
http://www.thatjeffsmith.com/archive/2011/12/sql-developer-tip-viewing-refcursor-output/
Still - it would be nice to write my own SQL to do this rather than using the execute window.
Sys_refcursor form an anonymous block is bit tricky. Use the sql-developer, explore the package or procedure , right click and execute the procedure/package.
Sql-developer will open an input/output UI where you can key in values. And you can see the output on the same UI as well. Let me know if you need more details. I was actually debugging the same a couple of weeks back successfully.

Call Oracle stored procedure with no arguments

I'm trying to call an Oracle stored procedure that accepts no input parameters. However, when running the procedure, I get an error back that states
PLS-00306: wrong number or types of arguments in call to 'MY_PROC'
To call the proc, I'm just entering the following text into TOra:
BEGIN
SCHEMA.MY_PROC();
END;
I've also tried (same error though)
EXEC SCHEMA.MY_PROC();
I'm familiar with MSSQL and I'm able to execute SP with no problem using SQL server, but I can't figure out how to do the same with Oracle. I can't view the actual code for the stored procedure, but from the limited documentation I have, it appears it accepts no input parameters and the return value is a ref cursor. I have a feeling that I need to pass in a ref cursor somehow, but everything I've tried in that regard has not worked.
I just want to view the results of the SP as if I had done a SELECT statement, that is, with the records populating the data grid in the results panel in the TOra interface.
It sounds like the procedure does have an OUT parameter (in Oracle, procedures do not return anything but can have OUT and IN OUT parameters, functions return something). So you would have to pass in a variable for that OUT parameter. Something like
DECLARE
l_results SYS_REFCURSOR;
BEGIN
schema.my_proc( l_results );
END;
should successfully call the procedure. But then you want your GUI to display the results from that cursor. That, unfortunately, gets a little more complicated because now you're talking about a GUI-specific issue.
I don't use TOra, so I don't know what you need to do in TOra to get the cursor to display. In SQL*Plus (or SQL Developer, Oracle's free GUI), you could do something like
create or replace procedure my_proc( p_rc OUT SYS_REFCURSOR )
as
begin
open p_rc
for select 1 col1
from dual;
end;
/
variable rc refcursor;
exec my_proc( :rc );
print rc;
This creates a stored procedure with an OUT parameter that is a cursor, declares a host variable that can be passed in, and then prints the results.

Calling Oracle package procedures which return ref cursors in straight PL/SQL

I've got an Oracle 10g database which is accessed from an ASP.NET application. Although I've used SQL Server heavily in many different aspects and Oracle for querying and reporting, this is my first time using Oracle as the OLTP database for an application.
The database-level procedures in the packages are typically of the form:
-- TYPE refcur IS REF CURSOR;
PROCEDURE get_some_stuff(o_cursor OUT refcur, p_param1 IN INTEGER, p_param2 IN INTEGER) IS
BEGIN
OPEN o_cursor FOR
SELECT whatever
FROM whatever
END
I assume these are done this way for the benefit of the ADO.NET layer able to use the cursor from the output param and it is my understanding that this is the acceptable best practice for calling Oracle procs from .NET.
In SQL Server, for example, we don't have explicit ref cursors, if a proc returns a result set (or several result sets), that's accessible as an output result set in both ADO.NET and SSMS, and you can simply test the SPs by doing EXEC spname param1, param2.
The problem I'm having is that I don't know how to call these directly in SQL in Toad, for example, to be able to test changes at the PL/SQL level first before going to the app. I'm very used to being able to exercise and even re-mix stored procs and functions in SQL Server to be able to refactor the database interface layer without affecting the external interface to application-level code.
look at the link that OMG Ponies posted, but what you can do is
var x refcursor;
declare
PROCEDURE GET_SOME_STUFF(O_CURSOR OUT SYS_REFCURSOR, P_PARAM1 IN NUMBER, P_PARAM2 IN NUMBER) IS
BEGIN
OPEN O_CURSOR FOR
SELECT LEVEL, p_param1 ,P_PARAM2 FROM DUAL CONNECT BY LEVEL < 3;
END ;
BEGIN
GET_SOME_STUFF(:x , 5, 10);
END;
/
PRINT X;
you pretty much just wrap it in a anonymous block ad it will run. I use SQL Developer (highly recommmend, free with plenty of support) or SQL plus so I cannot help with TOAD, but I would expect it to be the same. In SQL Developer (and in SQL Navigator if memory serves correct) you can simply right click the package/method you wish and it will create the script for you.
in toad and navigator I believe you may be able to get the ref cursor in a pretty grid while in developer you get it in text.
SQL Developer you can unit test as well
Try this:
DECLARE
aCursor SYS_REFCURSOR;
someVariable SOME_TYPE;
FUNCTION SOME_FUNC_RETURNING_A_CURSOR RETURN SYS_REFCURSOR IS
csrLocal SYS_REFCURSOR;
BEGIN
OPEN csrLocal FOR SELECT whatever FROM wherever;
RETURN csrLocal;
END SOME_FUNC_RETURNING_A_CURSOR;
BEGIN
aCursor := SOME_FUNC_RETURNING_A_CURSOR;
WHILE TRUE LOOP
FETCH aCursor INTO someVariable;
EXIT WHEN aCursor%NOTFOUND;
...do whatever with variables...
END LOOP;
COMMIT;
END;
Share and enjoy.
I found an easier way to this ...try it (This will also generate script for you)
In the Procedure Editor, load your procedure. Click on the lightning
bolt to execute and you will see the Set Parameters window, which is
also available via the button on the Proc Editor toolbar that has an
image similar to (...) on it, next to the lightning bolt. Click on the
output options button and you'll see your options. If this is a weak ref
cursor then you must use the in-memory grid option. Results go to the
cursor results tab at the bottom of the PE after you execute.
http://toad.10940.n7.nabble.com/display-ref-cursor-in-toad-td1427.html

Oracle Function: Replicate wm_concat

I currently am working on a project within Crystal Reports that refuses to use the undocumented function WM_CONCAT, which is allowable within Oracle 10g.
Here is the WM_CONCAT header information
WM_CONCAT(p1 IN VARCHAR2) RETURN VARCHAR2
To use WM_CONCAT I pass it the following: WM_CONCAT(column1); This function seems to accept a column of type varchar2, and returns a comma delimited list of values from the column. I currently have a custom version of this function that works (on my work computer), but it is not optimal and lacks re-usability. Could anyone provide a good, re-usable function like WM_CONCAT that I could use?
Do you get an error message when you use wm_concat?
Unlike functions like to_char, it is owned by wmsys and you might need to use wmsys.wm_concat to use it. (unless you create the necessary synonyms of course).
Now for the actual question,
This technique is called string aggregation.
You could find a lot of other alternatives here.
http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
For other methods, Search for "stragg" on http://asktom.oracle.com
Another useful link : http://www.orafaq.com/node/2290
This is probably the most used one.
A lot of teams write their own custom functions which more or less do the same.
CREATE OR REPLACE FUNCTION get_employees (p_deptno in emp.deptno%TYPE)
RETURN VARCHAR2
IS
l_text VARCHAR2(32767) := NULL;
BEGIN
FOR cur_rec IN (SELECT ename FROM emp WHERE deptno = p_deptno) LOOP
l_text := l_text || ',' || cur_rec.ename;
END LOOP;
RETURN LTRIM(l_text, ',');
END;
/
SHOW ERRORS
while this solution works for varchar2 and number, the best generic solution can be built using Oracle ODCIAggregate interface.
http://download-west.oracle.com/docs/cd/B14117_01/appdev.101/b10800/dciaggfns.htm#sthref462
Implementation for the same is at the first link above at www.oracle-base.com
I've solved this using a technique similar to the last one in the oracle-base article: define a custom TABLE type and write a function to aggregate a value of that type into a string. I called my function joinstr and then you can call it as follows:
SELECT joinstr(CAST(MULTISET(SELECT column1 FROM table1) AS my_string_table_type), ',')
FROM DUAL
Note: I was on 9i until recently and haven't looked into COLLECT yet.

how do oracle stored procedures (w/ cursors) work?

I have a following oracle stored procedure
CREATE OR REPLACE
PROCEDURE getRejectedReasons
(
p_cursor IN OUT SYS_REFCURSOR)
AS
BEGIN
OPEN p_cursor FOR SELECT * FROM reasons_for_rejection;
END;
However, when I run this stored procedure in sql-developer then I dont see anything. I just see something like this:
Connecting to the database oracleLocal.
Process exited.
Disconnecting from the database oracleLocal.
I'm coming from MS sql server and am used to seeing actual results when running a stored procedure like this. Is this stored procedure not returning results because I am using a cursor??
The stored procedure is returning something it's just you aren't doing anything with the results.
You can do this simply by running the following script in SQLDeveloper:
VARIABLE csr REFCURSOR;
EXEC getRejectedReasons(:csr); -- the colon identifies the parameter as a variable
PRINT csr;
Another method is to fetch each row and do some sort of processing:
DECLARE
-- sys_refcursor is weakly typed
refcsr SYS_REFCURSOR;
-- define a record so we can reference the fields
rej_rec Reasons_for_Rejection%ROWTYPE;
BEGIN
getRejectedReasons(refcsr);
-- loop through the results
LOOP
-- gets one row at a time
FETCH refcsr INTO rej_rec;
-- if the fetch doesn't find any more rows exit the loop
EXIT WHEN refcsr%NOTFOUND;
-- Do something here.
-- For example : DBMS_OUTPUT.PUT_LINE(rej_rec.reason_desc);
END LOOP;
END;
You opened the cursor. You didn't select anything from it, update it, or advance it.
All open does, effectively, to select the matching rows into temporary memory, so you can advance the cursor row by row. Which you didn't do.
One of the differences between Oracle and SQL Server is that the latter returns result sets naturally. I'd use a function, by the way.
In Oracle, functions typically return a single element. Cursors came later.
There's some documentation online that will help you understand the use of refcursor bind variables. Here's one such for SQL*Plus:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch5.htm#sthref1122
I think in SQL Developer you can do the same thing with autoprint on, although I haven't tested that.
Found a blog that also discusses something similar:
http://vadimtropashko.wordpress.com/cursors/
ETA: Ok. Ignore what I wrote. Listen to someone else. Apparently it's wrong, as I got down voted.
What tpdi said is correct. You have to do something with the cursor after you declare it.
Here's an example using two cursors in nested loops
PROCEDURE update_insert_tree (exid_in IN NUMBER, outvar_out OUT VARCHAR2)
IS
nxtid NUMBER;
phaseid NUMBER;
rowcounter1 NUMBER;
BEGIN
rowcounter1 := 0;
outvar_out := 0;
FOR acur IN (SELECT dept_exercise_id, phase
FROM ep_dept_exercise
WHERE exercise_id = exid_in)
LOOP
<<dept_loop>>
FOR thecur IN (SELECT document_name, thelevel, sortnum, type_flag,
ex_save_id
FROM ep_exercise_save
WHERE exercise_id = exid_in)
LOOP
phaseid := acur.phase;
IF phaseid = 0
THEN
phaseid := 10;
UPDATE ep_dept_exercise
SET phase = 10
WHERE dept_exercise_id = acur.dept_exercise_id;
END IF;
<<doc_loop>>

Resources