Function to return a cursor in PL SQL, - oracle

I have a function which returns a SYS_REFCURSOR, this function is to be called from different packages and we don't want to have to duplicate the cursor definition in multiple places.
FUNCTION f_get_cur(p_date DATE, p_code VARCHAR(10)) RETURN SYS_REFCURSOR IS
cur_s SYS_REFCURSOR;
BEGIN
OPEN cur_s FOR
SELECT .blah blah etc etc
return cur_s;
END f_get_cur;
Which compiles ok, however when I want to use the function in a FOR LOOP where I'd normally put the cursor I get the following error
Error: PLS-00456: item 'f_get_cur' is not a cursor
I'm attempting to open the cursor like so...
FOR cc_rec IN f_get_cur(c_date, p_c_code) LOOP
Am I using the wrong data type? Is there some other way of achieving what I'm trying?

You need to handle the returned cursor in a different way; for example:
SQL> create or replace FUNCTION f_get_cur(p_date DATE, p_code VARCHAR) RETURN SYS_REFCURSOR IS
2 cur_s SYS_REFCURSOR;
3 BEGIN
4 OPEN cur_s FOR
5 SELECT to_char(p_date, 'dd-mm-yyyy') || p_code val from dual;
6
7 return cur_s;
8 END f_get_cur;
9 /
Function created.
SQL> declare
2 cur_s SYS_REFCURSOR;
3 v varchar2(100);
4 begin
5 cur_s := f_get_cur(sysdate, 'xx');
6 loop
7 fetch cur_s into v;
8 exit when cur_s%NOTFOUND;
9 dbms_output.put_line(v);
10 end loop;
11 end;
12 /
30-04-2019xx
PL/SQL procedure successfully completed.
SQL>

I managed to get this working by creating another(!) cursor which implements the function I already created (which wraps the original cursor)
cursor cur_real(cp_date DATE, cd_code VARCHAR2(10)) IS
select ... etc
FROM TABLE(f_get_cur(cp_date, cp_code));
I can now use the cursor like so
FOR cc_rec IN f_get_cur(c_date, p_c_code) LOOP
do stuff ... etc
END LOOP

Related

How can I get the total number of records selected by a sysref cursor?

BACKGROUND
I am working on a web application that calls PLSQL stored procedures to retrieve and manipulate information. In one such case, the database has two stored procedures; one that selects the total number of records for a given set of parameters and one that returns the actual records with the same parameters, plus pagination parameters (min and max rownum).
EX (not the actual code):
PROCEDURE get_records_count(
p_first_name IN record_table.first_name%TYPE,
p_last_name IN record_table.last_name%TYPE,
p_resultCursor OUT sys_refcursor
)
IS BEGIN
OPEN p_resultCursor FOR
SELECT count(*) from record_table
WHERE first_name LIKE (p_first_name || '%')
OR last_name LIKE (p_last_name || '%');
END;
PROCEDURE get_records(
p_first_name IN record_table.first_name%TYPE,
p_last_name IN record_table.last_name%TYPE,
p_min IN NUMBER,
p_max IN NUMBER,
p_resultCursor OUT sys_refcursor
)
IS BEGIN
OPEN p_resultCursor FOR
SELECT * from record_table
WHERE first_name LIKE (p_first_name || '%')
OR last_name LIKE (p_last_name || '%')
AND rownum >= p_min AND rownum <= p_max;
END;
Whether or not one thinks that this is a good idea is beyond the scope of my position. The problem is that whenever either stored procedure is changed, the results don't match up. The short term fix is to look through both stored procedures, determine which selection criteria from which stored procedure is appropriate and then edit the other stored procedure so that they both match up.
As a long term fix, I would like to change the get_records_count procedure to call the get_records procedure and then return the total number of records that would be returned from the resulting sys_refcursor.
EX:
PROCEDURE get_records_count(
p_first_name IN record_table.first_name%TYPE,
p_last_name IN record_table.last_name%TYPE,
p_resultCursor OUT sys_refcursor
)
AS
v_recordsSelectedCursor sys_refcursor;
BEGIN
/*I understand that I will need to change some logic in get_records to
handle the case in which p_max is set to zero.
It should take this case to not apply an upper limit.*/
get_records(p_first_name,p_last_name,0,0,v_recordsSelectedCursor);
/*This is where I really have NO idea what I'm doing.
Hopefully, you can infer what I'm trying to do. */
OPEN p_resultCursor FOR
SELECT count(*) FROM v_recordsSelectedCursor;
END;
ACTUAL QUESTION
How can I select the number of records that would be returned for a sys_refcursor? The resulting number needs to be returned inside a sys_refcursor
A cursor is just a spec for fetching rows - it doesn't know how many rows are going to be returned until it has fetched them all.
Any method involving calling it twice risks getting inconsistent results unless you use dbms_flashback.enable_at_time at the start of the procedure (and disable it at the end). There is also the performance overhead, of course.
The only way to get a cursor to include its total rowcount is to include an analytic count(*) over () expression in the select list.
How can I select the number of records that would be returned for a
sys_refcursor? The resulting number needs to be returned inside a
sys_refcursor.
You can modify your procedure as below:
PROCEDURE get_records_count(
p_first_name IN record_table.first_name%TYPE,
p_last_name IN record_table.last_name%TYPE,
p_resultCursor OUT sys_refcursor
)
AS
v_recordsSelectedCursor sys_refcursor;
type y is table of record_table%rowtype;
z y;
num number:=0;
BEGIN
get_records(p_first_name,p_last_name,0,0,v_recordsSelectedCursor);
fetch v_recordsSelectedCursor bulk collect into z;
---taking the count of refcursor
num:=z.count;
OPEN p_resultCursor FOR
select num from dual;
dbms_output.put_line(num);
END;
See demo:
SQL> SELECT count(*)
FROM emp;
COUNT(*)
----------
14
SQL> CREATE OR REPLACE PROCEDURE sys_ref_rec_cnt (var OUT sys_refcursor)
2 AS
3 BEGIN
4 OPEN var FOR
5 SELECT *
6 FROM emp;
7 END;
8 /
Procedure created.
SQL> DECLARE
2 x sys_refcursor;
3 k sys_refcursor;
4 TYPE y IS TABLE OF emp%ROWTYPE;
5 z y;
6 num NUMBER := 0;
7 BEGIN
8 sys_ref_rec_cnt (x);
9
10 FETCH x
11 BULK COLLECT INTO z;
12
13 num :=z.count;
14
15 open k for
16 select num from dual;
17
18 DBMS_OUTPUT.put_line ('No. Of records-->'||num);
19 END;
20 /
No. Of records-->14
PL/SQL procedure successfully completed.

Using cursor with where in condition

I am passing arguments `EBN,BGE' into a procedure , then I am passing this argument to a cursor.
create or replace procedure TEXT_MD (AS_IDS VARCHAR2)
is
CURSOR C_A (AS_ID VARCHAR2) IS
SELECT
name
FROM S_US
WHERE US_ID IN (AS_ID);
BEGIN
FOR A IN C_A (AS_IDS) LOOP
DBMS_OUTPUT.PUT_LINE('I got here: '||AS_IDS);
end loop;
END;
But while debuging the count of the cursor is still null
So my question , why the cursor not returning values with in condition
You are passing a string parameter, so it will be used as a string, not as a list of strings; so, your cursor will be something like
SELECT name
FROM S_US
WHERE US_ID IN ('EBN,BGE')
This will, of course, not do what you need.
You may need to change your procedure and the way to pass parameters; if you want to keep a string parameter , one way could be the following:
setup:
SQL> CREATE TABLE S_US
2 (
3 US_ID,
4 NAME
5 ) AS
6 SELECT 'EBN', 'EBN name' FROM DUAL
7 UNION ALL
8 SELECT 'BGE', 'BGE name' FROM DUAL;
Table created.
procedure:
SQL> CREATE OR REPLACE PROCEDURE TEXT_MD_2(AS_IDS VARCHAR2) IS
2 vSQL varchar2(1000);
3 c sys_refcursor;
4 vName varchar2(16);
5 BEGIN
6 vSQL := 'SELECT name
7 FROM S_US
8 WHERE US_ID IN (' || AS_IDS || ')';
9 open c for vSQL;
10 loop
11 fetch c into vName;
12 if c%NOTFOUND then
13 exit;
14 end if;
15 DBMS_OUTPUT.PUT_LINE(vName);
16 END LOOP;
17 END;
18 /
Procedure created.
You need to call it with a string already formatted to be a parameter list for IN:
SQL> EXEC TEXT_MD_2('''EBN'',''BGE''');
EBN name
BGE name
PL/SQL procedure successfully completed.
This is only an example of a possible way, and not the way I would do this.
Among the reasons to avoud this kind of approach, consider what Justin Cave says:
"that would be a security risk due to SQL injection and would have a potentially significant performance penalty due to constant hard parsing".
I believe you should better check how to pass a list of values to your procedure, rather then using a string to represent a list of strings.
Here is a possible way to do the same thing with a collection:
SQL> CREATE OR REPLACE TYPE tabVarchar2 AS TABLE OF VARCHAR2(16)
2 /
Type created.
SQL>
SQL> CREATE OR REPLACE PROCEDURE TEXT_MD_3(AS_IDS tabVarchar2) IS
2 vSQL VARCHAR2(1000);
3 c SYS_REFCURSOR;
4 vName VARCHAR2(16);
5 BEGIN
6 FOR i IN (SELECT name
7 FROM S_US INNER JOIN TABLE(AS_IDS) tab ON (tab.COLUMN_VALUE = US_ID))
8 LOOP
9 DBMS_OUTPUT.PUT_LINE(i.name);
10 END LOOP;
11 END;
12 /
Procedure created.
SQL>
SQL> DECLARE
2 vList tabVarchar2 := NEW tabVarchar2();
3 BEGIN
4 vList.EXTEND(2);
5 vList(1) := 'BGE';
6 vList(2) := 'EBN';
7 TEXT_MD_3(vList);
8 END;
9 /
BGE name
EBN name
PL/SQL procedure successfully completed.
SQL>
Again, you can define collections in different ways, within a stored procedure or not, indexed or not, and so on; this is only one of the possible ways, not necessarily the best, depending on your environment, needs.

Oracle stored function - pass table name as parameter

I'm trying to create a stored function in Oracle that will count the table rows..i want to make the table name dynamic, so i passed it as a parameter, the stored function code looks like this
create type tes_jml_obj is object(jumlah integer);
create type tes_jml_table is table of tes_jml_obj;
create or replace function jumlahBaris(namatabel varchar)
return tes_jml_table
is
tabel tes_jml_table := tes_jml_table();
begin
for r in (execute immediate 'select count(*) as jumlah from' || namatabel)
loop
tabel.extend;
tabel(1) := tes_jml_obj(r.jumlah);
end loop;
return tabel;
end;
But when i execute it, it returns errors. Am i missing something here? Is that the correct way to get the table rows dynamically?
There is a space missing after FROM keyword in the EXECUTE IMMEDIATE statement.
EXECUTE IMMEDIATE statement has a syntax error. You are missing the INTO clause.
You cannot use EXECUTE IMMEDIATE inside a CURSOR FOR LOOP. Basically, you are returning nothing from the execute immediate statement as mentioned in point 2 above.
The iteration syntax for the LOOP is not correct. The syntax is FOR r IN 1..COUNT().
After rectifying your code, this is how it would look like:
SQL> CREATE OR REPLACE TYPE TES_JML_OBJ IS OBJECT(JUMLAH NUMBER)
2 /
Type created.
SQL> CREATE OR REPLACE TYPE TES_JML_TABLE IS TABLE OF TES_JML_OBJ
2 /
Type created.
SQL> CREATE OR REPLACE
2 FUNCTION jumlahBaris(
3 namatabel VARCHAR2)
4 RETURN tes_jml_table
5 IS
6 TABEL TES_JML_TABLE := TES_JML_TABLE();
7 cnt NUMBER;
8 BEGIN
9 EXECUTE IMMEDIATE 'select count(*) as jumlah from ' || NAMATABEL INTO CNT;
10 FOR R IN 1..CNT
11 LOOP
12 TABEL.EXTEND;
13 TABEL(R) := TES_JML_OBJ(R);
14 dbms_output.put_line(TES_JML_OBJ(R).jumlah);
15 END LOOP;
16 RETURN tabel;
17 END;
18 /
Function created.
SQL> SHO ERR
No errors.
So, the function compiled with no errors. Let's execute it and see the output:
SQL> SET SERVEROUTPUT ON
SQL> SELECT JUMLAHBARIS('EMP') FROM DUAL;
JUMLAHBARIS('EMP')(JUMLAH)
--------------------------------------------------------------------------------
TES_JML_TABLE(TES_JML_OBJ(1), TES_JML_OBJ(2), TES_JML_OBJ(3), TES_JML_OBJ(4), TE
S_JML_OBJ(5), TES_JML_OBJ(6), TES_JML_OBJ(7), TES_JML_OBJ(8), TES_JML_OBJ(9), TE
S_JML_OBJ(10), TES_JML_OBJ(11), TES_JML_OBJ(12), TES_JML_OBJ(13), TES_JML_OBJ(14
))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
SQL>
Your execute immediate will return only one value, the count, so what is there to loop over?
Also I'm not sure that execute immediate works with an implicit cursor.
In your SQL it looks like you don't have a space after the from keyword.
Try something like this instead:
create or replace function jumlahBaris(namatabel varchar)
return tes_jml_table
is
tabel tes_jml_table := tes_jml_table();
the_count integer;
the_sql varchar(100);
begin
the_sql := 'select count(*) as jumlah from ' || namatabel;
execute immediate the_sql INTO the_count;
if the_count IS NOT NULL THEN
tabel.extend;
tabel(1) := tes_jml_obj(the_count);
end if;
return tabel;
end;

Get the name of the calling procedure or function in Oracle PL/SQL

Does anyone know whether it's possible for a PL/SQL procedure (an error-logging one in this case) to get the name of the function/procedure which called it?
Obviously I could pass the name in as a parameter, but it'd be nice to make a system call or something to get the info - it could just return null or something if it wasn't called from a procedure/function.
If there's no method for this that's fine - just curious if it's possible (searches yield nothing).
There is a package called OWA_UTIL (which is not installed by default in older versions of the database). This has a method WHO_CALLED_ME() which returns the OWNER, OBJECT_NAME, LINE_NO and CALLER_TYPE. Note that if the caller is a packaged procedure it will return the PACKAGE name not the procedure name. In this case there is no way of getting the procedure name; this is because the procedure name can be overloaded, so it's not necessarily very useful.
Find out more.
Since 10gR2 there is also the $$PLSQL_UNIT special function; this will also return the OBJECT NAME (i.e. package not packaged procedure).
I found this forum: http://www.orafaq.com/forum/t/60583/0/. It may be what you are looking.
Basically, you can use the Oracle supplied dbms_utility.format_call_stack:
scott#ORA92> CREATE TABLE error_tab
2 (who_am_i VARCHAR2(61),
3 who_called_me VARCHAR2(61),
4 call_stack CLOB)
5 /
Table created.
scott#ORA92>
scott#ORA92> CREATE OR REPLACE PROCEDURE d
2 AS
3 v_num NUMBER;
4 v_owner VARCHAR2(30);
5 v_name VARCHAR2(30);
6 v_line NUMBER;
7 v_caller_t VARCHAR2(100);
8 BEGIN
9 select to_number('a') into v_num from dual; -- cause error for testing
10 EXCEPTION
11 WHEN OTHERS THEN
12 who_called_me (v_owner, v_name, v_line, v_caller_t);
13 INSERT INTO error_tab
14 VALUES (who_am_i,
15 v_owner || '.' || v_name,
16 dbms_utility.format_call_stack);
17 END d;
18 /
Procedure created.
scott#ORA92> SHOW ERRORS
No errors.
scott#ORA92> CREATE OR REPLACE PROCEDURE c
2 AS
3 BEGIN
4 d;
5 END c;
6 /
Procedure created.
scott#ORA92> CREATE OR REPLACE PROCEDURE b
2 AS
3 BEGIN
4 c;
5 END b;
6 /
Procedure created.
scott#ORA92> CREATE OR REPLACE PROCEDURE a
2 AS
3 BEGIN
4 b;
5 END a;
6 /
Procedure created.
scott#ORA92> execute a
PL/SQL procedure successfully completed.
scott#ORA92> COLUMN who_am_i FORMAT A13
scott#ORA92> COLUMN who_called_me FORMAT A13
scott#ORA92> COLUMN call_stack FORMAT A45
scott#ORA92> SELECT * FROM error_tab
2 /
WHO_AM_I WHO_CALLED_ME CALL_STACK
------------- ------------- ---------------------------------------------
SCOTT.D SCOTT.C ----- PL/SQL Call Stack -----
object line object
handle number name
6623F488 1 anonymous block
66292138 13 procedure SCOTT.D
66299430 4 procedure SCOTT.C
6623D2F8 4 procedure SCOTT.B
6624F994 4 procedure SCOTT.A
66299984 1 anonymous block
scott#ORA92>
Basically, all you need to do is to define vars and pass them in a call to a utility method to fill them up with values:
create or replace procedure some_test_proc (p_some_int int)
is
owner_name VARCHAR2 (100);
caller_name VARCHAR2 (100);
line_number NUMBER;
caller_type VARCHAR2 (100);
begin
....
OWA_UTIL.WHO_CALLED_ME (owner_name,caller_name,line_number,caller_type);
-- now you can insert those values along with systimestamp into a log file
....
end;

Selecting Values from Oracle Table Variable / Array?

Following on from my last question (Table Variables in Oracle PL/SQL?)...
Once you have values in an array/table, how do you get them back out again? Preferably using a select statement or something of the like?
Here's what I've got so far:
declare
type array is table of number index by binary_integer;
pidms array;
begin
for i in (
select distinct sgbstdn_pidm
from sgbstdn
where sgbstdn_majr_code_1 = 'HS04'
and sgbstdn_program_1 = 'HSCOMPH'
)
loop
pidms(pidms.count+1) := i.sgbstdn_pidm;
end loop;
select *
from pidms; --ORACLE DOESN'T LIKE THIS BIT!!!
end;
I know I can output them using dbms_output.putline(), but I'm hoping to get a result set like I would from selecting from any other table.
Thanks in advance,
Matt
You might need a GLOBAL TEMPORARY TABLE.
In Oracle these are created once and then when invoked the data is private to your session.
Oracle Documentation Link
Try something like this...
CREATE GLOBAL TEMPORARY TABLE temp_number
( number_column NUMBER( 10, 0 )
)
ON COMMIT DELETE ROWS;
BEGIN
INSERT INTO temp_number
( number_column )
( select distinct sgbstdn_pidm
from sgbstdn
where sgbstdn_majr_code_1 = 'HS04'
and sgbstdn_program_1 = 'HSCOMPH'
);
FOR pidms_rec IN ( SELECT number_column FROM temp_number )
LOOP
-- Do something here
NULL;
END LOOP;
END;
/
In Oracle, the PL/SQL and SQL engines maintain some separation. When you execute a SQL statement within PL/SQL, it is handed off to the SQL engine, which has no knowledge of PL/SQL-specific structures like INDEX BY tables.
So, instead of declaring the type in the PL/SQL block, you need to create an equivalent collection type within the database schema:
CREATE OR REPLACE TYPE array is table of number;
/
Then you can use it as in these two examples within PL/SQL:
SQL> l
1 declare
2 p array := array();
3 begin
4 for i in (select level from dual connect by level < 10) loop
5 p.extend;
6 p(p.count) := i.level;
7 end loop;
8 for x in (select column_value from table(cast(p as array))) loop
9 dbms_output.put_line(x.column_value);
10 end loop;
11* end;
SQL> /
1
2
3
4
5
6
7
8
9
PL/SQL procedure successfully completed.
SQL> l
1 declare
2 p array := array();
3 begin
4 select level bulk collect into p from dual connect by level < 10;
5 for x in (select column_value from table(cast(p as array))) loop
6 dbms_output.put_line(x.column_value);
7 end loop;
8* end;
SQL> /
1
2
3
4
5
6
7
8
9
PL/SQL procedure successfully completed.
Additional example based on comments
Based on your comment on my answer and on the question itself, I think this is how I would implement it. Use a package so the records can be fetched from the actual table once and stored in a private package global; and have a function that returns an open ref cursor.
CREATE OR REPLACE PACKAGE p_cache AS
FUNCTION get_p_cursor RETURN sys_refcursor;
END p_cache;
/
CREATE OR REPLACE PACKAGE BODY p_cache AS
cache_array array;
FUNCTION get_p_cursor RETURN sys_refcursor IS
pCursor sys_refcursor;
BEGIN
OPEN pCursor FOR SELECT * from TABLE(CAST(cache_array AS array));
RETURN pCursor;
END get_p_cursor;
-- Package initialization runs once in each session that references the package
BEGIN
SELECT level BULK COLLECT INTO cache_array FROM dual CONNECT BY LEVEL < 10;
END p_cache;
/
The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)
Very basic sample:
declare
type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
pidms TPidmList;
begin
select distinct sgbstdn_pidm
bulk collect into pidms
from sgbstdn
where sgbstdn_majr_code_1 = 'HS04'
and sgbstdn_program_1 = 'HSCOMPH';
-- do something with pidms
open :someCursor for
select value(t) pidm
from table(pidms) t;
end;
When you want to reuse it, then it might be interesting to know how that would look like.
If you issue several commands than those could be grouped in a package.
The private package variable trick from above has its downsides.
When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.
e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)
However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.
create package Abc as
type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
function CreateList(majorCode in Varchar,
program in Varchar) return TPidmList;
function Test1(list in TPidmList) return PLS_Integer;
-- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
procedure Test2(list in TPidmList);
end;
create package body Abc as
function CreateList(majorCode in Varchar,
program in Varchar) return TPidmList is
result TPidmList;
begin
select distinct sgbstdn_pidm
bulk collect into result
from sgbstdn
where sgbstdn_majr_code_1 = majorCode
and sgbstdn_program_1 = program;
return result;
end;
function Test1(list in TPidmList) return PLS_Integer is
result PLS_Integer := 0;
begin
if list is null or list.Count = 0 then
return result;
end if;
for i in list.First .. list.Last loop
if ... then
result := result + list(i);
end if;
end loop;
end;
procedure Test2(list in TPidmList) as
begin
...
end;
return result;
end;
How to call it:
declare
pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
xyz PLS_Integer;
begin
Abc.Test2(pidms);
xyz := Abc.Test1(pidms);
...
open :someCursor for
select value(t) as Pidm,
xyz as SomeValue
from table(pidms) t;
end;

Resources