PLS-00497: cannot mix between single row and multi-row (BULK) in INTO list - oracle

I have created a procure to display the data in two table using BULK COLLECT, but i keep getting this error.
PLS-00497: cannot mix between single row and multi-row (BULK) in INTO list
However it works if i remove the BULK COLLECT and include a where clause in the statement.
create or replace PROCEDURE sktReport IS
TYPE inventory_table_type is RECORD (
v_WH_ID INVENTORY.WH_ID%TYPE,
v_wa_Product_quantity_id Product_quantity.ST_ID%TYPE);
v_inventory_table inventory_table_type;
BEGIN
SELECT INVENTORY.WH_ID, Product_quantity.ST_ID,
BULK COLLECT INTO
v_inventory_table.v_WH_ID,
v_inventory_table.v_wa_Product_quantity_id,
FROM INVENTORY
INNER JOIN Product_quantity
ON Product_quantity.ST_ID = INVENTORY.ST_ID;
FOR i IN v_inventory_table.v_WH_ID..v_inventory_table.v_WH_ID
LOOP
DBMS_OUTPUT.PUT_LINE ('ID : ' || v_inventory_table.v_WH_ID
|| ' quantity ID : ' || v_inventory_table.v_in_Product_quantity_id);
END LOOP;
END;

Here's a simple showcase, I've just written that might help you :)
SET SERVEROUTPUT ON;
DECLARE
TYPE t_some_type IS RECORD (
the_id NUMBER
,the_name VARCHAR2(1)
);
TYPE t_some_type_tab IS TABLE OF t_some_type;
lt_some_record t_some_type;
lt_some_array t_some_type_tab := NEW t_some_type_tab();
BEGIN
WITH some_values AS (
SELECT
DECODE(LEVEL,1,1,2,2,3,3,4,4) AS the_id
,DECODE(LEVEL,1,'A',2,'B',3,'C',4,'D') AS the_name
FROM
dual
CONNECT BY LEVEL < 5
)
SELECT
sv.the_id
,sv.the_name
BULK COLLECT INTO -- use this to select into an array/collection type variable
lt_some_array
FROM
some_values sv;
DBMS_OUTPUT.PUT_LINE(lt_some_array.COUNT);
WITH some_values AS (
SELECT
DECODE(LEVEL,1,1,2,2,3,3,4,4) AS the_id
,DECODE(LEVEL,1,'A',2,'B',3,'C',4,'D') AS the_name
FROM
dual
CONNECT BY LEVEL < 5
)
SELECT
sv.the_id
,sv.the_name
INTO -- use this to select into a regular variables
lt_some_record.the_id
,lt_some_record.the_name
FROM
some_values sv
WHERE
sv.the_id = 1;
DBMS_OUTPUT.PUT_LINE(lt_some_record.the_id||': '||lt_some_record.the_name);
-- you can also insert such record into your array type variable
lt_some_array := NEW t_some_type_tab();
lt_some_array.EXTEND; -- extend the array type variable (so it could store one more element, than now - which was 0)
lt_some_array(lt_some_array.LAST) := lt_some_record; -- assign the first element of array type variable
DBMS_OUTPUT.PUT_LINE(lt_some_array.COUNT||' '||lt_some_array(lt_some_array.LAST).the_id||': '||lt_some_array(lt_some_array.LAST).the_name);
END;
/
Also, since you want to iterate through your results, you can just use cursor (implicit or explicit) e.g.
DECLARE
-- cursor declaration
CURSOR c_some_cursor IS
WITH some_values AS (
SELECT
DECODE(LEVEL,1,1,2,2,3,3,4,4) AS the_id
,DECODE(LEVEL,1,'A',2,'B',3,'C',4,'D') AS the_name
FROM
dual
CONNECT BY LEVEL < 5
)
SELECT
sv.the_id
,sv.the_name
FROM
some_values sv;
BEGIN
-- using explicit, earlier declared cursor
FOR c_val IN c_some_cursor
LOOP
DBMS_OUTPUT.PUT_LINE(c_val.the_id||': '||c_val.the_name);
END LOOP;
-- using implicit, not declared cursor
FOR c_val IN (
WITH some_values AS (
SELECT
DECODE(LEVEL,1,1,2,2,3,3,4,4) AS the_id
,DECODE(LEVEL,1,'A',2,'B',3,'C',4,'D') AS the_name
FROM
dual
CONNECT BY LEVEL < 5
)
SELECT
sv.the_id
,sv.the_name
FROM
some_values sv
)
LOOP
DBMS_OUTPUT.PUT_LINE(c_val.the_id||': '||c_val.the_name);
END LOOP;
END;
/

Here i have demonstrated a simple example to replicate your scenario. Please see below code. This may help you out.
SET serveroutput ON;
DECLARE
TYPE AV_TEST
IS
RECORD
(
lv_att1 PLS_INTEGER,
lv_att2 PLS_INTEGER );
type av_test_tab
IS
TABLE OF av_test;
av_test_tab_av av_test_tab;
BEGIN
NULL;
SELECT LEVEL,
LEVEL+1 BULK COLLECT
INTO av_test_tab_av
FROM DUAL
CONNECT BY LEVEL < 10;
dbms_output.put_line(av_test_tab_av.count);
FOR I IN av_test_tab_av.FIRST..av_test_tab_av.LAST
LOOP
dbms_output.put_line('working fine '||av_test_tab_av(i).lv_att1||' '||av_test_tab_av(i).lv_att2);
END LOOP;
END;

Related

PL/SQL - pass query in for loop stored in variable

i have a scenario where i need to create a dynamic query with some if/else statements, i have prepared the query but unable to use this inside loop below is the snippet of what i am trying to acheive.
Query :
select user_name into username from table1 where user ='user1';
for(query)
Loop
Dbms_output.put_line('user name ' || user_name);
END Loop;
is this possible to use the vaiable in the for loop ?
Not really. Notice in the 19c PL/SQL Reference it says:
cursor
Name of an explicit cursor (not a cursor variable) that is not open when the cursor FOR LOOP is entered.
You have to code this the long way, by explicitly fetching the cursor into a record until you hit cursorname%notfound, e.g.
create or replace procedure cheese_report
( cheese_cur in sys_refcursor )
as
type cheese_detail is record
( name varchar2(15)
, region varchar2(30) );
cheese cheese_detail;
begin
loop
fetch cheese_cur into cheese;
dbms_output.put_line(cheese.name || ', ' || cheese.region);
exit when cheese_cur%notfound;
end loop;
close cheese_cur;
end;
Test:
declare
cheese sys_refcursor;
begin
open cheese for
select 'Cheddar', 'UK' from dual union all
select 'Gruyere', 'France' from dual union all
select 'Ossau Iraty', 'Spain' from dual union all
select 'Yarg', 'UK' from dual;
cheese_report(cheese);
end;
/
Cheddar, UK
Gruyere, France
Ossau Iraty, Spain
Yarg, UK
In Oracle 21c you can simplify this somewhat, though you still have to know the structure of the result set:
create or replace procedure cheese_report
( cheese_cur in sys_refcursor )
as
type cheese_detail is record
( cheese varchar2(15)
, region varchar2(30) );
begin
for r cheese_detail in values of cheese_cur
loop
dbms_output.put_line(r.cheese || ', ' || r.region);
end loop;
end;
You could parse an unknown ref cursor using dbms_sql to find the column names and types, but it's not straightforward as you have to do every processing step yourself. For an example of something similar, see www.williamrobertson.net/documents/refcursor-to-csv.shtml.

Oracle CAST MULTISET ORA-00902: invalid datatype

I'm trying to sort an Oracle PL/SQL collection (an associative array) using the approach presented here. I modified the example from the linked page in order to use an associative array, but I guess I'm having some casting issues.
Here it is my code:
DECLARE
TYPE TABLE_TYPE IS TABLE OF NUMBER INDEX BY VARCHAR2(10);
table_in TABLE_TYPE;
table_out TABLE_TYPE;
BEGIN
-- 1. Populating the collection with random numbers between 1 and 50
FOR i IN 1..9 LOOP
SELECT ROUND(DBMS_RANDOM.VALUE(1,50))
INTO table_in('key-'||i)
FROM DUAL;
END LOOP;
-- 2. Trying to order the collection -> throws ORA-00902: invalid datatype
SELECT CAST (MULTISET(
SELECT * FROM TABLE(table_in)
ORDER BY 2
) AS TABLE_TYPE
)
INTO table_out
FROM DUAL;
END;
What am I doing wrong?
You can't use associative array as a table in select, because that time is working SQL Engine and SQL Engine doesn't know what is associative array, SQL Engine can only works with Table Type, and you don't need first select (select from dual), you can do it via pl/sql engine, change it like this
....................
TYPE NumbersTableType IS TABLE OF NUMBER; -- it must be in global types, not in your local package
....................
DECLARE
table_in NumbersTableType := NumbersTableType();
table_out NumbersTableType;
BEGIN
-- 1. Populating the collection with random numbers between 1 and 50
FOR i IN 1..9 LOOP
table_in.Extend;
table_in(i):=ROUND(DBMS_RANDOM.VALUE(1,50));
END LOOP;
SELECT CAST (MULTISET(
SELECT * FROM TABLE(table_in)
ORDER BY 1
) AS NumbersTableType
)
INTO table_out
FROM DUAL;
END;
For sake of completeness I'll report here the trivial workaround I used to order a collection (index by varchar) in Oracle version before 12c. The solution just replaces the associative array collection with a custom Table type (in order to make it visible to the SQL Engine).
CREATE OR REPLACE TYPE MY_TABLE_TYPE_OBJ AS OBJECT (
THE_KEY VARCHAR2(10),
THE_VALUE NUMBER
);
/
CREATE OR REPLACE TYPE MY_TABLE_TYPE IS TABLE OF MY_TABLE_TYPE_OBJ;
/
DECLARE
my_key VARCHAR2(10);
table_in MY_TABLE_TYPE := MY_TABLE_TYPE();
table_out MY_TABLE_TYPE := MY_TABLE_TYPE();
BEGIN
-- Creating an unsorted collection
FOR i IN 1..9 LOOP
table_in.EXTEND;
table_in(i) := MY_TABLE_TYPE_OBJ(
'key-'||i,
ROUND(DBMS_RANDOM.VALUE(1,50))
);
END LOOP;
-- Sorting the collection
SELECT CAST (MULTISET(
SELECT * FROM TABLE(table_in)
ORDER BY 2
) AS MY_TABLE_TYPE
)
INTO table_out
FROM DUAL;
END;
Hope this helps.

Oracle lookup function in loop returns rowtype how to get fields from rowtype

I have a procedure that runs a select ( I tested that is good returns 56 records )
then when I run a cursor I want to pass 3 fields to a function ( see above ) that will
lookup/select a record from a table that contains 15 million records ( 10 years worth ).
It returns a rowtype that I want to then extract the fields from this rowtype record to
run an insert with both the records from the 1st select and the additional fields acquired
from the lookup function.
If I run the procedure the console prints out my test msgs but when I try to run
select * bulk collect into v_tab_proc_claim_recs from v_processed_claim;
it doesn't compile due to Error(97,65): PL/SQL: ORA-00942: table or view does not exist
as if either of these are not Tables.
Am I doing this right... how can I do it, why can't it see the table I'm trying to extract to ?
Should I do this some other way..
Thanks for any help/suggestions :)
The function is below....
create or replace function get_processed_claim_rec(
p_provider VARCHAR2,
p_rx VARCHAR2,
p_record_no NUMBER
)
return i_idb.processed_claim%rowtype
as
l_claim_record i_idb.processed_claim%rowtype;
begin
select * into l_claim_record from i_idb.processed_claim
where source_date = p_provider
AND rx = p_rx
AND rec_no = p_record_no;
return(l_claim_record);
end;
And the procedure is....
create or replace PROCEDURE import_mailer_data
AS
-------------------------------
/**
for the lookup table
**/
v_processed_claim i_idb.processed_claim%rowtype;
TYPE proc_claim_recs IS TABLE OF v_processed_claim%ROWTYPE INDEX BY PLS_INTEGER;
v_tab_proc_claim_recs proc_claim_recs;
--------------------------------
CURSOR myCursor
IS
SELECT *
from
(
SELECT
j.create_date as open_date,
case when (j.create_date < (sysdate - 20) )
then 'POD'
else 'REG'
end as priority,
c.division,
c.unit,
--p.refill as days_supply,
--p.din_name,
'CM_JOHN' as log_code,
c.first_name,
c.last_name,
--p.UNLISTED_compound,
--p.intervention_code,
--p.substitution,
--p.confirm,
c.PROVIDER,
c.rx,
c.DISPENSE_DATE,
c.DIN,
c.QTY,
c.DIN_COST_PAID,
c.DISP_FEE_PAID,
c.PAID_AMOUNT,
c.SOURCE_DATE,
c.RECORD_NO,
c.RELATIONSHIP,
c.INSURER_NO,
c.GROUP_NO,
c.CERTIFICATE,
c.BIRTH_DATE,
c.USER_ID,
--p.rej_code --v_seq_no
rank() over
(
partition by c.provider, c.rx, c.record_no Order by c.provider desc, c.rx desc
) as RNK
FROM AUDITCOLLECTIONS.MAILER_CLAIMS c,
AUDITCOLLECTIONS.MAILER_JOBS j
WHERE MAILER_JOB_DETAIL_ID IN
(SELECT MAILER_JOB_DETAIL_ID
FROM AUDITCOLLECTIONS.MAILER_JOB_DETAILS
WHERE MAILER_JOB_ID IN
( SELECT MAILER_JOB_ID FROM AUDITCOLLECTIONS.MAILER_JOBS
)
)
AND ( c.PROVIDER, c.rx, c.record_no ) NOT IN
( SELECT provider, rx, rec_no FROM AUDITCOLLECTIONS.COLLECTION_AUDIT_STAGING
)
AND j.create_date > (sysdate - 30)
AND c.provider = '2010500042'
) A_Latest
where A_Latest.RNK = 1;
BEGIN
v_report_id := audit_load.create_loaded_report(v_report_type_id);
FOR curRec IN myCursor
LOOP
BEGIN
dbms_output.put_line ('===>>>> PRINTING TEST1 = ');
v_processed_claim := get_processed_claim_rec(curRec.PROVIDER, curRec.RX, curRec.RECORD_NO);
select * bulk collect into v_tab_proc_claim_recs from v_processed_claim;
END LOOP;
audit_load.update_status_to_loaded(v_report_id);
END import_mailer_data;
You can do this:
FOR curRec IN myCursor
LOOP
v_processed_claim :=
get_processed_claim_rec(curRec.PROVIDER, curRec.RX, curRec.RECORD_NO);
v_tab_proc_claim_recs (v_tab_proc_claim_recs.COUNT+1) := v_processed_claim;
END LOOP;
Or simplify to:
FOR curRec IN myCursor
LOOP
v_tab_proc_claim_recs (v_tab_proc_claim_recs.COUNT+1) :=
get_processed_claim_rec(curRec.PROVIDER, curRec.RX, curRec.RECORD_NO);
END LOOP;

PL SQL : Create oracle record dynamically

I dont know if it is possible but I would like to do this in PL/SQL
Let's say I have a parameter in my procedure, a number : numberColumns.
Inside the procedure I would like to create a record :
TYPE arrayColumn IS RECORD (
column1 VARCHAR2(200),
column2 VARCHAR2(200)...
... as much à numberColumns value
....
);
ty
This can be achieved easily with with OBJECT type in Oracle. But this kind of architecture is not at all suggested. Hope this below solution helps.
CREATE OR REPLACE
PROCEDURE test_obj_form(
a NUMBER )
AS
lv_sql VARCHAR2(32676);
BEGIN
SELECT '('
||listagg(str,',') WITHIN GROUP (
ORDER BY lvl)
||')'
INTO lv_sql
FROM
(SELECT 1 dum,
'column'
||LEVEL
||' '
||'varchar2(200)' str,
level lvl
FROM dual
CONNECT BY LEVEL < A
ORDER BY LEVEL
)
GROUP BY dum;
EXECUTE IMMEDIATE 'CREATE OR REPLACE TYPE name_rec IS OBJECT '||lv_sql;
dbms_output.put_line(lv_sql);
END;
/
Rather than using a record, you could use a collection:
CREATE OR REPLACE TYPE stringlist IS TABLE OF VARCHAR2(4000);
/
Then do:
CREATE OR REPLACE PROCEDURE your_procedure(
number_columns IN INTEGER,
values OUT stringlist
)
IS
BEGIN
values := stringlist();
IF number_columns < 1 THEN
RETURN;
END IF;
values.EXTEND( number_columns );
FOR i IN 1 .. number_columns LOOP
values(i) := DBMS_RANDOM.STRING( 'X', 100 ); -- Assign some value
END LOOP;
END;
/
Otherwise, if you really want a record, then you will have to result to dynamic SQL.

Storing an entire column in a variable inside a stored procedure

I have a complex stored procedure inside a package. Inside this SP, I need to query a table to get all the data pertaining one column and then use this to check some other condition inside an "IF" statement.
Here is what I am doing:
--declare a variable to store the holidays
l_holidays MySchema. HolidayTable.DateColumn%TYPE
-- populate this variable
Select a.DateColumn into l_holidays
from MySchema. HolidayTable a;
-- using this variable inside an "IF" statement
IF (current_Date IN l_holidays)
THEN
-- do something
ELSE
-- do something
END IF;
Every time I run this, I get the following error
ORA-01422: exact fetch returns more than requested number of rows
I know this is because I am trying to populate the entire column using the "INTO" clause. But I don't know any other way of doing it.
Create a collection and use BULK COLLECT INTO:
CREATE PROCEDURE my_proc (
current_date IN MySchema.HolidayTable.DateColumn%TYPE
)
AS
TYPE date_tab IS TABLE OF MySchema.HolidayTable.DateColumn%TYPE;
l_holidays date_tab;
BEGIN
SELECT DateColumn
BULK COLLECT INTO l_holidays
FROM MySchema.HolidayTable;
IF (current_Date MEMBER OF l_holidays)
THEN
NULL; -- do something
ELSE
NULL; -- do something
END IF;
END;
Otherwise you can just test in the select:
CREATE PROCEDURE my_proc (
current_date IN MySchema.HolidayTable.DateColumn%TYPE
)
AS
has_date NUMBER(1,0);
BEGIN
SELECT CASE WHEN EXISTS ( SELECT 'X'
FROM MySchema.HolidayTable
WHERE DateColumn = Current_Date )
THEN 1
ELSE 0
END
INTO has_date
FROM DUAL;
IF has_date = 1
THEN
NULL; -- do something
ELSE
NULL; -- do something
END IF;
END;
Hello similarly you can use this query to fulfill your requirements
SET serveroutput ON;
SET sqlbl ON;
DECLARE
type l_holiday
IS
TABLE OF DATE;
tab_holiday l_holiday;
BEGIN
SELECT a.dt BULK COLLECT
INTO tab_holiday
FROM
(SELECT SYSDATE dt FROM DUAL
UNION
SELECT SYSDATE+1 dt FROM DUAL
UNION
SELECT SYSDATE+2 dt FROM DUAL
UNION
SELECT SYSDATE+3 FROM DUAL
)a;
IF tab_holiday.COUNT > 0 THEN
IF SYSDATE MEMBER OF tab_holiday THEN
dbms_output.put_line('yes working');
ELSE
dbms_output.put_line('awsme working');
END IF;
END IF;
END;

Resources