expression is of wrong type - plsql

I am trying to create a function that returns all values of the emp table Why do I get the error?
create or replace FUNCTION EMP_value
RETURN VARCHAR2
is
CURSOR a is select * from emp;
v_all emp%rowtype;
begin
open a;
LOOP
fetch a into v_all;
exit when a%notfound;
dbms_output.put_line(v_all.empno|| ' ' ||v_all.ename|| ' ' ||v_all.sal);
RETURN V_ALL;
end loop;
close a;
end;

Try to simplify your code as much as possible. If you want to return all the attributes of cursor from function, try using BULK collect and return it as complex data type. Here in this case its nested table type. Hope it helps.
--Create a schema level nested table type function
CREATE OR REPLACE TYPE emp_obj IS OBJECT
(
EMPNO NUMBER,
ENAME VARCHAR2(100),
SAL NUMBER,
MGR_NO NUMBER,
HIREDATE DATE
)
/
CREATE OR REPLACE TYPE emp_tab IS TABLE OF emp_obj
/
--Funtion to return all attributes from EMP tab
CREATE OR REPLACE FUNCTION EMP_value
RETURN emp_tab
AS
e_tab emp_tab;
begin
SELECT * BULK COLLECT INTO e_tab
FROM EMP;
RETURN e_tab;
end;
/

Related

How to get value from nested table in pl sql table

I have created nested table as follow:
CREATE OR REPLACE TYPE EMP_NO_NAME
AS OBJECT
(
EMPNO NUMBER(4),
ENAME VARCHAR2(20),
JOB VARCHAR2(20),
MGR NUMBER(5),
HIREDATE DATE,
SAL NUMBER(7,2)
);
CREATE OR REPLACE TYPE EMP_TABLE IS TABLE OF EMP_NO_NAME;
-----------------------
CREATE TABLE NESTED_EMP
(
DEPTNO NUMBER(2) ,
EMPLOYEE EMP_TABLE
)
NESTED TABLE EMPLOYEE STORE AS NESTED_EMPLOYEE;
INSERT INTO NESTED_EMP (DEPTNO,EMPLOYEE)
VALUES (10,EMP_TABLE(EMP_NO_NAME(7839,'KING','PRESIDENT',NULL,'17-NOV-81',5000),
EMP_NO_NAME(7782,'CLARK','MANAGER',7839,'09-JUN-81',2450),
EMP_NO_NAME(7934,'MILLER','CLERK',7782,'23-JAN-82',1300)
)
);
INSERT INTO NESTED_EMP (DEPTNO,EMPLOYEE)
VALUES (20,EMP_TABLE(EMP_NO_NAME(7566,'JONES','MANAGER',7839,'02-APR-81',2975),
EMP_NO_NAME(7902,'FORD','ANALYST',7566,'03-DEC-81',3000),
EMP_NO_NAME(7369,'SMITH','CLERK',7902,'17-DEC-80',800),
EMP_NO_NAME(7788,'SCOTT','ANALYST',7566,'09-DEC-82',3000),
EMP_NO_NAME(7876,'ADAMS','CLERK',7788,'12-JAN-83',1100)
)
);
INSERT INTO NESTED_EMP (DEPTNO,EMPLOYEE)
VALUES (20,EMP_TABLE(EMP_NO_NAME(7698,'BLAKE','MANAGER',7839,'01-MAY-81',2850),
EMP_NO_NAME(7654,'MARTIN','SALESMAN',7698,'28-SEP-81',1250),
EMP_NO_NAME(7499,'ALLEN','SALESMAN',7698,'20-FEB-81',1600),
EMP_NO_NAME(7844,'TURNER','SALESMAN',7698,'08-SEP-81',1500),
EMP_NO_NAME(7900,'JAMES','CLERK',7698,'03-DEC-81',950),
EMP_NO_NAME(7521,'WARD','SALESMAN',7698,'22-FEB-81',1250)
)
);
Now I getting the value of nested table in plsql:
DECLARE
CURSOR EMPLOYEE IS
select p.* from NESTED_EMP p1 ,table(p1.employee) p;
V_EMP EMP_TABLE;
BEGIN
FOR V_EMP IN EMPLOYEE
LOOP
EXIT WHEN EMPLOYEE%NOTFOUND;
END LOOP;
FOR MYINDEX IN V_EMP.FIRST..V_EMP.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V_EMP(MYINDEX).ENAME);
END LOOP;
END;
/
END;
Error report:
ORA-06531: Reference to uninitialized collection ORA-06512: at line 10
06531. 00000 - "Reference to uninitialized collection"
*Cause: An element or member function of a nested table or varray
was referenced (where an initialized collection is needed)
without the collection having been initialized.
*Action: Initialize the collection with an appropriate constructor
or whole-object assignment.
How to get nested table value in plsql table ?
The problem with your code is that V_EMP is not actually of type EMP_TABLE. Rather, it's an EMPLOYEE.ROWTYPE. When you initialize a cursor for loop, the variable is automatically made an appropriate ROWTYPE, overriding any previous declarations.
The good news is that, since you've already referenced the nested table in the query, you don't need to do so in the loop (it's already been exploded). Your PL/SQL can be vastly simplified:
DECLARE
CURSOR employee IS
SELECT p.*
FROM nested_emp p1 CROSS JOIN TABLE (p1.employee) p;
BEGIN
FOR v_emp IN employee LOOP
DBMS_OUTPUT.put_line (v_emp.ename);
END LOOP;
END;
/
You'll notice the EXIT WHEN was removed as well. A cursor for loop terminates automatically after the last record.
An alternative would be to not explode the nested table in the query. Then you would need two loops:
DECLARE
CURSOR employee IS
SELECT p.*
FROM nested_emp p;
BEGIN
FOR v_emp IN employee LOOP
for i in v_emp.employee.first..v_emp.employee.last loop
DBMS_OUTPUT.put_line (v_emp.employee(i).ename);
end loop;
END LOOP;
END;
/

plsql Result consisted of more than one row. How to handel it

CREATE PROCEDURE book_check(book_Id varchar(64))
begin
declare book_available varchar(64);
select book_id into book_available
from book_copies
where No_of_Copies >0 and book_id=book_Id;
if(book_Id in book_available ) then
select concat ("Book available");
else
select concat ("Book not available");
end if;
end
//
what can i write in place of 'in' . I know the syntax i wrong .
It's easy - try something like this:
create or replace function book_check(book_id varchar) return varchar as
begin
for r in (select 1 from book_copies where no_of_copies > 0 and book_id = book_check.book_id) loop
return 'Book available';
end loop;
return 'Book not available';
end book_check;
/
It's unclear to me what you are trying to do. I assume you want to find out if a book is available or not and return that information to the caller of the function.
Your declaration of the procedure header and the variables is wrong.
Procedure or function parameters are not defined with a length for the datatype.
Inside a procedure or function you don't need declare
you can't have a select statement without putting the result somewhere. * Assigning a constant value to a variable is done using :=
If you want to return information to the caller, use a function, not a procedure
You should not give variables or parameters the same name as a column. A common naming convention in the Oracle world is to give parameters the prefix p_ and local variables the prefix l_ but anything that avoids a name clash between column names and variables is OK - just be consistent.
CREATE function book_check(p_book_id varchar)
return varchar
as
l_count integer;
l_result varchar(20);
begin
select count(*)
into l_count
from book_copies
where No_of_Copies > 0
and book_id = p_book_id;
if l_count > 0 then
l_result := 'Book available';
else
l_result := "Book not available";
end if;
return result;
end;
/
You should really take the time and read the PL/SQL Language reference. All the above is explained there.

Assigning object type in plsql

I need your help to know how to assign the object type through a string in PLSQL
Below is the problem description:
I first created the object types as below:
create or replace type picu_obj is object(Customer_ID varchar2(32767),Customer_Name varchar2(32767),Server_Name varchar2(32767),Time_stamp varchar2(32767));
create or replace type picu_obj_tab is table of picu_obj;
and I have a PLSQL block as below:
declare
l_str1 varchar2(1000);
l_str2 varchar2(10000);
l_newstr1_1 varchar2(10000);
picu_var picu_obj_tab;
cursor c1cudetails
is
select item,current_value
from
(select rownum,
last_value(category ignore nulls) over (order by rownum) category ,
last_value(item ignore nulls) over (order by rownum) item,
current_value
from pi_perfdata_new
order by rownum
)
where upper(category) like '%CUSTOMER%DETAILS%' ;
type cudet is table of c1cudetails%rowtype index by pls_integer;
l_cudet cudet;
begin
/* create dynamic string for items */
open c1cudetails;
fetch c1cudetails bulk collect into l_cudet limit 50;
for i in l_cudet.first..l_cudet.last loop
l_str1:=l_str1||','||''''||l_cudet(i).current_value||'''';
l_str2:=trim(leading ',' from l_str1);
l_newstr1_1:='picu_obj_tab(picu_obj('||l_str2||'))';
end loop;
-- dbms_output.put_line(''||l_newstr1_1||'');
-- picu_var := l_newstr1_1;
close c1cudetails;
end;
For the string "l_newstr1_1" following value is retruned from above PLSQL block
picu_obj_tab(picu_obj('CSCO5','DXRTYE','PI22-pro-333','2015-07-22-22:48:56'))
Now I want to assign the above result to variable "picu_var" which I have declared.
Basically I need to convert to the following during runtime.
picu_var := picu_obj_tab(picu_obj('CSCO5','DXRTYE','PI22-pro-333','2015-07-22-22:48:56'))
How to achieve the same?
Please suggest how to initialize the object type variable to the string values.
Use dynamic PL/SQL like this:
execute immediate 'begin :x := ' || l_newstr1_1|| '; end;'
using out picu_var;

pl/sql displaying all columns of a table

employee table schema
employee(id, name, company, salary);
procedure created to display all the column values
create or replace procedure p1
IS
BEGIN
select * from employee;
END;
/
exe p1;
However, this does not display the data.
Your PL/SQL block is not valid, and won't even run. You need to either return the data back to the client, or if you're using SQL*Plus use dbms_output.put_line to print the query resultset.
create or replace procedure p1
IS
BEGIN
DBMS_OUTPUT.ENABLE;
FOR emp_rec in select * from employee LOOP
dbms_output.put_line('EMployee id: || emp_rec.emp_id || ' Name: ' || emp_rec ename);
END LOOP
END;
/
Change the column name suitably

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

Resources