PL / SQL使用表中的数据填充对象

时间:2015-03-20 07:10:43

标签: database oracle plsql constructor object-type

我在pl / sql中创建了自定义对象。我想要做的是创建从表中传递id的对象,并使用来自一行的数据填充对象属性(由此id修改)。这该怎么做?我在oracle 10g工作。

我的类型如下:

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
);

type body声明:

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;

表列与userType属性具有相同的名称。

2 个答案:

答案 0 :(得分:2)

我认为你应该能够做到以下几点:

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;

虽然我不确定这是正确的还是最好的方式。

答案 1 :(得分:2)

我认为你正在努力做到这一点

SQL> desc employ
 Name                                      Null?    Type
 ----------------------------------------- -------- ---------------------------

 ID                                                 NUMBER
 NAME                                               VARCHAR2(50)


SQL> select * from employ
  2  ;

        ID NAME
---------- --------------------------------------------------
         1 Exhaust
         2 Object
         3 Fill



SQL> ed
Wrote file afiedt.buf

  1  create or replace type usertype as object
  2  (
  3  id number,
  4  name varchar2(50),
  5  constructor function usertype(userId number) return self as result
  6* );
SQL> /

Type created.


SQL> ed
Wrote file afiedt.buf

  1  create or replace type body usertype as
  2  constructor function usertype(userid number) return self as result
  3  as
  4  outvar employ.name%type;
  5  begin
  6  self.id := userid;
  7  select name into outvar from employ where id = userid;
  8  self.name := outvar;
  9  return;
 10  end;
 11* end;
SQL> /

Type body created.



SQL> declare
  2  v_usertype usertype;
  3  begin
  4  v_usertype := usertype(1);
  5  dbms_output.put_line(v_usertype.name);
  6  end;
  7  /
Exhaust

PL/SQL procedure successfully completed.