Search code examples
oracleobjectoracle11gordbms

How execute a member procedure on a table of objects record?


I'm currently working on Oracle11g and I've come to grips with Table of objects. Classic example:

create or replace TYPE T_person AS OBJECT 
(
  name varchar2(20),
  surname varchar2(20),
  MEMBER PROCEDURE Set_Sir
);
 /

create or replace TYPE BODY T_person AS 
  MEMBER PROCEDURE Set_Sir IS 
  BEGIN 
        name := 'Sir ' || name;
  END;
END;
 /

CREATE TABLE person_obj_table OF t_person;

insert into person_obj_table values (t_person('John', 'Scofield'));

Now I want to call "Set_Sir" to add prefix 'Sir' to all persons named 'John' (only one in this case). How can I do that?

update 7/1/2018: this is the best solution found till now (for just one element):

declare
  p_pers t_person;
begin
  select t_person(name, surname) into p_pers
  from PERSON_OBJ_TABLE
  where NAME = 'John';

  p_pers.set_sir();

  update PERSON_OBJ_TABLE p
  set p = p_pers
  where name = 'John';
end;

Solution

  • Seems like there ought to be a better way to do this, but the best I could come up with was switching between SQL and PL/SQL.

    declare
        v_rowid rowid;
    begin
        for people in
        (
            select treat(value(p) as t_person) a_person, rowid the_rowid
            from person_obj_table p
        ) loop
            people.a_person.set_sir;
    
            update person_obj_table p
            set p = people.a_person
            where rowid = people.the_rowid;
        end loop;
    end;
    /