Can I define a type from a cursor?
Currently I have to write the following in order to create a record variable from some table fields:
declare
cursor cur
is
select
f_1,
f_2,
f_3,
f_4
from
mytable
where
1=0;
myvar cur%rowtype; -- use the cursor to declare myvar
begin
null;
end;
I would like to write something like this:
declare
cursor cur
is
select
f_1,
f_2,
f_3,
f_4
from
mytable
where
1=0;
type mytype is cur%rowtype; -- declare "mytype" from cursor
myvar mytype; -- use "mytype" to declare "myvar"
begin
null;
end;
This doesn't look useful in this trivial example, but can be useful in real problems.
An alternative is to manually create the record type:
declare
type mytype is record -- declare "mytype"
(
f_1 mytable.f_1%type,
f_2 mytable.f_2%type,
f_3 mytable.f_3%type,
f_4 mytable.f_4%type
);
myvar mytype; -- use "mytype" to declare "myvar"
begin
null;
end;
but it is more dirty to me (I have to repeat every field name twice, and the table name many times).
Procedure. Formulate a CREATE TYPE (CURSOR) statement: Specify a name for the type. Specify a row definition by doing one of: referencing the name of a row data type, specifying that the type should be anchored to a table or view, or anchored to the result set definition associated with an existing strong cursor type.
You can use %TYPE to provide the datatype of a record variable. Also, in the RETURN clause of a REF CURSOR type definition, you can use %ROWTYPE to specify a record type that represents a row returned by a strongly (not weakly) typed cursor variable.
A cursor variable is like an explicit cursor that is not limited to one query. To create a cursor variable, either declare a variable of the predefined type SYS_REFCURSOR or define a REF CURSOR type and then declare a variable of that type. You cannot use a cursor variable in a cursor FOR LOOP statement.
PL/SQL has two types of cursors: implicit cursors and explicit cursors.
Can I define a type from a cursor?
Yes, you can define your own type that is based on cursor_name%rowtype
record type(basically it will be a synonym in this situation), using subtype
keyword, not the type
one.
Here is an example:
set serveroutput on;
declare
cursor c1 is
select 1 as col1
, 2 as col2
, 3 as col3
from dual;
subtype mytype is c1%rowtype;
l_myvar mytype;
begin
open c1;
fetch c1 into l_myvar;
dbms_output.put(to_char(l_myvar.col1) || ' : ');
dbms_output.put(to_char(l_myvar.col2) || ' : ');
dbms_output.put_line(to_char(l_myvar.col3));
close c1;
end;
Result:
anonymous block completed
1 : 2 : 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With