Browsing each column of a record separately - plsql

I have a table that has a lot of columns. For some reason, I need to fetch data from it and then do some stuff on each column value separately. So I'd like to do something like this :
SELECT record FROM table
FOREACH field of the record
do some stuff
The "do some stuff" part shall do something according to the column name.
Is there an easy way to perform such a browse in PL/SQL ?
Thanks !

Unfortunately, you can't loop like this through fields of a record. However, you could use DBMS_SQL to loop through all the returned columns and do whatever you need. Check my simple example below based on this thread: Loop through columns of a record with DBMS_SQL
CREATE TABLE my_iter_tab_test (
id NUMBER,
name VARCHAR2(20),
salary NUMBER
);
INSERT INTO my_iter_tab_test VALUES (1, 'Smith', 5000);
INSERT INTO my_iter_tab_test VALUES (2, 'Brown', 6000);
COMMIT;
DECLARE
v_cur NUMBER;
v_temp NUMBER;
v_col_cnt NUMBER;
v_desc_tab_rec DBMS_SQL.DESC_TAB;
v_ret NUMBER;
v_v_val VARCHAR2(4000);
BEGIN
v_cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cur, 'SELECT * FROM my_iter_tab_test', DBMS_SQL.NATIVE);
v_temp := DBMS_SQL.EXECUTE(v_cur);
DBMS_SQL.DESCRIBE_COLUMNS(v_cur, v_col_cnt, v_desc_tab_rec);
FOR v_i IN 1..v_col_cnt
LOOP
dbms_output.put_line(v_desc_tab_rec(v_i).col_name);
DBMS_SQL.DEFINE_COLUMN(v_cur ,v_i, v_v_val, 2000);
END LOOP;
LOOP
v_ret := DBMS_SQL.FETCH_ROWS(v_cur);
EXIT WHEN v_ret = 0;
FOR v_i IN 1..v_col_cnt
LOOP
DBMS_SQL.COLUMN_VALUE(v_cur, v_i, v_v_val);
DBMS_OUTPUT.PUT_LINE(v_desc_tab_rec(v_i).col_name || ' : ' || v_v_val);
END LOOP;
END LOOP;
DBMS_SQL.CLOSE_CURSOR(v_cur);
END;
Output:
ID
NAME
SALARY
ID : 1
NAME : Smith
SALARY : 5000
ID : 2
NAME : Brown
SALARY : 6000
I guess you'll want to change the DEFINE_COLUMN to proper types in your final solution.

Related

PLS-00382: expression is of wrong type in populating an associative array table

I have this structure of table in my database
Now i want all the values inside of it in a associative array that is indexed by the job_id%type which is a varchar2, so i created this anonymous block first before creating a procedure to test it and i want to populate my associative array with the results:
DECLARE
TYPE jobs_tab_type IS TABLE OF jobs%rowtype INDEX BY jobs.job_id%type;
jobstab jobs_tab_type;
BEGIN
FOR rec IN (SELECT * FROM jobs)
LOOP
jobstab(rec.job_id) := rec.job_id;
END LOOP;
END;
I know for sure that this is a wrong way to do it since I've encountered this error: PLS-00382: expression is of wrong type , but at the same time i don't know if there is any proper way to do this. I have seen the documentation but all the examples were to use a user defined string that will hold the job_id, but the problem is that i need the job_id to be indexed and not a user defined string. Is there any way to fix this problem in PL/SQL?
You don't need the index by INDEX BY jobs.job_id%type. It is making your code more complicated. The INDEX BY determines the index of the collection - that is the character used to indicate the position in the collection. That doesn't need to be a column from the table you are taking a %rowtype from.
Typically an INDEX BY VARCHAR2 is used if you want to reference the collection based on a meaningful string, like capitals('United States') = 'Washingston'
Now, about your question. Here is the answer to the original question:
create table jobs
(job_id VARCHAR2(10)
,job_title VARCHAR2(30)
,min_salary NUMBER
,max_salary NUMBER
);
INSERT INTO jobs (job_id, job_title, min_salary, max_salary) VALUES ('a','CLERK',100,500);
INSERT INTO jobs (job_id, job_title, min_salary, max_salary) VALUES ('b','PRESIDENT',1000,5000);
INSERT INTO jobs (job_id, job_title, min_salary, max_salary) VALUES ('c','SALESMAN',500,800);
DECLARE
TYPE jobs_tab_type IS TABLE OF jobs%rowtype INDEX BY jobs.job_id%type;
jobstab jobs_tab_type;
l_idx VARCHAR2(100);
BEGIN
FOR rec IN (SELECT * FROM jobs)
LOOP
jobstab(rec.job_id) := rec;
END LOOP;
l_idx := jobstab.FIRST;
WHILE (l_idx IS NOT NULL) LOOP
dbms_output.put_line(l_idx ||': '||jobstab(l_idx).job_title);
l_idx := jobstab.NEXT(l_idx);
END LOOP;
END;
/
a: CLERK
b: PRESIDENT
c: SALESMAN
Notice that in this block, it's a bit tedious to loop through the elements, just because the index is not an integer. Now lets look at the same functionality, but using an INDEX BY BINARY_INTEGER:
DECLARE
TYPE jobs_tab_type IS TABLE OF jobs%rowtype INDEX BY BINARY_INTEGER;
jobstab jobs_tab_type;
l_idx NUMBER := 1;
BEGIN
-- example 1: using a cursor for loop
-- FOR rec IN (SELECT * FROM jobs)
-- LOOP
-- jobstab(l_idx) := rec;
-- l_idx := l_idx + 1;
-- END LOOP;
-- example 2: using bulk collect
SELECT * BULK COLLECT INTO jobstab FROM jobs;
FOR r IN 1 .. jobstab.COUNT LOOP
dbms_output.put_line(r ||': '||jobstab(r).job_title);
END LOOP;
END;
/
1: CLERK
2: PRESIDENT
3: SALESMAN
It's simpler to loop through the values of a collection because of the numeric index and it also can be implicitly assigned as well, using the BULK COLLECT statement.
The value of your associative array is the entire record. Hence just remove .job_id from this line of your code.
jobstab(rec.job_id) := rec.job_id;
In other words, the line should be
jobstab(rec.job_id) := rec;
Refer to this db<>fiddle

Getting error 'Table,View Or Sequence reference 'EMPLOYEES.EMP_NAME' not allowed in this context'

create table Employees (emp_id number, emp_name varchar2(50), salary number, department_id number, DESIGNATION varchar2(50), DEVELOPED_TESTED varchar2(50)) ;
insert into Employees values(1,'ALex',10000,10,'Developer','VLC');
insert into Employees values(2,'Duplex',20000,20,'Developer','VLC');
insert into Employees values(3,'Charles',30000,30,'Tester','Tested_VLC');
insert into Employees values(4,'Demon',40000,40,'Tester ','Tested_VLC');
insert into employees values(5,'Chaem',5000,50,'Developer','');
Requirement :
I want to return 2 if the designation is 'Developer' and developed_tested column is null. But in the output I am getting null and NOT 2. Can you please check on this.
Code :
create or replace FUNCTION calculate_royalty (
i_empno IN NUMBER
) RETURN VARCHAR2 IS
l_employee employees%ROWTYPE;
BEGIN
SELECT *
INTO l_employee
FROM
employees
WHERE emp_id = i_empno;
IF l_employee.designation = 'Developer' THEN
RETURN l_employee.developed_tested;
ELSIF l_employee.designation = 'Developer' and l_employee.developed_tested is null THEN
RETURN 2;
ELSE
RETURN 1;
END IF;
EXCEPTION WHEN NO_DATA_FOUND THEN
RETURN 0;
END ;
select CALCULATE_ROYALTY(5) from dual; -- Output coming as NULL but it should be 2 ideally.
Just select the entire row into a variable, no need to use a count. Use the NO_DATA_FOUND exception to handle the case of user does not exist.
Your question mentions some functionality related to the "royalty" column. That is missing from your test case but it should be a piece of cake to modify code below so it caters to all your needs.
create or replace FUNCTION calculate_royalty (
empno_i IN NUMBER
-- don't use column names as names of input parameters, that is a recipe for disaster. Use prefix/suffix.
) RETURN VARCHAR2 IS
lv_count NUMBER;
l_employee employees%ROWTYPE;
BEGIN
SELECT *
INTO l_employee
FROM
employees
WHERE emp_id = empno_i;
IF l_employee.designation = 'Developer' THEN
RETURN l_employee.salary;
ELSE
RETURN 1;
END IF;
-- dbms_output just sends data to a buffer that you then print to the console. it cannot be used as a return value.
-- RETURN dbms_output.put_line('Emp Name :'...
-- elsif needs to be followed by an expression. It cannot be followed by a RETURN keyword. Use "ELSE" instead if there is no condition.
-- elsif return 1;
EXCEPTION WHEN NO_DATA_FOUND THEN
RETURN 0;
END ;
/
set serveroutput on size 999999
clear screen
BEGIN
dbms_output.put_line('output for Developer: '|| calculate_royalty(EMPNO_I => 2));
dbms_output.put_line('output for no Developer: '|| calculate_royalty(EMPNO_I => 3));
dbms_output.put_line('output for non-existing user: '|| calculate_royalty(EMPNO_I => 10));
END;
output for Developer: 20000
output for no Developer: 1
output for non-existing user: 0
PL/SQL procedure successfully completed.

Calling columns of record by it´s index, not name

I have table with more than 160 columns and I need to work with each column in PL/SQL procedure. I make a record of whole row from the table like this:
DECLARE
l_employee rec_employees%ROWTYPE;
COLUMN_AND_VALUE VARCHAR2(200);
BEGIN
SELECT *
INTO l_employee
FROM employees
WHERE employee_id = 100;
and now I want to work with all columns of this record with FOR LOOP, but I don't know how, because I have to refer to each column of record by its column name like l_employee.id, l_employee.salary,.... is it possible to refer to them in order somehow like l_employee[INDEX_OF_COLUMN] and also get the name of column I am working with? Here is the example I want to do with record:
FOR INDEX_OF_COLUMN IN 1 .. 167 LOOP
COLUMN_AND_VALUE := l_employee[INDEX_OF_COLUMN].COLUMN_NAME || ': ' || l_employee[INDEX_OF_COLUMN].VALUE_OF_COLUMN
-- I know those commands don't work, but I need something like that
END LOOP;
Or is here better way to do it without using record?
Thank you very much and I'm really sorry for my bad English. I hope you understood my question :)
Finally i found with some help this solution. It is exactly what i needed in this post, but then i realised it´s not the best way for me because of another conditions i had.
`DECLARE
l_query VARCHAR2(32767) := 'SELECT * FROM employees where id=1';
l_theCursor INTEGER DEFAULT dbms_sql.open_cursor;
l_columnValue VARCHAR2(4000);
l_status INTEGER;
l_descTbl dbms_sql.desc_tab;
l_colCnt NUMBER;
BEGIN
dbms_sql.parse(l_theCursor,l_query,dbms_sql.native);
dbms_sql.describe_columns( l_theCursor, l_colCnt, l_descTbl);
FOR i IN 1 .. l_colCnt
LOOP
dbms_sql.define_column(l_theCursor, i, l_columnValue, 4000);
END LOOP;
l_status := dbms_sql.execute(l_theCursor);
WHILE ( dbms_sql.fetch_rows(l_theCursor) > 0 )
LOOP
FOR i IN 1 .. l_colCnt
LOOP
dbms_sql.column_value( l_theCursor, i, l_columnValue );
dbms_output.put_line( l_descTbl(i).col_name|| ': ' ||l_columnValue );
END LOOP;
END LOOP;
EXCEPTION
WHEN OTHERS THEN
dbms_sql.close_cursor( l_theCursor );
RAISE;
END; `

Can I pass an explicit cursor to a function/procedure for use in FOR loop?

I have a procedure that performs some calculations on all records returned by a cursor. It looks a bit like this:
PROCEDURE do_calc(id table.id_column%TYPE)
IS
CURSOR c IS
SELECT col1, col2, col3
FROM table
WHERE ...;
BEGIN
FOR r IN c LOOP
-- do some complicated calculations using r.col1, r.col2, r.col3 etc.
END LOOP;
END;
Now I have the case where I need to perform the exact same calculation on a different set of records that come from a different table. However, these have the same "shape" as in the above in example.
Is it possible to write a procedure that looks like this:
PROCEDURE do_calc2(c some_cursor_type)
IS
BEGIN
FOR r IN c LOOP
-- do the calc, knowing we have r.col1, r.col2, r.col3, etc.
END LOOP;
END;
I know about SYS_REFCURSOR, but I was wondering if it was possible to use the much more convenient FOR ... LOOP syntax and implicit record type.
Create a package.
Declare your cursor as package variable.
Use %rowtype to set function parameter type.
create or replace package test is
cursor c is select 1 as one, 2 as two from dual;
procedure test1;
function test2(test_record c%ROWTYPE) return number;
end test;
create or replace package body test is
procedure test1 is
begin
for r in c loop
dbms_output.put_line(test2(r));
end loop;
end;
function test2(test_record c%ROWTYPE) return number is
l_summ number;
begin
l_summ := test_record.one + test_record.two;
return l_summ;
end;
end test;
I had a similar problem, where I had two cursors that needed to be processed the same way, so this is how I figured it out.
DECLARE
--Define our own rowType
TYPE employeeRowType IS RECORD (
f_name VARCHAR2(30),
l_name VARCHAR2(30));
--Define our ref cursor type
--If we didn't need our own rowType, we could have this: RETURN employees%ROWTYPE
TYPE empcurtyp IS REF CURSOR RETURN employeeRowType;
--Processes the cursors
PROCEDURE process_emp_cv (emp_cv IN empcurtyp) IS
person employeeRowType;
BEGIN
LOOP
FETCH emp_cv INTO person;
EXIT WHEN emp_cv%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Name = ' || person.f_name ||
' ' || person.l_name);
END LOOP;
END;
--Defines the cursors
PROCEDURE mainProcedure IS
emp empcurtyp;
BEGIN
OPEN emp FOR SELECT first_name, last_name FROM employees WHERE salary > 50000;
process_emp_cv(emp);
CLOSE emp;
OPEN emp FOR SELECT first_name, last_name FROM kuren WHERE first_name LIKE 'J%';
process_emp_cv(emp);
CLOSE emp;
END;
BEGIN
mainProcedure;
END;
/
You can also use this if you want to bulk collect your cursors. You just need to change your helper procedure process_emp_cv; the rest can stay the same.
Using BULK COLLECT
--Processes the cursors
PROCEDURE process_emp_cv (emp_cv IN empcurtyp) IS
TYPE t_employeeRowTable IS TABLE OF employeeRowType;
employeeTable t_employeeRowTable;
BEGIN
LOOP
FETCH emp_cv BULK COLLECT INTO employeeTable LIMIT 50;
FOR indx IN 1 .. employeeTable.Count
LOOP
DBMS_OUTPUT.PUT_LINE('Name = ' || employeeTable(indx).f_name ||
' ' || employeeTable(indx).l_name);
END LOOP;
EXIT WHEN emp_cv%NOTFOUND;
END LOOP;
END;
Try this one, Usong ref cursor.
declare
type c is ref cursor;
c2 c;
type rec is record(
id number,
name varchar(20)
);
r rec;
procedure p1(c1 in out c,r1 in out rec)is begin
loop
fetch c1 into r1;
exit when c1%notfound;
dbms_output.put_line(r1.id || ' ' ||r1.name);
end loop;
end;
begin
open c2 for select id, name from student;
p1(c2,r);
end;
Yes you can use Cursor explicitly into procedure and function,for that cursor need to declare into package as variable

How to insert into a table correctly using table of records and forall in pl/sql

I want to insert records into MY_TABLE using forall. But the no. of records dat gets inserted keeps on changing with each test run! I think it has something to do with loop counter but I am not able to figure out. Here's the code snippet.
DECLARE
TYPE l_rec_type IS RECORD (
datakey SOURCE_TABLE.datakey%TYPE,
sourcekey SOURCE_TABLE.sourcekey%TYPE,
DESCRIPTION SOURCE_TABLE.DESCRIPTION%TYPE,
dimension_name SOURCE_TABLE.dimension_name%TYPE ,
data_type SOURCE_TABLE.data_type%TYPE
);
TYPE l_table_type IS TABLE OF l_rec_typeINDEX BY PLS_INTEGER;
l_table l_table_type;
l_cntr NUMBER;
BEGIN
FOR rec_dimname IN (SELECT dimension_name FROM dimension_table) LOOP
l_cntr1 := 1
FOR rec_source IN (SELECT * FROM source_table WHERE data_type IS NOT NULL) LOOP
l_table(l_ctr1).datakey := rec_source.datakey;
l_table(l_ctr1).sourcekey := rec_source.sourcekey;
l_table(l_ctr1).DESCRIPTION := rec_source.DESCRIPTION;
l_table(l_ctr1).dimension_name := rec_source.dimension_name;
l_table(l_ctr1).data_type := rec_source.data_type;
l_cntr1 := l_cntr1+1;
END LOOP
FORALL j IN l_table.FIRST..l_table.LAST
INSERT INTO my_table VALUES(l_table(j).datakey,
l_table(j).sourcekey,
l_table(j).DESCRIPTION,
l_table(j).dimension_name,
l_table(j).data_type,
1,
SYSDATE,
login_id
);
END LOOP;
END;
What am I doing wrong? Normal insert using for loop is inserting 5000 records. Another problem that I am facing is how to handle WHEN DUP_VAL_ON_INDEX and WHEN OTHERS exception using forall. In nornal for loop its easy. But I have to use FORALL for fast inserts. Please help!
Looking at your code I can see that you not delete the data stored in the pl/table inside your loop and you don't have a order by to your query's. So if the first iteration have more data then the second you will have duplicate data.
So after initializing your l_cntr1 var (l_cntr1 := 1) you must clear your pl/table:
l_table.delete;
Hope that helps.
Here's the fixed code. Plus SAVE EXCEPTIONS really saved my day!. Here is how I implemented the solution. Thank you all for your valuable time and suggestions.
DECLARE
TYPE l_rec_type IS RECORD (
datakey SOURCE_TABLE.datakey%TYPE,
sourcekey SOURCE_TABLE.sourcekey%TYPE,
DESCRIPTION SOURCE_TABLE.DESCRIPTION%TYPE,
dimension_name SOURCE_TABLE.dimension_name%TYPE ,
data_type SOURCE_TABLE.data_type%TYPE
);
TYPE l_table_type IS TABLE OF l_rec_typeINDEX BY PLS_INTEGER;
l_table l_table_type;
l_cntr NUMBER;
ex_dml_errors EXCEPTION;
PRAGMA EXCEPTION_INIT(ex_dml_errors, -24381);
login_id NUMBER := -1;
errm VARCHAR2(512);
err_indx NUMBER
BEGIN
FOR rec_dimname IN (SELECT dimension_name FROM dimension_table) LOOP
l_cntr1 := 1;
l_table.DELETE; -- Added
FOR rec_source IN (SELECT * FROM source_table WHERE data_type IS NOT NULL) LOOP
l_table(l_ctr1).datakey := rec_source.datakey;
l_table(l_ctr1).sourcekey := rec_source.sourcekey;
l_table(l_ctr1).DESCRIPTION := rec_source.DESCRIPTION;
l_table(l_ctr1).dimension_name := rec_source.dimension_name;
l_table(l_ctr1).data_type := rec_source.data_type;
l_cntr1 := l_cntr1+1;
END LOOP
FORALL j IN l_table.FIRST..l_table.LAST SAVE EXCEPTIONS
INSERT INTO my_table VALUES(l_table(j).datakey,
l_table(j).sourcekey,
l_table(j).DESCRIPTION,
l_table(j).dimension_name,
l_table(j).data_type,
1,
SYSDATE,
login_id
);
END LOOP;
END LOOP;
EXCEPTION
WHEN ex_dml_errors THEN
l_error_count := SQL%BULK_EXCEPTIONS.count;
DBMS_OUTPUT.put_line('Number of failures: ' || l_error_count);
errm := SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE);
err_indx := SQL%BULK_EXCEPTIONS(i).error_index
FOR i IN 1 .. l_error_count LOOP
DBMS_OUTPUT.put_line('Error: ' || i ||
' Array Index: ' || SQL%BULK_EXCEPTIONS(i).error_index ||
' Message: ' || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
IF errm LIKE '%unique%constraint%violated' THEN -- Insert into my_multiple_entries_tbl on duplicate value on index DATAKEY
INSERT INTO my_multiple_entries_tbl(my_multiple_entries_tbl_seq.NEXTVAL,
l_table(err_indx).datakey,
l_table(err_indx).sourcekey,
l_table(err_indx).data_type,
SYSDATE,
login_id );
ELSE -- Insert into my_other_errors_tbl on other errors
INSERT INTO my_other_errors_tbl ( my_other_errors_tbl_seq.NEXTVAL,
l_table(err_indx).datakey,
l_table(err_indx).sourcekey,
l_table(err_indx).data_type,
SYSDATE,
login_id );
END IF;
END;
Your seem to be inserting exactly the same thing multiple times - you're solely looping through the count of dimension_table, which means it can be simplified to the following, which will be faster. At the bottom is a forall version.
You can't use exception when dup_val_on_index with either version, you have to do it row by row. Judging solely by what you've posted I suspect that you can actually achieve what you're trying to do in a single query and save all this problem completely ( including dealing with duplicate values ).
declare
i integer;
begin
select count(*)
into i
from dimension_table;
for j in 1 .. i loop
insert into my_table (datakey, sourcekey, description
, dimension_name, someother_column
, some_date_column, login_id
select datakey, sourcekey, description, dimension_name
, data_type, 1, sysdate, login_id -- previously missing
from source_table
where data_type is not null;
end loop;
commit;
end;
/
If, however, you really want to use forall you can do something like this:
declare
cursor c_src is
select datakey, sourcekey, description, dimension_name
, data_type, 1, sysdate, login_id -- previously missing
from source_table
where data_type is not null;
type t__src is table of c_src%rowtype index by binary_integer;
t_src t__src;
i integer;
begin
select count(*)
into i
from dimension_table;
for j in 1 .. i loop
open c_src;
loop
fetch c_src bulk collect into t_src;
forall k in t_src.first .. t_src.last
insert into my_table (datakey, sourcekey, description
, dimension_name, someother_column
, some_date_column, login_id
values t_src;
end loop;
close c_src;
end loop;
commit;
end;
/

Resources