I am new to PL/SQL, I am trying to create a type of a table with %rowtype and followed by declaring a variable and doing sort of operations example; below is the code snippet of the logic that i am trying:
DECLARE
TYPE my_type IS TABLE OF emp%rowtype INDEX BY PLS_INTEGER;
l_arr_type my_type;
BEGIN
SELECT * BULK COLLECT INTO l_arr_type FROM emp;
FOR rec IN (SELECT * FROM TABLE (l_arr_type) ORDER BY HIREDATE)
LOOP
DBMS_OUTPUT.PUT_LINE('Ename is: '||rec.ENAME||' and hire date is: '||rec.HIREDATE);
END LOOP;
END;
Error:
ORA-06550: line 8, column 38: PLS-00382: expression is of wrong type
But same thing is working when i am declaring the variable inside a package and using the same; am I missing some thing here? Isn't not a strange behavior? Below is the working code snippet:
CREATE OR REPLACE PACKAGE my_array IS
TYPE my_type IS TABLE OF emp%rowtype INDEX BY PLS_INTEGER;
END my_array;
/
DECLARE
l_arr_type my_array.my_type;
BEGIN
SELECT * BULK COLLECT INTO l_arr_type FROM emp;
FOR rec IN (SELECT * FROM TABLE (l_arr_type) ORDER BY HIREDATE)
LOOP
DBMS_OUTPUT.PUT_LINE('Ename is: '||rec.ENAME||' and hire date is: '||rec.HIREDATE);
END LOOP;
END;
It will be helpful if i can get a clarification behind this kind of behavior ;
------------------------update-----------------
Similar operation is working with TYPE as RECORD; below is my code snippet
DECLARE
TYPE my_type IS RECORD (ename_t emp.ENAME%TYPE, sal_t emp.SAL%TYPE, eno_t emp.empno%TYPE);
l_arr_type my_type;
BEGIN
SELECT ENAME, sal, empno INTO l_arr_type FROM emp where ename='KING';
DBMS_OUTPUT.PUT_LINE('Ename is: '||l_arr_type.ename_t);
END;
SQL is different than PL/SQL. They are processed by different engines and have a different set of recognized types. When you invoke a SQL statement within PL/SQL, you switch to the SQL engine and it operates without visibility to your code. For this reason, historically SQL could only navigate collections typed as SQL types (
create type ...). PL/SQL types were inaccessible to it.But starting in 12.1, Oracle began permitting the
TABLESQL operator to access PL/SQL collections, but requires them to be defined in package headers. Package headers are sort of like exposed object specifications that outside code, and now the SQL engine itself, can interrogate to understand how to access a PL/SQL object, including a collection.