Search code examples
databaseoracleplsqlconstructorobject-type

PL/SQL Fill object with data from tables


I have custom object created in pl/sql. What I want to do is to create object passing id from table and fill object attributes with data from one row (speciefied by this id). How to do this? I'm working in oracle 10g.

My type looks like this:

CREATE OR REPLACE TYPE userType AS OBJECT(
    id number,
    name varchar2(100),
    nickname varchar2(100),
    email varchar2(100),
    CONSTRUCTOR FUNCTION userType(userId number) RETURN SELF AS RESULT
);

And type body declaration:

CREATE OR REPLACE TYPE BODY userType AS
    CONSTRUCTOR FUNCTION userType(userId number) RETURN SELF AS RESULT
    AS
    BEGIN
        self.id := userId;
        self.name := ???;    --<- need help there  
        self.nickname := ??? --(something like select name from userType where id = userId)                   
        (and so on)
        RETURN;
    END;
END;

Table columns have the same name as userType attributes.


Solution

  • I think you should be able to do the following:

    CREATE OR REPLACE TYPE BODY userType AS
        CONSTRUCTOR FUNCTION userType(userId number) RETURN SELF AS RESULT
        AS
        BEGIN
            self.id := userId;
            SELECT name, nickname INTO self.name, self.nickname FROM user_table WHERE id = userId;                   
            RETURN;
        END;
    END;
    

    Although I'm not sure on whether this is the correct or best way.