Felipe
Felipe

Reputation: 11887

Is it possible to do this in Oracle PL/SQL?

I have a regular table called TABLE1 with a column NUMBER(8) and a column varchar2(100).

Now I've created an OBJECT TYPE T_MYTYPEwith two attributes: one NUMBER and another varchar2.

In a nutshell, they are exactly the same.

Now I want to do the following.

v_obj T_MYTYPE;

begin 
 select * into v_obj from TABLE1 t1 where t1.num = 9;--guaranteed to return only ONE row!!
end;  

but PL/SQL: ORA-00947: not enough values..

This is quite frustrating... I just want to be able to return ONE row of data into a collection!! Be it a RECORD or a OBJECT TYPE!!, I don't care... I just can't seem to make this work..!!!! Can anyone help??

Upvotes: 2

Views: 1561

Answers (2)

Justin Cave
Justin Cave

Reputation: 231671

You can. You just need to use the object constructor

SQL> create type t_simple_emp
  2      as object
  3  (
  4    empno number,
  5    ename varchar2(100)
  6  );
  7  /

Type created.

SQL> declare
  2    l_simple_emp t_simple_emp;
  3  begin
  4    select t_simple_emp( empno, ename )
  5      into l_simple_emp
  6      from emp
  7     where ename = 'KING';
  8  end;
  9  /

PL/SQL procedure successfully completed.

In your case, it would be

SELECT t_mytype( column1, column2 )
  INTO v_obj
  FROM table1 t1
 WHERE t1.num = 9;

If all you want to do is select an entire row from a table into a record type, however, then you'd want to do as ruakh suggested and just declare a %ROWTYPE record

declare
  l_emp_rec emp%rowtype;
begin
  select *
    into l_emp_rec
    from emp
   where ename = 'KING';
end;
/

Upvotes: 7

ruakh
ruakh

Reputation: 183361

Instead of this:

v_obj T_MYTYPE;

Try this:

v_obj table1%ROWTYPE;

to declare it as having the exact same type as a row of table1.

Upvotes: 3

Related Questions