set serveroutput on;
declare
v_tab user_tables.table_name%TYPE;
begin
select table_name
into v_tab
from user_tables
where tablespace_name = 'EXAMPLE';
dbms_output.put_line('Table Names are : ' || v_tab);
exception
when too_many_rows then
dbms_output.put_line('More than 1 rows are fetched');
when others then
dbms_output.put_line('Other Exception occurred');
end;
/
--=============================================================================================
--simple for cursor
set serveroutput on;
declare
begin
for rec in (
select table_name
from user_tables
where tablespace_name = 'EXAMPLE')
loop
dbms_output.put_line(rec.table_name);
end loop;
end;
/
--===============================================================================================
--assigning data retrived from for cursor into collection
--1. Associate Arrays
set serveroutput on;
declare
--Associate arrays
TYPE ass_arr is table of user_tables.table_name %TYPE index by pls_integer;
ass_arr_obj ass_arr;
i number :=0;
begin
for rec in (
select table_name
from user_tables
where tablespace_name = 'EXAMPLE')
loop
ass_arr_obj(i):= rec.table_name;
i:=i+1;
end loop;
dbms_output.put_line('Table Names are :');
for j in ass_arr_obj.first.. ass_arr_obj.last
loop
dbms_output.put_line(ass_arr_obj(j));
end loop;
end;
/
2. Nested Tables
--Persistent collection - Can be stored in the databse and reused
CREATE OR REPLACE TYPE nes_tab is table of VARCHAR2(100);
declare
TYPE nes_tab is table of VARCHAR2(100);
nes_tab_val nes_tab := nes_tab(
'LOCATIONS',
'JOB_HISTORY',
'EMPLOYEES',
'JOBS',
'DEPARTMENTS',
'REGIONS');
begin
dbms_output.put_line('The table names are :');
for i in 1..nes_tab_val.count
loop
dbms_output.put_line(nes_tab_val(i));
end loop;
end;
/
3. VARRAYS
--Using cursors to fetch records by looping into a variable
set serveroutput on;
declare
v_tab user_tables.table_name%TYPE;
cursor tab_cur is
select table_name
from user_tables
where tablespace_name = 'EXAMPLE';
begin
open tab_cur;
loop
fetch tab_cur into v_tab;
exit when tab_cur%notfound;
dbms_output.put_line('Table Names are : ' || v_tab);
end loop;
close tab_cur;
exception
when too_many_rows then
dbms_output.put_line('More than 1 rows are fetched');
when others then
dbms_output.put_line('Other Exception occurred');
end;
/
--==================================================================================
--Using cursors with bulkcollect and collection
set serveroutput on;
declare
TYPE v_col_tab IS TABLE OF user_tables.table_name%TYPE index by PLS_INTEGER;
v_tab v_col_tab;
cursor tab_cur is
select table_name
from user_tables
where tablespace_name = 'EXAMPLE';
begin
open tab_cur;
fetch tab_cur bulk collect into v_tab;
dbms_output.put_line('Table Names are :');
for i in 1..v_tab.count
loop
dbms_output.put_line( v_tab(i));
end loop;
close tab_cur;
exception
when too_many_rows then
dbms_output.put_line('More than 1 rows are fetched');
when others then
dbms_output.put_line('Other Exception occurred');
end;
/