Oracle SQL dynamic nr of FOR LOOP iterations - sql

I would like to run the FOR LOOP in Oracle based on a parameter that is dynamically populated. Please see, how the code could look like:
declare
idx number := (select max(field_name) from table_name);
begin
for i in 1..idx loop
dbms_output.put_line (i);
end loop;
end;
So basically if the select max(field_name) from table_name returns for example 10, the loop should be run 10 times (for i in 1..10 loop).

Assuming that field_name is an integer, you only need to fetch the max value in the right way:
declare
idx number;
begin
select max(field_name)
into idx
from table_name;
if idx is not null then -- to handle the case where the table is empty
for i in 1..idx loop
dbms_output.put_line (i);
end loop;
end if;
end;
or, without the IF:
declare
idx number;
begin
select nvl(max(field_name), 0)
into idx
from table_name;
for i in 1..idx loop
dbms_output.put_line (i);
end loop;
end;

Related

Return SQL Array from string [duplicate]

I'd like to create an in-memory array variable that can be used in my PL/SQL code. I can't find any collections in Oracle PL/SQL that uses pure memory, they all seem to be associated with tables. I'm looking to do something like this in my PL/SQL (C# syntax):
string[] arrayvalues = new string[3] {"Matt", "Joanne", "Robert"};
Edit:
Oracle: 9i
You can use VARRAY for a fixed-size array:
declare
type array_t is varray(3) of varchar2(10);
array array_t := array_t('Matt', 'Joanne', 'Robert');
begin
for i in 1..array.count loop
dbms_output.put_line(array(i));
end loop;
end;
Or TABLE for an unbounded array:
...
type array_t is table of varchar2(10);
...
The word "table" here has nothing to do with database tables, confusingly. Both methods create in-memory arrays.
With either of these you need to both initialise and extend the collection before adding elements:
declare
type array_t is varray(3) of varchar2(10);
array array_t := array_t(); -- Initialise it
begin
for i in 1..3 loop
array.extend(); -- Extend it
array(i) := 'x';
end loop;
end;
The first index is 1 not 0.
You could just declare a DBMS_SQL.VARCHAR2_TABLE to hold an in-memory variable length array indexed by a BINARY_INTEGER:
DECLARE
name_array dbms_sql.varchar2_table;
BEGIN
name_array(1) := 'Tim';
name_array(2) := 'Daisy';
name_array(3) := 'Mike';
name_array(4) := 'Marsha';
--
FOR i IN name_array.FIRST .. name_array.LAST
LOOP
-- Do something
END LOOP;
END;
You could use an associative array (used to be called PL/SQL tables) as they are an in-memory array.
DECLARE
TYPE employee_arraytype IS TABLE OF employee%ROWTYPE
INDEX BY PLS_INTEGER;
employee_array employee_arraytype;
BEGIN
SELECT *
BULK COLLECT INTO employee_array
FROM employee
WHERE department = 10;
--
FOR i IN employee_array.FIRST .. employee_array.LAST
LOOP
-- Do something
END LOOP;
END;
The associative array can hold any make up of record types.
Hope it helps,
Ollie.
You can also use an oracle defined collection
DECLARE
arrayvalues sys.odcivarchar2list;
BEGIN
arrayvalues := sys.odcivarchar2list('Matt','Joanne','Robert');
FOR x IN ( SELECT m.column_value m_value
FROM table(arrayvalues) m )
LOOP
dbms_output.put_line (x.m_value||' is a good pal');
END LOOP;
END;
I would use in-memory array. But with the .COUNT improvement suggested by uziberia:
DECLARE
TYPE t_people IS TABLE OF varchar2(10) INDEX BY PLS_INTEGER;
arrayvalues t_people;
BEGIN
SELECT *
BULK COLLECT INTO arrayvalues
FROM (select 'Matt' m_value from dual union all
select 'Joanne' from dual union all
select 'Robert' from dual
)
;
--
FOR i IN 1 .. arrayvalues.COUNT
LOOP
dbms_output.put_line(arrayvalues(i)||' is my friend');
END LOOP;
END;
Another solution would be to use a Hashmap like #Jchomel did here.
NB:
With Oracle 12c you can even query arrays directly now!
Another solution is to use an Oracle Collection as a Hashmap:
declare
-- create a type for your "Array" - it can be of any kind, record might be useful
type hash_map is table of varchar2(1000) index by varchar2(30);
my_hmap hash_map ;
-- i will be your iterator: it must be of the index's type
i varchar2(30);
begin
my_hmap('a') := 'apple';
my_hmap('b') := 'box';
my_hmap('c') := 'crow';
-- then how you use it:
dbms_output.put_line (my_hmap('c')) ;
-- or to loop on every element - it's a "collection"
i := my_hmap.FIRST;
while (i is not null) loop
dbms_output.put_line(my_hmap(i));
i := my_hmap.NEXT(i);
end loop;
end;
Sample programs as follows and provided on link also https://oracle-concepts-learning.blogspot.com/
plsql table or associated array.
DECLARE
TYPE salary IS TABLE OF NUMBER INDEX BY VARCHAR2(20);
salary_list salary;
name VARCHAR2(20);
BEGIN
-- adding elements to the table
salary_list('Rajnish') := 62000; salary_list('Minakshi') := 75000;
salary_list('Martin') := 100000; salary_list('James') := 78000;
-- printing the table name := salary_list.FIRST; WHILE name IS NOT null
LOOP
dbms_output.put_line ('Salary of ' || name || ' is ' ||
TO_CHAR(salary_list(name)));
name := salary_list.NEXT(name);
END LOOP;
END;
/
Using varray is about the quickest way to duplicate the C# code that I have found without using a table.
Declare your public array type to be use in script
type t_array is varray(10) of varchar2(60);
This is the function you need to call - simply finds the values in the string passed in using a comma delimiter
function ConvertToArray(p_list IN VARCHAR2)
RETURN t_array
AS
myEmailArray t_array := t_array(); --init empty array
l_string varchar2(1000) := p_list || ','; - (list coming into function adding final comma)
l_comma_idx integer;
l_index integer := 1;
l_arr_idx integer := 1;
l_email varchar2(60);
BEGIN
LOOP
l_comma_idx := INSTR(l_string, ',', l_index);
EXIT WHEN l_comma_idx = 0;
l_email:= SUBSTR(l_string, l_index, l_comma_idx - l_index);
dbms_output.put_line(l_arr_idx || ' - ' || l_email);
myEmailArray.extend;
myEmailArray(l_arr_idx) := l_email;
l_index := l_comma_idx + 1;
l_arr_idx := l_arr_idx + 1;
END LOOP;
for i in 1..myEmailArray.count loop
dbms_output.put_line(myEmailArray(i));
end loop;
dbms_output.put_line('return count ' || myEmailArray.count);
RETURN myEmailArray;
--exception
--when others then
--do something
end ConvertToArray;
Finally Declare a local variable, call the function and loop through what is returned
l_array t_array;
l_Array := ConvertToArray('email1#gmail.com,email2#gmail.com,email3#gmail.com');
for idx in 1 .. l_array.count
loop
l_EmailTo := Trim(replace(l_arrayXX(idx),'"',''));
if nvl(l_EmailTo,'#') = '#' then
dbms_output.put_line('Empty: l_EmailTo:' || to_char(idx) || l_EmailTo);
else
dbms_output.put_line
( 'Email ' || to_char(idx) ||
' of array contains: ' ||
l_EmailTo
);
end if;
end loop;

Inserting values into table of records type

I am creating a procedure and I want to store multiple values into table of records type and I am trying to insert values by cursor but I get this errors :
Error(14,7): PL/SQL: Statement ignored
Error(14,12): PLS-00306: wrong number or types of arguments in call to
'+'
Error(15,7): PL/SQL: Statement ignored
Error(15,12): PLS-00382: expression is of wrong type
The lines that are mentioned in errors are these two :
n := n+1;
ulaz(n) := bank_id_rec(tmp_row.bank_id);
create or replace PROCEDURE BULK_STATUS_JOB
IS
CURSOR tmp_cursor
IS
SELECT bank_id FROM mdm_tbank_customer;
n INTEGER :=0;
ulaz bank_id_tab;
izlaz bank_service_status_tab;
rec itf_return_rec;
BEGIN
OPEN tmp_cursor;
LOOP
FOR n in tmp_cursor LOOP
n := n+1;
ulaz(n) := bank_id_rec(tmp_row.bank_id);
END LOOP;
EXIT
WHEN tmp_cursor%notfound;
END LOOP;
rec := mdm_tbank_itf_sb.get_tbank_service_status_bulk(ulaz, izlaz);
FOR i IN izlaz.first..izlaz.last
LOOP
DBMS_OUTPUT.PUT_LINE(ulaz(i).bank_id);
DBMS_OUTPUT.PUT_LINE(izlaz(i).bank_id || ': '||izlaz(i).service_status);
END LOOP;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line(SQLERRM);
IF tmp_cursor%ISOPEN THEN
CLOSE tmp_cursor;
END IF;
END BULK_STATUS_JOB;
You have an issue in
FOR n in tmp_cursor LOOP
n := n+1;
You have used the same name for loop identifier and local variable but when it is used in the scope of the loop, n represents tmp_cursor. so
n := n+1 represents tmp_cursor := tmp_cursor + 1; which is invalid.
So please change the identifier to some other name (let's say nn) and use it all over the loop as follows.
FOR nn in tmp_cursor LOOP -- nn represents loop identifier
n := n+1; -- n represents your local variable declared by you
Also, there are few other issues which seem unnecessary, see the comments in the following final code
create or replace PROCEDURE BULK_STATUS_JOB
IS
CURSOR tmp_cursor
IS
SELECT bank_id FROM mdm_tbank_customer;
n INTEGER :=0;
ulaz bank_id_tab;
izlaz bank_service_status_tab;
rec itf_return_rec;
BEGIN
--OPEN tmp_cursor; -- not needed
--LOOP -- not needed
FOR nn in tmp_cursor LOOP -- changed loop variable name to nn
n := n+1;
ulaz(n) := bank_id_rec(nn.bank_id); --- used nn.bank_id
END LOOP;
--EXIT -- not needed
--WHEN tmp_cursor%notfound; -- not needed
--END LOOP; -- not needed
rec := mdm_tbank_itf_sb.get_tbank_service_status_bulk(ulaz, izlaz);
FOR i IN izlaz.first..izlaz.last
LOOP
DBMS_OUTPUT.PUT_LINE(ulaz(i).bank_id);
DBMS_OUTPUT.PUT_LINE(izlaz(i).bank_id || ': '||izlaz(i).service_status);
END LOOP;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line(SQLERRM);
IF tmp_cursor%ISOPEN THEN
CLOSE tmp_cursor;
END IF;
END BULK_STATUS_JOB;
Cheers!!

run a procedure in while loop

I have this stored proc :
begin
Sp_Racf_Test;
end;
I don't want to edit anything inside this proc.
I want to run a loop statement where it should run the proc Sp_Racf_Test until
a column RACF_ID in table tem_joins is null. I mean the loop of running stored procedure should stop when there are no null values in the column RACF_ID of table tem_joins.
Please suggest a query
Try the below one:
declare
v_count number := 1;
begin
while v_count > 0 loop
Select count(*) into v_count from tem_joins
where racf_id is null;
if v_count > 0 then
Sp_Racf_Test;
else
exit;
end if;
end loop;
end;

PL SQL Cursor For Loop: add up values in same variable and output the summed total

I'm trying to calculate the GPA within a function that accepts a studentID as an input. My issue is that the variable lv_gpa_calc isn't adding to itself when the loop works through the cursor set. I added the DBMS_OUTPUT.PUT_LINE to make sure that it's working through the cursor set correctly and that prints to the screen the correct individual row values of what lv_gpa_calc should be, but when it gets returned in the function in a SQL block, it isn't adding all of those values together. Can you not set a variable to itself within a CURSOR FOR LOOP?
Update: initializing the lv_gpa_calc fixed the problem where the variable value wasn't adding to itself.
CREATE OR REPLACE
FUNCTION CALCULATE_GPA
(p_studentID IN number)
RETURN NUMBER
IS
CURSOR cur_gpa IS
SELECT grade, grade_value, credit_hours
FROM grade
JOIN enrollment USING (Grade)
JOIN section USING (term_code, subject_code, course_number, section)
JOIN course USING (subject_code, course_number)
WHERE student_ID = p_studentID;
lv_gpa_calc NUMBER(4,2):=0;
BEGIN
FOR rec_gpa IN cur_gpa LOOP
lv_gpa_calc:= lv_gpa_calc + ((rec_gpa.grade_value * rec_gpa.credit_hours)/rec_gpa.credit_hours);
DBMS_OUTPUT.PUT_LINE(lv_gpa_calc);
END LOOP;
RETURN lv_gpa_calc;
END CALCULATE_GPA;
The problem in your code is that variable lv_gpa_calc is not initialized. Adding whatever to NULL will result as NULL.
Simplified working test case:
--DROP TABLE my_numbers;
CREATE TABLE my_numbers (
id NUMBER
);
/
BEGIN
FOR l_i IN 1..10 LOOP
INSERT INTO my_numbers VALUES (DBMS_RANDOM.RANDOM);
END LOOP;
COMMIT;
END;
/
SELECT * FROM my_numbers;
/
DECLARE
CURSOR cur IS
SELECT id
FROM my_numbers;
l_sum NUMBER(10) := 0;
BEGIN
FOR rec IN cur LOOP
l_sum := l_sum + rec.id;
DBMS_OUTPUT.PUT_LINE('l_sum = ' || l_sum);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Sum = ' || l_sum);
END;
/
Important line is:
l_sum NUMBER(10) := 0;
Without initialization :=0 it won't work.

A procedure to Reverse a String in PL/SQL

I just started learning PL/SQL and I'm not sure how to create a procedure. The logic seems about right but I think there's some syntactical mistake in the first line. Here's my code:-
CREATE OR REPLACE PROCEDURE ReverseOf(input IN varchar2(50)) IS
DECLARE
reverse varchar2(50);
BEGIN
FOR i in reverse 1..length(input) LOOP
reverse := reverse||''||substr(input, i, 1);
END LOOP;
dbms_output.put_line(reverse);
END;
/
Two things - you shouldn't specify the datatype size in procedure's/function's parameter list and you do not need the DECLARE keyword. Try this:
CREATE OR REPLACE PROCEDURE ReverseOf(input IN varchar2) IS
rev varchar2(50):='';
BEGIN
FOR i in reverse 1..length(input) LOOP
rev := rev||substr(input, i, 1);
END LOOP;
dbms_output.put_line(rev);
END;
Try it without PL/SQL!
WITH
params AS
(SELECT 'supercalifragilisticexpialidocious' phrase FROM dual),
WordReverse (inpt, outpt) AS
(SELECT phrase inpt, CAST(NULL AS varchar2(4000)) outpt FROM params
UNION ALL
SELECT substr(inpt,2,LENGTH(inpt)-1), substr(inpt,1,1) || outpt
FROM wordReverse
WHERE LENGTH(inpt) > 0
)
SELECT phrase,outpt AS reversed FROM wordReverse, params
WHERE LENGTH(outpt) = LENGTH(phrase) ;
PHRASE REVERSED
---------------------------------- -----------------------------------
supercalifragilisticexpialidocious suoicodilaipxecitsiligarfilacrepus
Citation: http://rdbms-insight.com/wp/?p=94
Another solution reverse string minimizing loop count
DECLARE
v_str VARCHAR2(100) DEFAULT 'MYSTRING';
v_len NUMBER;
v_left VARCHAR2(100);
v_right VARCHAR2(100);
BEGIN
v_len := LENGTH(v_str)/2;
FOR rec IN 1..v_len
LOOP
v_left := substr(v_str,rec,1) || v_left;
IF rec * 2 <= LENGTH(v_str) THEN
v_right := v_right || substr(v_str,-rec,1);
END IF;
END LOOP;
v_str := v_right || v_left;
dbms_output.put_line(v_str);
END;
set serveroutput on
declare
str1 varchar2(30);
len number(3);
str2 varchar2(30);
i number(3);
begin
str1:='&str1';
len:=length(str1);
for i in reverse 1..len
loop
str2:=str2 || substr(str1,i,1);
end loop;
dbms_output.put_line('Reverse string is: '||str2);
end;
/
create or replace procedure ap_reverse_number(input_no VARCHAR2) as
output_no VARCHAR2(100);
begin
for i in 1 .. length(input_no) loop
output_no := output_no || '' ||
substr(input_no, (length(input_no) - i + 1), 1);
end loop;
dbms_output.put_line('Input no. is :' || input_no);
dbms_output.put_line('Output no. is:' || output_no);
end;
This should do the job correctly.
Try this one line statement to reverse the string in sql
with a as (select 'brahma' k from dual)
select listagg(substr(k,length(k)-level+1,1),'') within group (order by 1) b from a connect by level<length(k)+1
Try this one line query to reverse a string or a number.
select reverse('HelloWorld') from dual;
declare
name varchar2(20):='&name';
rname varchar2(20);
begin
for i in reverse 1..length(name)
loop
rname:=rname||substr(name,i,1);
end loop;
display(rname);
end;