Pass a regular CURSOR to a PL/SQL procedure that expects SYS_REFCURSOR - oracle

I have a lot of named cursors in PL/SQL like this:
cursor MY_CURSOR_01 is select * from my_table_01;
cursor MY_CURSOR_02 is select * from my_table_02;
I want to use them in dbms_xmlgen.newContext procedure which expects a SYS_REFCURSOR or a VARCHAR2 containing the actual query.
I already know that I could do:
dbms_xmlgen.newContect('select * from my_table_01');
But I would like to reuse the existing cursors I have, without rewriting them as string queries.
Any ideas? I am on Oracle 10gR2.

I don't think such a function exists, because Oracle's language specification doesn't allow for cursor objects to be passed as parameters. Unless Oracle has used some magic somewhere, there's just no way to generically reference a cursor without using a refcursor.
However, you don't need to embed your SQL in a string to use a sys_refcursor. Here's a very simple example showing that a sys_refcursor can be opened using static SQL:
DECLARE
c SYS_REFCURSOR;
BEGIN
OPEN c FOR SELECT * FROM DUAL;
CLOSE c;
END;

Related

stored procedure for select query not giving output

I am using sqlplus and have a table named users from which I wish to retrieve all values with the help of a stored procedure in oracle. Here is what I am trying to do -
create or replace procedure getall(prc out sys_refcursor)
is
begin
open prc for select * from users
end;
/
When I hit return after this, I get the following error -
Warning: Procedure created with compilation errors.
Why does this happen? And how do I get the desired output? Help much appreciated!
To see the compilation errors use the show errors‌​ SQL*Plus command (which also works in SQL Developer), or query the user_errors view which works with any client. You can also query all_errors to see problems with objects that are not in your schema.
But you are just missing a semicolon after the select:
create or replace procedure getall(prc out sys_refcursor)
is
begin
open prc for select * from users;
end;
/
You'll need a bind variable to be able to see the output in SQL*Plus, e.g.:
variable rc refcursor;
exec getall(:rc);
print rc
Notice the colon before the rc in the procedure call, which shows it's a bind variable reference. And exec is a shorthand anonymous block.
You might find it simpler to have a function that returns a ref cursor, or a pipelined function; or just query the table directly of course.

PLSQL: Procedure outputting multiple cursors

I'd like to return multiple cursor in one procedure, one based on other.
My currently code is:
TYPE REFCURSOR IS REF CURSOR;
PROCEDURE GETCARS(oCARS OUT REFCURSOR)
BEGIN
OPEN oCARS FOR SELECT * FROM CARS;
END GETCARS;
I'm not sure if that's posible but I want to make something like:
PROCEDURE GETCARS(oCARS OUT REFCURSOR, oREPAIRS OUT REFCURSOR)
BEGIN
OPEN oCARS FOR SELECT * FROM CARS;
..??..
END GETCARS;
which would return as a second parameter all repairs connected with currently fetched oCARS row.
(Table repairs has a FK for an id_car from cars)
Now I do that on C# side, when I fetch one row from oCARS cursor I call second procedure which gives me list of repairs, but maybe it's somehow possible to do that in one procedure (which would give me performance gain? - I don't want to use join, cause it returns multiplied cars for each repair)
The simple answer is that you can't do what you are attempting.
Cursors are basically just pointers to the start of the result set that contains the query results. Until you fetch a row, there is no way to know what that row will contain. Because your application, rather than the PL/SQL code, is doing the fetching, the PL/SQL portion has no knowledge of the values being returned.
To do what you're attempting, the database would have to detect the fetch from the first query, create a new result set using the second query, then place the new result set at the address that the procedure originally returned for the second cursor. Databases just aren't designed to handle this kind of operation.
How about
PROCEDURE GETCARS(oCARS OUT SYS_REFCURSOR, oREPAIRS OUT SYS_REFCURSOR, oCHARGES OUT SYS_REFCURSOR)
BEGIN
OPEN oCARS FOR SELECT * FROM CARS;
OPEN oREPAIRS FOR SELECT * FROM REPAIRS;
OPEN oCHARGES FOR SELECT * FROM CHARGES;
END GETCARS;
Share and enjoy.

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.

Getting results in a result set from dynamic SQL in Oracle

This question is similar to a couple others I have found on StackOverflow, but the differences are signficant enough to me to warrant a new question, so here it is:
I want to obtain a result set from dynamic SQL in Oracle and then display it as a result set in a SqlDeveloper-like tool, just as if I had executed the dynamic SQL statement directly. This is straightforward in SQL Server, so to be concrete, here is an example from SQL Server that returns a result set in SQL Server Management Studio or Query Explorer:
EXEC sp_executesql N'select * from countries'
Or more properly:
DECLARE #stmt nvarchar(100)
SET #stmt = N'select * from countries'
EXEC sp_executesql #stmt
The question "How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?" addresses the first half of the problem--executing dynamic SQL into a cursor. The question "How to make Oracle procedure return result sets" provides a similar answer. Web search has revealed many variations of the same theme, all addressing just the first half of my question. I found this post explaining how to do it in SqlDeveloper, but that uses a bit of functionality of SqlDeveloper. I am actually using a custom query tool so I need the solution to be self-contained in the SQL code. This custom query tool similarly does not have the capability to show output of print (dbms_output.put_line) statements; it only displays result sets. Here is yet one more possible avenue using 'execute immediate...bulk collect', but this example again renders the results with a loop of dbms_output.put_line statements. This link attempts to address the topic but the question never quite got answered there either.
Assuming this is possible, I will add one more condition: I would like to do this without having to define a function or procedure (due to limited DB permissions). That is, I would like to execute a self-contained PL/SQL block containing dynamic SQL and return a result set in SqlDeveloper or a similar tool.
So to summarize:
I want to execute an arbitrary SQL statement (hence dynamic SQL).
The platform is Oracle.
The solution must be a PL/SQL block with no procedures or functions.
The output must be generated as a canonical result set; no print statements.
The output must render as a result set in SqlDeveloper without using any SqlDeveloper special functionality.
Any suggestions?
The closest thing I could think of is to create a dynamic view for which permission is required. This will certainly involve using a PL/SQL block and a SQL query and no procedure/function. But, any dynamic query can be converted and viewed from the Result Grid as it's going to be run as a select query.
DEFINE view_name = 'my_results_view';
SET FEEDBACK OFF
SET ECHO OFF
DECLARE
l_view_name VARCHAR2(40) := '&view_name';
l_query VARCHAR2(4000) := 'SELECT 1+level as id,
''TEXT''||level as text FROM DUAL ';
l_where_clause VARCHAR2(4000):=
' WHERE TRUNC(1.0) = 1 CONNECT BY LEVEL < 10';
BEGIN
EXECUTE IMMEDIATE 'CREATE OR REPLACE VIEW '
|| l_view_name
|| ' AS '
|| l_query
|| l_where_clause;
END;
/
select * from &view_name;
You seem to be asking for a chunk of PL/SQL code that will take an arbitrary query returning result set of undetermined structure and 'forward/restructure' that result set in some way such that is can easily be rendered by some "custom GUI tool".
If so, look into the DBMS_SQL for dynamic SQL. It has a DESCRIBE_COLUMNS procedure which returns the columns from a dynamic SELECT statement. The steps you would need are,
Parse the statement
Describe the result set (column names and data types)
Fetch each row, and for each column, call the datatype dependent function to return that value into a local variable
Place those local variables into a defined structure to return to the calling environment (eg consistent column names [such as col_1, col_2] probably all of VARCHAR2)
As an alternative, you could try building the query into an XMLFOREST statement, and parse the results out of the XML.
Added :
Unlike SQL Server, an Oracle PL/SQL call will not 'naturally' return a single result set. It can open up one or more ref cursors and pass them back to the client. It then becomes the client's responsibility to fetch records and columns from those ref cursors. If your client doesn't/can't deal with that, then you cannot use a PL/SQL call.
A stored function can return a pre-defined collection type, which can allow you to do something like "select * from table(func_name('select * from countries'))". However the function cannot do DML (update/delete/insert/merge) because it blows away any concept of consistency for that query. Plus the structure being returned is fixed so that
select * from table(func_name('select * from countries'))
must return the same set of columns (column names and data types) as
select * from table(func_name('select * from persons'))
It is possible, using DBMS_SQL or XMLFOREST, for such a function to take a dynamic query and restructure it into a pre-defined set of columns (col_1, col_2, etc) so that it can be returned in a consistent manner. But I can't see what the point of it would be.
Try try these.
DECLARE
TYPE EmpCurTyp IS REF CURSOR;
v_emp_cursor EmpCurTyp;
emp_record employees%ROWTYPE;
v_stmt_str VARCHAR2(200);
v_e_job employees.job%TYPE;
BEGIN
-- Dynamic SQL statement with placeholder:
v_stmt_str := 'SELECT * FROM employees WHERE job_id = :j';
-- Open cursor & specify bind argument in USING clause:
OPEN v_emp_cursor FOR v_stmt_str USING 'MANAGER';
-- Fetch rows from result set one at a time:
LOOP
FETCH v_emp_cursor INTO emp_record;
EXIT WHEN v_emp_cursor%NOTFOUND;
END LOOP;
-- Close cursor:
CLOSE v_emp_cursor;
END;
declare
v_rc sys_refcursor;
begin
v_rc := get_dept_emps(10); -- This returns an open cursor
dbms_output.put_line('Rows: '||v_rc%ROWCOUNT);
close v_rc;
end;
Find more examples here. http://forums.oracle.com/forums/thread.jspa?threadID=886365&tstart=0
In TOAD when executing the script below you will be prompted for the type of v_result. From the pick list of types select cursor, the results are then displayed in Toad's data grid (the excel spreadsheet like result). That said, when working with cursors as results you should always write two programs (the client and the server). In this case 'TOAD' will be the client.
DECLARE
v_result sys_refcursor;
v_dynamic_sql VARCHAR2 (4000);
BEGIN
v_dynamic_sql := 'SELECT * FROM user_objects where ' || ' 1 = 1';
OPEN :v_result FOR (v_dynamic_sql);
END;
There may be a similar mechanism in Oracle's SQL Developer to prompt for the binding as well.

In PL/SQL, can I pass the table schema of a cursor FROM clause via a stored procedure parameter?

In PL/SQL, I would like to pass in a "source" schema as a parameter to a stored procedure. For instance:
BEGIN
CURSOR my_cursor IS
SELECT my_field FROM <schema>.my_table
...
I want the 'schema' value to come from an input parameter into the stored procedure. Does anyone know how I could do that?
P.S. Sorry if this is a stupid simple question, but I'm new to PL/SQL and must get some functions written quickly.
In addition to what Mark Brady said, another dynamic SQL option is to use a REF CURSOR. Since your sample code includes a cursor this would be the most relevant.
PROCEDURE select_from_schema( the_schema VARCHAR2)
IS
TYPE my_cursor_type IS REF CURSOR;
my_cursor my_cursor_type;
BEGIN
OPEN my_cursor FOR 'SELECT my_field FROM '||the_schema||'.my_table';
-- Do your FETCHes just as with a normal cursor
CLOSE my_cursor;
END;
This has to be done with dynamic sql.
Either the DBMS_SQL package or the Execute Immediate statement.
You can't use variables in the FROM clause.
A potential solution may be to
ALTER SESSION SET Current_Schema = '' <-- the schema you want.
That command changes the default schema. SO if you have a bunch of identically named tables you can save yourself dynamic SQL and make a Dynamic Alter Session.

Resources