ORA-06532: Subscript outside of limit error - sql

I am getting a ORA-06532 error in my pl/sql procedure. It has to do with my array, and it seems to be happening on the line that starts: "term_1 := ...". The query that selects into gets 7 records, so it should be the same amount as what I am calling for. I am a little new to the SQL array thing, so I may have missed something obvious. Any help is appreciated, thanks.
DECLARE
listOfTerms VC50_ARRAY;
term_1 varchar2(30);
term_2 varchar2(30);
term_3 varchar2(30);
term_4 varchar2(30);
term_5 varchar2(30);
term_6 varchar2(30);
term_7 varchar2(30);
BEGIN
SELECT apl.awdp_acad_terms
BULK COLLECT INTO listOfTerms
FROM fa_years fay
JOIN award_periods_ls apl
ON apl.award_periods_id = fay.award_periods_id
WHERE (SELECT b.awdp_fa_year as faYear
FROM award_periods_ls a
JOIN coll18_test.fa_years b ON a.award_periods_id = b.award_periods_id
WHERE awdp_acad_terms = v_ug_term) = fay.awdp_fa_year
ORDER BY apl.awdp_acad_terms DESC;
term_1 := listOFTerms(1);
term_2 := listOFTerms(2);
term_3 := listOFTerms(3);
term_4 := listOFTerms(4);
term_5 := listOFTerms(5);
term_6 := listOFTerms(6);
term_7 := listOFTerms(7);

I think you're over-complicating this. You code is equivalent to:
DECLARE
-- Declare the cursor explicitly.
cursor c_my_cursor is
SELECT apl.awdp_acad_terms
FROM fa_years fay
JOIN award_periods_ls apl
ON apl.award_periods_id = fay.award_periods_id
WHERE ( SELECT b.awdp_fa_year as faYear
FROM award_periods_ls a
JOIN coll18_test.fa_years b
ON a.award_periods_id = b.award_periods_id
WHERE awdp_acad_terms = v_ug_term ) = fay.awdp_fa_year
ORDER BY apl.awdp_acad_terms DESC;
-- Create a-user defined type that is the same as a single row in the cursor.
type t__listOfTerms is table of c_my_cursor%rowtype index by binary_integer;
-- Initialise a variable that is of data-type t__listofterms.
t_listofterms t__listofterms;
BEGIN
open c_my_cursor;
fetch c_my_cursor bulk collect into t_listofterms;
close c_my_cursor;
END;
You can then reference the items in your type by their index values so term_1 is the same as t_listofterms(1). There's no need create an additional variable with the same value; you can reference it in the same way so length(term1) and length(t_listofterms(1)) are also the same.
There's a lot of stuff out there about array processing but PSOUG is helpful as is the documentation.
Judging by your comment you may be referencing the collection explicitly, i.e. something := t_listofterms(7). This assumes that there is a specific number of rows. Bulk collect fills a collection from 1 to n, where n is the number of rows returned by the query. It's often better to loop through this if you want to do something with it rather than explicit referencing. Something like,
for i in t_listofterms.first .. t_listofterms.last loop
do_something;
end loop;

Related

Print multiple rows from select statement

I have this table :
| Pattern |
----------------------
|category |varchar|
|patternexpr |varchar|
For example in this table I can have a category ISBN and its pattern to recognize it.
I want to create a procedure which takes three arguments : a table T, one of its column C and a category. I want to print every rows in column C in T table which respect the pattern associated.
This is what I did (Updated with the correct answer):
CREATE OR REPLACE PROCEDURE Recognize(T varchar,C varchar,catego varchar)
IS
v_patt Pattern.CATEGOR%Type;
BEGIN
SELECT patternexpr INTO v_patt
FROM Pattern WHERE CATEGOR=catego;
FOR myrow IN (SELECT C FROM T WHERE REGEXP_LIKE(C, v_patt) LOOP
dbms_output.put_line(myrow.C);
END LOOP;
END;
/
How can I declare a cursor to print my result without knowing the value of my variable patt in the "DECLARE" place ? Should I add another declare and begin...end bloc after the first query ? What is the best way to do it ?
(I'm working on Oracle SGBD)
Use REF CURSOR to fetch records for this purpose.
CREATE OR REPLACE PROCEDURE Recognize(
T VARCHAR2,
C VARCHAR2,
catego VARCHAR2)
IS
v_patt Pattern.CATEGOR%Type;
v_cur_txt VARCHAR2(400);
TYPE cur_type
IS
REF
CURSOR;
v_cur cur_type;
v_c VARCHAR2(20);
BEGIN
SELECT patternexpr INTO v_patt FROM Pattern WHERE CATEGOR=catego;
v_cur_txt := 'SELECT '||C||' FROM '|| T ||' WHERE REGEXP_LIKE('||C||', '''||v_patt||''')';
OPEN v_cur FOR v_cur_txt;
LOOP
FETCH v_cur INTO v_c;
EXIT
WHEN v_cur%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(v_c);
END LOOP;
CLOSE v_cur;
END;
/
NOTE: : Include proper EXCEPTION handling in your code for NO_DATA_FOUND etc.Also as per Nicholas , make some validations by using dbms_assert package
In Oracle, you don't need an explicit cursor:
for myrow in (select c from t where regexp_like(c, patt) loop
dbms_output.put_line(myrow.c);
end loop;
I would call the pattern variable something like v_patt; that way, declared variables don't get confused with column names.

PL/SQL query with parameter

I am familiar with MSSQL and using a parameter within the query, but I am not sure how I would do this within PL/SQL.
DECLARE
LSITEID NUMBER := 100001;
BEGIN
SELECT * from invoicehead ih
JOIN sitemaster sm on sm.SITEIID = ih.SITEIID
JOIN invoiceline il on il.invoiceIID = ih.invoiceIID
WHERE
ih.StartDate BETWEEN '2015-12-01' AND '2016-03-07'
AND SITEIID IN ( LSITEID)
END;
Right now I am testing this within Pl/SQL. But essentially I would be passing in the query with the parameter from MSSQL Linked Server OPENQuery.
How I can run the above query in PL/SQL with the parameter?
There is plenty of other resource for finding an answer, e.g. here (Tutorialspoint) or specifically here (plsql-tutorial). But perhaps I have missed your point.
To not remain on merely citing links, your query could look like this:
DECLARE
LSITEID integer;
BEGIN
LSITEID := 100001;
-- dostuff
END;
Two things to note: First, in a declare part (as I have learnt it) you should avoid assigning values. Second, if you intend to pass in different parameters you could/should use a procedure.
In PL/SQL you just use the name of the argument. In the following example, the argument is P_VALUE, note select statement says where dummy = p_value.
DECLARE
FUNCTION dummycount (p_value IN DUAL.dummy%TYPE)
RETURN INTEGER
AS
l_ret INTEGER;
BEGIN
SELECT COUNT (*) c
INTO l_ret
FROM DUAL
WHERE dummy = p_value;
RETURN l_ret;
END dummycount;
BEGIN
DBMS_OUTPUT.put_line ('A: ' || dummycount (p_value => 'A'));
DBMS_OUTPUT.put_line ('X: ' || dummycount (p_value => 'X'));
END;
This results in the following output:
A: 0
X: 1

What is the difference between nested array and associative array?

There are two links
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/composites.htm#LNPLS99981 and
Purpose of using different types of PL/SQL collections in Oracle
by referring above two links i have two doubt
1.Which one is correct nested table?
2.If the oracle doc is correct what is the difference between nested table and associative array?
Here is another difference which is not that commonly known. You can compare two nested tables with = or <> but associative array you cannot.
DECLARE
TYPE associative_array IS TABLE OF INTEGER INDEX BY PLS_INTEGER;
a_var_associative_array associative_array;
b_var_associative_array associative_array;
TYPE nested_table IS TABLE OF INTEGER;
a_var_nested_table nested_table := nested_table(1, 2, 3, 4, 5);
b_var_nested_table nested_table := nested_table(5, 4, 3, 2, 1);
BEGIN
IF a_var_nested_table = b_var_nested_table THEN
-- Note, the different order of values!
DBMS_OUTPUT.PUT_LINE ( 'TRUE' );
ELSE
DBMS_OUTPUT.PUT_LINE ( 'FALSE' );
END IF;
-- IF a_var_associative_array = b_var_associative_array THEN -> gives you an error!
END;
When you work with nested tables you can also use Multiset Operators, Multiset Conditions and SET which are not available for associative arrays.
A nested table is just an array of n elements.
declare
type nested_table_of_integer is table of integer;
v_my_nested_table nested_table_of_integer;
begin
v_my_nested_table := nested_table_of_integer(); -- initialize
v_my_nested_table.extend(10); -- add 10 elements
v_my_nested_table(1) := 100;
v_my_nested_table(11) := 1000; -- ORA-06533: Subscript beyond count
end;
A nested table must be initialized as shown. It has zero elements at first. To add elements we use EXTEND. This nested table has 10 elements. They are indexed 1 to 10. Element 1 has the value 100. The others have value null. An access to a non-existent element, say the 11th element, raises an error.
An associative array on the other hand is an array of name/value pairs. Let's use numbers (pls_integer typically) for the naming:
declare
type associative_array_of_integer is table of integer index by pls_integer;
v_my_associative_array associative_array_of_integer;
begin
v_my_associative_array(1) := 100;
v_my_associative_array(11) := 1000;
v_my_associative_array(12) := v_my_associative_array(2); -- ORA-01403: no data found
end;
An associative array needs no initialization. It is empty and gets populated. Here we associate the element called 1 with the value 100 and the element with the name 11 with the value 1000. So there are two elements in the array. We get a no data found exception when we try to access a name that is not in the array.
We can also use strings for the names:
declare
type associative_array_of_integer is table of integer index by varchar2(100);
v_my_associative_array associative_array_of_integer;
begin
v_my_associative_array('age father') := 39;
v_my_associative_array('age mother') := 32;
v_my_associative_array('age daughter') := 11;
end;
You can use both collections to get table data, but you use them differently. The nested table has a count and you can just loop from 1 to count to access its elements:
declare
type nested_table_of_integer is table of integer;
v_my_nested_table nested_table_of_integer;
begin
v_my_nested_table := nested_table_of_integer(); -- initialize
select table_name bulk collect into v_my_nested_table from user_tables;
for i in 1 .. v_my_nested_table.count loop
dbms_output.put_line(v_my_nested_table(i));
end loop;
end;
The associative array however must be read from whatever happens to be the first index to the next and next and next using FIRST and NEXT.
declare
type associative_array_of_integer is table of integer index by pls_integer;
v_my_associative_array associative_array_of_integer;
i integer;
begin
select table_name bulk collect into v_my_associative_array from user_tables;
i := v_my_associative_array.first;
while i is not null loop
dbms_output.put_line(v_my_associative_array(i));
i := v_my_associative_array.next(i);
end loop;
end;
The "names" happen to be 1, 2, 3, etc. here (given thus by the bulk collection) and you could access v_my_associative_array(1) for instance. Later in your program, however, after some possible delete operations in the array, there may be gaps, so you don't know whether an element named 1 exists and whether the element before element 4 happens to be element 3. As with bulk collect the "names" for the elements have no meaning you would not really use them, but go instead through the chain as shown.

Oracle PL SQL: Comparing ref cursor results returned by two stored procs

I was given a stored proc which generates an open cursor which is passed as output to a reporting tool. I re-wrote this stored proc to improve performance. What I'd like to do is to show that the two result sets are the same for a given set of input parameters.
Something that is the equivalent of:
select * from CURSOR_NEW
minus
select * from CURSOR_OLD
union all
select * from CURSOR_OLD
minus
select * from CURSOR_NEW
Each cursor returns several dozen columns from a large subset of tables. Each row has an id value, and a long list of other column values for that id. I would want to check:
Both cursors are returning the same set of ids (I already checked this)
Both cursors have the same list of values for each id they have in common
If it was just one or two columns, I could concatenate them and find a hash and then sum it up over the cursor. Or another way might be to create a parent program that inserted the cursor results into a global temp table and compared the results. But since it's several dozen columns I'm trying to find a less brute force approach to doing the comparison.
Also it would be nice if the solution was scalable for other situations that involved different cursors, so it wouldn't have to be manually re-written each time, since this is a situation I'm running into more often.
I figured out a way to do this. It was a lot more complicated than I expected. I ended up using some DBMS_SQL procedures that allow converting REFCURSORs to defined cursors. Oracle has documentation on it here:
http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/dynamic.htm#LNPLS00001
After that I concatenated the row values into a string and printed the hash. For bigger cursors, I will change concat_col_vals to use a CLOB to prevent it from overflowing.
p_testCursors returns a simple refcursor for example purposes.
declare
cx_1 sys_refcursor;
c NUMBER;
desctab DBMS_SQL.DESC_TAB;
colcnt NUMBER;
stringvar VARCHAR2(4000);
numvar NUMBER;
datevar DATE;
concat_col_vals varchar2(4000);
col_hash number;
h raw(32767);
n number;
BEGIN
p_testCursors(cx_1);
c := DBMS_SQL.TO_CURSOR_NUMBER(cx_1);
DBMS_SQL.DESCRIBE_COLUMNS(c, colcnt, desctab);
-- Define columns:
FOR i IN 1 .. colcnt LOOP
IF desctab(i).col_type = 2 THEN
DBMS_SQL.DEFINE_COLUMN(c, i, numvar);
ELSIF desctab(i).col_type = 12 THEN
DBMS_SQL.DEFINE_COLUMN(c, i, datevar);
-- statements
ELSE
DBMS_SQL.DEFINE_COLUMN(c, i, stringvar, 4000);
END IF;
END LOOP;
-- Fetch rows with DBMS_SQL package:
WHILE DBMS_SQL.FETCH_ROWS(c) > 0 LOOP
concat_col_vals := '~';
FOR i IN 1 .. colcnt LOOP
IF (desctab(i).col_type = 1) THEN
DBMS_SQL.COLUMN_VALUE(c, i, stringvar);
--Dbms_Output.Put_Line(stringvar);
concat_col_vals := concat_col_vals || '~' || stringvar;
ELSIF (desctab(i).col_type = 2) THEN
DBMS_SQL.COLUMN_VALUE(c, i, numvar);
--Dbms_Output.Put_Line(numvar);
concat_col_vals := concat_col_vals || '~' || to_char(numvar);
ELSIF (desctab(i).col_type = 12) THEN
DBMS_SQL.COLUMN_VALUE(c, i, datevar);
--Dbms_Output.Put_Line(datevar);
concat_col_vals := concat_col_vals || '~' || to_char(datevar);
-- statements
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE(concat_col_vals);
col_hash := DBMS_UTILITY.GET_SQL_HASH(concat_col_vals, h, n);
DBMS_OUTPUT.PUT_LINE('Return Value: ' || TO_CHAR(col_hash));
DBMS_OUTPUT.PUT_LINE('Hash: ' || h);
END LOOP;
DBMS_SQL.CLOSE_CURSOR(c);
END;
/
This is not easy task for Oracle.
Very good article you can find on dba-oracle web:
Sql patterns symmetric diff
and Convert set to join sql parameter
If you need it often, you can:
add "hash column" and fill it always with insert using trigger, or
for each table in cursor output get unique value (create unique index) and compare only this column wiht anijoin
and you can find other possibilities in article.

Looping on values, creating dynamic query and adding to result set

I have the following problem. I am an experienced Java programmer but am a bit of a n00b at SQL and PL/SQL.
I need to do the following.
1 Pass in a few arrays and some other variables into a procedure
2 Loop on the values in the arrays (they all have the same number of items) and dynamically create an SQL statement
3 Run this statement and add it to the result set (which is an OUT parameter of the procedure)
I already have experience of creating an SQL query on the fly, running it and adding the result to a result set (which is a REF CURSOR) but I'm not sure how I'd loop and add the results of each call to the query to the same result set. I'm not even sure if this is possible.
Here's what I have so far (code edited for simplicity). I know it's wrong because I'm just replacing the contents of the RESULT_SET with the most recent query result (and this is being confirmed in the Java which is calling this procedure).
Any and all help would be greatly appreciated.
TYPE REF_CURSOR IS REF CURSOR;
PROCEDURE GET_DATA_FASTER(in_seq_numbers IN seq_numbers_array, in_values IN text_array, in_items IN text_array, list IN VARCHAR2, RESULT_SET OUT REF_CURSOR) AS
query_str VARCHAR2(4000);
seq_number NUMBER;
the_value VARCHAR2(10);
the_item VARCHAR2(10);
BEGIN
FOR i IN 1..in_seq_numbers.COUNT
LOOP
seq_number := in_seq_numbers(i);
the_value := trim(in_values(i));
the_item := trim(in_items(i));
query_str := 'SELECT distinct '||seq_number||' as seq, value, item
FROM my_table ai';
query_str := query_str || '
WHERE ai.value = '''||the_value||''' AND ai.item = '''||the_item||'''
AND ai.param = ''BOOK''
AND ai.prod in (' || list || ');
OPEN RESULT_SET FOR query_str;
END LOOP;
EXCEPTION WHEN OTHERS THEN
RAISE;
END GET_DATA_FASTER;
A pipelined table function seems a better fit for what you want, especially if all you're doing is retrieving data. See http://www.oracle-base.com/articles/misc/pipelined-table-functions.php
What you do is create a type for your output row. So in your case you would create an object such as
CREATE TYPE get_data_faster_row AS OBJECT(
seq NUMBER(15,2),
value VARCHAR2(10),
item VARCHAR2(10)
);
Then create a table type which is a table made up of your row type above
CREATE TYPE get_data_faster_data IS TABLE OF get_data_faster_row;
Then create your table function that returns the data in a pipelined manner. Pipelined in Oracle is a bit like a yield return in .net (not sure if you're familiar with that). You find all of the rows that you want and "pipe" them out one at a time in a loop. When your function completes the table that's returned consists of all the rows you piped out.
CREATE FUNCTION Get_Data_Faster(params) RETURN get_data_faster_data PIPELINED AS
BEGIN
-- Iterate through your parameters
--Iterate through the results of the select using
-- the current parameters. You'll probably need a
-- cursor for this
PIPE ROW(get_data_faster_row(seq, value, item));
LOOP;
LOOP;
END;
EDIT: Following Alex's comment below, you need something like this. I haven't been able to test this but it should get you started:
CREATE FUNCTION Get_Data_Faster(in_seq_numbers IN seq_numbers_array, in_values IN text_array, in_items IN text_array, list IN VARCHAR2) RETURN get_data_faster_data PIPELINED AS
TYPE r_cursor IS REF CURSOR;
query_results r_cursor;
results_out get_data_faster_row := get_data_faster_row(NULL, NULL, NULL);
query_str VARCHAR2(4000);
seq_number NUMBER;
the_value VARCHAR2(10);
the_item VARCHAR2(10);
BEGIN
FOR i IN 1..in_seq_number.COUNT
LOOP
seq_number := in_seq_numbers(i);
the_value := trim(in_values(i));
the_item := trim(in_items(i));
query_str := 'SELECT distinct '||seq_number||' as seq, value, item
FROM my_table ai';
query_str := query_str || '
WHERE ai.value = '''||the_value||''' AND ai.item = '''||the_item||'''
AND ai.param = ''BOOK''
AND ai.prod in (' || list || ');
OPEN query_results FOR query_str;
LOOP
FETCH query_results INTO
results_out.seq,
results_out.value,
results_out.item;
EXIT WHEN query_results%NOTFOUND;
PIPE ROW(results_out);
END LOOP;
CLOSE query_results;
END LOOP;
END;
Extra info from Alex's comment below useful for the answer:
you can have multiple loops from different sources, and as long as the
data from each be put into the same object type, you can just keep
pumping them out with pipe row statements anywhere in the function.
The caller sees them as a table with the rows in the order you pipe
them. Rather than call a procedure and get a result set as an output
parameter, you can query as select seq, value, item from
table(package.get_data_faster(a, b, c, d)), and of course you can
still have an order by clause if the order they're piped isn't what
you want.