Hohenheimsenberg
Hohenheimsenberg

Reputation: 980

How to edit a cursor attribute for a return statement on plsql?

I want to return a cursor from a function, I have read that I can use:

return sys_refcursor

And then

open curs for select* from mytable;
return curs;

I tried curs.att := 'something' but I get an error

Also read I can do my own type:

 TYPE type IS REF CURSOR RETURN mytable%ROWTYPE;

Then

CURSOR cur IS
    SELECT* FROM mytable;
var cur%ROWTYPE;

BEGIN
OPEN cur;
FETCH cur INTO var;
var.att = 'something';
RETURN var;

This time I didn't get an error in the assign but in the return statement.

If I changed the var type to my type I couldn't fetch the value.

I wan't to edit the cursor, but not the table, how can I do this?

Upvotes: 0

Views: 1284

Answers (1)

Justin Cave
Justin Cave

Reputation: 231661

A cursor is a read-only structure. The only way to change the data that you would fetch from a cursor is to change the SQL statement that is used to open the cursor or to change the data in the underlying table(s).

While it is possible to return a cursor from one PL/SQL block to another, it is rarely the appropriate architecture. A SYS_REFCURSOR is generally appropriate when you want to return a result to a client application that knows how to use a cursor.

Do you really want to return a cursor, though? Or do you want to return a record type? The second code snippet you posted appears to be trying to return a record-- that's certainly possible but you would need to declare that the function returns a record rather than a cursor. That is, the RETURN statement in the declaration would need to be RETURN mytable%ROWTYPE rather than RETURN type. For example, if you want to return a record based on the EMP table

create or replace function get_emp( p_empno in emp.empno%type )
  return emp%rowtype
is
  l_rec emp%rowtype;
begin
  select *
    into l_rec
    from emp
   where empno = p_empno;
  l_rec.sal := l_rec.sal + 100;
  return l_rec;
end;

Upvotes: 1

Related Questions