Oracle read and return data from cursor - oracle

I'm trying to create a stored procedure in Oracle that has one input parameter and one output variable and, in case of results, return a dataset to my .Net Application. The main issue is that I can't change the signature of the procedure and need to do if condition to validate if exist records or not.
The main issue that i've being struggled is with cursors (to execute and return the information), and to count the results of the select.
Here is an example of what i'm doing to try to retrieve the data.
CREATE PROCEDURE SP_Testing (v_input IN VARCHAR2(50), v_OutID NUMBER(1))
AS
TYPE v_record_botoes IS RECORD (
v_dummy_col1 VARCHAR2(50),
v_dummy_col2 VARCHAR2(250)
);
TYPE table_botoes IS TABLE OF v_record_botoes;
tt_botoes table_botoes;
v_ref_cursor SYS_REFCURSOR;
CURSOR v_cursor IS
(SELECT dt.v_dummy_col1,
dt.v_dummy_col2
FROM dummy_table dt
WHERE v_dummy_col3 = v_input);
v_check NUMBER;
BEGIN
tt_botoes := table_botoes();
v_check := 0;
FOR v_row IN v_cursor
LOOP
tt_botoes.extend;
tt_botoes(tt_botoes.COUNT) := v_row;
END LOOP;
v_check := tt_botoes.COUNT;
-- condition that need to know the nr of records of the select
IF v_check = 0 THEN
v_OutID := 0;
ELSE
v_OutID := 1;
OPEN v_ref_cursor FOR
SELECT *
FROM tt_botoes; -- also tryed "FROM TABLE (tt_botoes)" and "FROM TABLE (cast(tt_botoes AS table_botoes))"
-- return dataset to .net application
DBMS_SQL.RETURN_RESULT(v_ref_cursor)
END IF;
END;
Already tryed to convert the v_cursor into a sys_refcursor to be outputed by the DBMS_SQL package but didn't get anywhere.
Also i've tried to create a temporary table to hold the information, but then have a concurrency issue.
Any idea what i'm doing wrong, or any other possible solution to solve this issue?
Thanks in advance

Completely untested because I do not have the environment to test it but I would structure this quite differently, see below (I am assuming that the missing out in the specification is just a typo)
CREATE PROCEDURE SP_Testing (v_input IN VARCHAR2(50), v_OutID **out** NUMBER(1))
AS
v_ref_cursor SYS_REFCURSOR;
v_check NUMBER;
BEGIN
select count(1)
into v_check
from dummy_table dt
WHERE v_dummy_col3 = v_input
-- condition that need to know the nr of records of the select
IF v_check = 0 THEN
v_OutID := 0;
ELSE
v_OutID := 1;
OPEN v_ref_cursor FOR
SELECT dt.v_dummy_col1,
dt.v_dummy_col2
FROM dummy_table dt
WHERE v_dummy_col3 = v_input
-- return dataset to .net application
DBMS_SQL.RETURN_RESULT(v_ref_cursor)
END IF;
END;

Related

Validation of result before executing the query

When running a stored procedure to fetch some rows, First I want to validate if the query will return a row before sending the result, and second if it is possible to validate without running the same query twice.
I am using a cursor to store the yielded result, So I tried the cursor attribute %ROWCOUNT & %NOTFOUND. But the doesnt quite work. Plus I want to do this without running a loop on the cursor.
procedure MODULE_LIST_GK(p_module_Id IN MODULE_LIST.MODULE_ID% TYPE,
p_Error_Code out nvarchar2,
p_Error_Msg out nvarchar2,
p_Cursor out sys_refcursor) IS
BEGIN
OPEN p_Cursor FOR
SELECT A.MODULE_ID,
A.MODULE_NM,
A.AUTH_STATUS_ID
FROM MODULE_LIST A
WHERE A.MODULE_ID=p_module_Id;
SELECT COUNT(MODULE_ID)
INTO v_row_num
FROM MODULE_LIST A
WHERE A.MODULE_ID=p_module_Id;
IF v_row_num=0 THEN
p_Error_Code := SQLCODE;
p_Error_Msg := 'Does not Exists';
Return;
end IF;
EXCEPTION
WHEN OTHERS THEN
p_error_code:= SQLCODE;
p_error_msg := SQLERRM;
END MODULE_LIST_GK;
Your implementation have several points that could be improved.
First if you expect that for lot of parameters the returned cursor will be empty,
than first check the empty cursor and only after this check open the cursor. You do it vice versa.
How to check if the cursor is empty? Unfortunatelly you must fetch the first row to be able to verify it.
open l_cur for
select id, status from tab where id = p_id;
fetch l_cur into l_id, l_status;
if l_cur%NOTFOUND then
p_Error_Msg := 'Does not Exists';
Return;
end if;
This check is far more effective that the often used count(*) as it is considering only the first (few) rows and not counting all rows in the cursor.
If the check fails you are ready, othervise simple open the cursor and return it.
open l_cur for
select id, status from tab where id = p_id;
p_Cursor := l_cur;
Two additional thinks come to mind.
You should rething the generall approach if the database is very dynamic. How would you handle the case when other session deletes some row between the check and the second open of the cursor?
Finally consider returning an exception instead of the return code.
In order to know whether a cursor contains rows, you must open it and fetch the first row. Once you've done this, it makes no sense anymore to return that cursor, for the recipient will not be able to fetch that first row, because the cursor already points beyond it.
So, you must select twice. What you'd do is to use ROWNUM or an EXISTS clause here to show the DBMS that you are not interested in any more rows. This can speed up the query extremely.
PROCEDURE module_list_gk(p_module_id IN MODULE_LIST.MODULE_ID%TYPE,
p_error_code OUT NVARCHAR2,
p_error_msg OUT NVARCHAR2,
p_cursor OUT SYS_REFCURSOR) IS
v_count INTEGER;
BEGIN
SELECT COUNT(*)
INTO v_count
FROM module_list
WHERE module_id = p_module_Id
AND ROWNUM = 1;
IF v_count = 0 THEN
p_error_code := 0; -- Or -1403 for NO DATA FOUND if you like
p_error_msg := 'Does not Exists';
RETURN;
END IF;
OPEN p_Cursor FOR
SELECT module_id, module_nm, auth_status_id
FROM module_list
WHERE module_id = p_module_id;
EXCEPTION WHEN OTHERS THEN
p_error_code:= SQLCODE;
p_error_msg := SQLERRM;
END module_list_gk;
SQLCODE for the first query will be 0 by the way (SELECT COUNT(*) returns one row with the number of records found - no error hence). This is why you should decide to either return zero explicitly or some error code, such as -1403.
Here is the same with EXISTS:
BEGIN
SELECT CASE WHEN EXISTS
(
SELECT NULL
FROM module_list
WHERE module_id = p_module_Id
) THEN 1 ELSE 0 END
INTO v_count
FROM DUAL;
IF v_count = 0 THEN

PLSQL : FORALL insert when data is NOT from the type

I want to use FORALL to insert data into a table. But, in my below code I will not be able to
get l_final_amt and l_reference_number variables outside the FOR loop of l_tbl_table_test_retrieve.
How to use FORALL to insert data into a table when values are not in the given type?
CREATE OR REPLACE PACKAGE test_FORALL AS
PROCEDURE pr_test_FORALL;
END test_FORALL;
CREATE OR REPLACE PACKAGE BODY test_FORALL AS
PROCEDURE pr_test_FORALL IS
TYPE ty_tbl_table_test IS TABLE OF table_test%ROWTYPE INDEX BY BINARY_INTEGER;
l_tbl_table_test_retrieve ty_tbl_table_test;
l_tbl_table_test ty_tbl_table_test;
l_final_amt INTEGER;
l_reference_number VARCHAR2(100);
BEGIN
SELECT * BULK COLLECT
INTO l_tbl_table_test_retrieve
FROM table_test t1;
FOR i IN 1 .. l_tbl_table_test_retrieve.COUNT
LOOP
l_tbl_table_test(l_tbl_table_test.COUNT + 1) := l_tbl_table_test_retrieve(i);
l_final_amt := l_final_amt + 10;
l_reference_number := SYSDATE + l_tbl_table_test_retrieve(i).ID;
insert into some_other_table(fname, address,final_amt,ref_number)
values(l_tbl_table_test_retrieve(i).fname, l_tbl_table_test_retrieve(i).address,l_final_amt,l_reference_number);
END LOOP;
--I want to insert into some_other_table using FORALL. But,l_final_amt and l_reference_number variables
-- are not available in l_tbl_table_test_retrieve.
EXCEPTION
DBMS_OUTPUT.put_line('EXCEPTION occurred');
END;
END pr_test_FORALL;
END test_FORALL;
Use a cursor and add the fields into the rows returned by the cursor:
PROCEDURE pr_test_FORALL IS
DECLARE csrData AS CURSOR FOR
SELECT t1.*,
NULL AS COUNT_VAL,
NULL AS FINAL_AMT,
NULL AS REFERENCE_NUMBER
FROM TABLE_TEST t1;
TYPE ty_tbl_table_test IS
TABLE OF csrData%ROWTYPE -- Note: csrData%ROWTYPE
INDEX BY BINARY_INTEGER;
l_tbl ty_tbl_table_test;
l_final_amt INTEGER := 0;
l_reference_number VARCHAR2(100);
BEGIN
OPEN csrData
FETCH csrData
BULK COLLECT INTO l_tbl;
CLOSE csrData;
FOR i IN 1 .. l_tbl.COUNT LOOP
l_final_amt := l_final_amt + 10;
l_tbl(i).FINAL_AMT := l_final_amt;
l_tbl(i).REFERENCE_NUMBER := SYSDATE + l_tbl(i).ID;
END LOOP;
FORALL i IN l_tbl.FIRST..l_tbl.LAST
INSERT INTO SOME_OTHER_TABLE
(FNAME, ADDRESS, FINAL_AMT, REF_NUMBER)
VALUES
(l_tbl(i).FNAME,
l_tbl(i).ADDRESS,
l_tbl(i).FINAL_AMT,
l_tbl(i).REFERENCE_NUMBER);
EXCEPTION
DBMS_OUTPUT.put_line('EXCEPTION occurred');
END pr_test_FORALL;
You could convert the whole thing into two inserts of the below form into the required tables.
I see that in your code l_reference_number is defined as a VARCHAR2 variable but it sounds like a number. ( SYSDATE + some_number ) will yield a date type. It will be implicitly converted into a string based on your NLS_ settings when you assign it to a varchar2. I'm not sure what do you want to store in there as a "REFERENCE_NUMBER".
INSERT INTO some_other_table (
fname,
address,
final_amt,
ref_number
)
SELECT fname,
address,
10 * ROWNUM AS final_amt,
SYSDATE + id as reference_number
FROM table_test;

ORACLE APEX PL SQL Procedure Error

I keep getting a the error: success with compilation error. What am I doing wrong with my code? I tried it in sqlfiddle but I get an invalid SQL statement error. As far as I know, this is the correct syntax for PL/SQL
create or replace PROCEDURE PRC_CALC
(W_ORDERID_IN IN NUMBER)
AS
W_PARTSERVICEID VARCHAR2(10);
W_EXIST_FLAG NUMBER(1) :=0;
W_SUBTOTAL NUMBER(9) :=0;
W_TAX NUMBER(9) :=0.07;
W_DISCOUNT NUMBER(9) :=0;
W_TOTAL NUMBER(9) :=0;
BEGIN
SELECT COUNT(*)
INTO W_EXIST_FLAG
FROM tblJobOrders
WHERE fldOrderId = W_ORDERID_IN;
IF W_EXIST_FLAG = 1 THEN
CURSOR CUR_ORDERCHARGES IS
SELECT fldPartServiceId
FROM tblOrderCharges
WHERE fldOrderId = W_ORDERID_IN;
OPEN CUR_ORDERCHARGES;
LOOP
FETCH CUR_ORDERCHARGES
INTO W_PARTSERVICEID
EXIT WHEN CUR_ORDERCHARGES%NOTFOUND;
SELECT fldPartServiceAmount, fldDiscountPercent
INTO W_SUBTOTAL, W_DISCOUNT
FROM tblPartsServices
WHERE fldPartServiceId = W_PARTSERVICEID;
W_DISCOUNT := (W_SUBTOTAL*(W_DISCOUNT*.01));
W_TAX := (W_TOTAL*W_TAX);
W_TOTAL := W_SUBTOTAL - W_DISCOUNT;
W_TOTAL := W_TOTAL + W_TAX;
htp.prn('Your subtotal is: $' ||W_SUBTOTAL||'<br>');
htp.prn('Your Discount is: $' ||W_DISCOUNT||'<br>');
htp.prn('Your Tax is: $' ||W_TAX||'<br>');
htp.prn('Your Total is: $' ||W_TOTAL||'<br>');
END LOOP;
CLOSE CUR_ORDERCHARGES;
ELSE
htp.prn('The Order Id: '||W_ORDERID_IN||' does not exist in the database');
END IF;
END;
Your variable declarations need work
W_PARTSERVICEID VARCHAR2; should have a size such as W_PARTSERVICEID VARCHAR2(250);
Your number declarations will work but are better to specify a size as well
W_EXIST_FLAG NUMBER; should be W_EXIST_FLAG NUMBER(9);
W_EXIST_ORDER_FLAG is not declared and should be as well.
As a programming practice that goes beyond your question you should check that the values coming into the procedure and in the cursor are not null or zero.
The CURSOR CUR_ORDERCHARGES should be declared with the other declarations or put inside a new DECLARE BEGIN END block
and you are missing a semi colon when you FETCH the cursor, it should be
FETCH CUR_ORDERCHARGES
INTO W_PARTSERVICEID;
EXIT WHEN CUR_ORDERCHARGES%NOTFOUND;
The W_EXIST_ORDER_FLAG used in the first query is undefined. Perhaps, you meant W_EXIST_FLAG?

Oracle table type to nested table cast error

I declared table type and set a value in it with using loop. I am having an error while I was casting this t_table
DECLARE
TYPE t_row IS RECORD
(
id NUMBER,
description VARCHAR2(50)
);
TYPE t_table IS TABLE OF t_row;
l_tab t_table := t_table();
BEGIN
FOR i IN 1 .. 10 LOOP
l_tab.extend();
l_tab(l_tab.last).id := i;
l_tab(l_tab.last).description := 'Description for ' || i;
END LOOP;
SELECT * from TABLE(CAST(l_tab AS t_table));
END
Best regards
Why do you want to do a select onto the the type? You would use the the TABLE() and the CAST rather if you have a collection in a column stored in a table.
You could just loop through the table in your code. Example:
for i in l_tab.first .. l_tab.last
loop
dbms_output.put_line(l_tab(i).id||' '||l_tab(i).description);
end loop;
Since l_tab is of type t_table, there's no need for the cast. But that's not your problem.
Your problem is that you're trying to reference a PL/SQL type in SQL, which you simply can't do. You can either remove the select as #hol suggested or make the type a database object (which will allow SQL to access it):
CREATE OR REPLACE TYPE t_row AS OBJECT
(
id NUMBER,
description VARCHAR2 (50)
);
CREATE OR REPLACE TYPE t_table AS TABLE OF t_row;
DECLARE
l_tab t_table := t_table ();
BEGIN
FOR i IN 1 .. 10 LOOP
l_tab.EXTEND ();
l_tab (l_tab.LAST) := t_row (i, 'Description for ' || i);
END LOOP;
FOR r IN (SELECT * FROM TABLE (l_tab)) LOOP
DBMS_OUTPUT.put_line (r.id);
END LOOP;
END;
There is a second problem with the initial code, in that you are running a select without telling the code what to do with it. Unlike some other procedural SQL extensions, PL/SQL does not allow you to implicitly return a handle to a resultset (prior to 12c). You must either handle it directly or explicitly return a ref_cursor that points to it. The code above has been update to primitively handle the result of the query.

How to use function returning Oracle REF_CURSOR in a procedure

I have to write an Oracle procedure which should invoke an Oracle function returning REF_CURSOR. The function is declared like that
FUNCTION "IMPACTNET"."TF_CONVERTPARA" (PARASTRING IN NVARCHAR2) RETURN SYS_REFCURSOR
AS
c SYS_REFCURSOR;
BEGIN
OPEN c FOR
SELECT SUBSTR(element, 1, INSTR(element, '|') - 1) as key,
SUBSTR(element, INSTR(element, '|') + 1, 99999) as val
FROM (
SELECT REGEXP_SUBSTR(PARASTRING, '[^;]+', 1, LEVEL) element
FROM dual
CONNECT BY LEVEL < LENGTH(REGEXP_REPLACE(PARASTRING, '[^;]+')) + 1
);
RETURN c;
END;
Can you tell me what I need to write in order to invoke the function from within my procedure? I'd like to insert all the returned values (shaped a table with two columns) into a rational table.
Thank you in advance!
Something along the lines of this should work (obviously, I'm guessing about table names and column names and the exact logic that you're trying to implement)
CREATE PROCEDURE some_procedure_name
AS
l_rc SYS_REFCURSOR := impactnet.tf_convertpara( <<some string>> );
l_key VARCHAR2(100);
l_val VARCHAR2(100);
BEGIN
LOOP
FETCH l_rc
INTO l_key, l_val;
EXIT WHEN l_rc%notfound;
INSERT INTO some_table( key_column, val_column )
VALUES( l_key, l_val );
END LOOP;
END;
As Ollie points out, it would be more efficient to do a BULK COLLECT and a FORALL. If you're just dealing with a few thousand rows (since your function is just parsing the data in a delimited string, I'm assuming you expect relatively few rows to be returned), the performance difference is probably minimal. But if you're processing more data, the difference can be quite noticeable. Depending on the Oracle version and your specific requirements, you may be able to simplify the INSERT statement in the FORALL to insert a record rather than listing each column from the record individually.
CREATE PROCEDURE some_procedure_name
AS
TYPE key_val_rec
IS RECORD(
key VARCHAR2(100),
val VARCHAR2(100)
);
TYPE key_val_coll
IS TABLE OF key_val_rec;
l_rc SYS_REFCURSOR := impactnet.tf_convertpara( <<some string>> );
l_coll key_val_coll;
BEGIN
LOOP
FETCH l_rc
BULK COLLECT INTO l_coll
LIMIT 100;
EXIT WHEN l_coll.count = 0;
FORALL i IN l_coll.FIRST .. l_coll.LAST
INSERT INTO some_table( key_column, val_column )
VALUES( l_coll(i).key, l_coll(i).val );
END LOOP;
END;

Resources