0

假设我有一个包含嵌套表的集合:

CREATE TYPE address_type AS OBJECT (
   address_code VARCHAR2(1),
   address      VARCHAR2(30),
   city         VARCHAR2(30),
   state        VARCHAR2(3),
   zip          VARCHAR2(10));

CREATE TYPE addresses_type AS TABLE OF address_type;

-- You can see here that the person may have multiple addresses (addrs)
CREATE TYPE person_type AS OBJECT (
  personID  NUMBER,
  name      VARCHAR2(30),
  birthdate DATE,
  gender    VARCHAR2(1),
  addrs     addresses_type);

CREATE TYPE people_type as TABLE OF person_type;

如果我有一个 PLSQL 块,并且我想从下表中创建并加载一个人的对象及其地址,那么最简单的方法是什么?我必须执行多个查询吗?

DECLARE
   the_people people_type;
BEGIN
   -- want to Query and load "the_people" with everybody in the tables below:
..
END;

表:外键是 PERSON_ID

PERSON
------
PERSON_ID
NAME 
BIRTHDATE
GENDER

ADDRESSES
---------
PERSON_ID
ADDRESS_CODE
ADDRESS
CITY 
STATE
ZIP
4

1 回答 1

2

您可以在一个查询中完成:

CREATE TABLE person (
  person_ID  NUMBER,
  name      VARCHAR2(30),
  birthdate DATE,
  gender    VARCHAR2(1)
);

CREATE TABLE addresses (
  person_id NUMBER,
  address_code VARCHAR2(1),
  address      VARCHAR2(30),
  city         VARCHAR2(30),
  state        VARCHAR2(3),
  zip          VARCHAR2(10)
);

INSERT INTO person VALUES (1, 'Brown', SYSDATE, 'M');
INSERT INTO person VALUES (2, 'Smith', SYSDATE, 'M');

INSERT INTO addresses VALUES (1, 'A', 'B', 'C', 'D', '1');
INSERT INTO addresses VALUES (1, 'A', 'BB', 'CC', 'DD', '1');
INSERT INTO addresses VALUES (2, 'B', 'E', 'F', 'G', '1');

COMMIT;

DECLARE
  the_people people_type;
BEGIN
  SELECT
    person_type(
        person_id,
        name,
        birthdate,
        gender,
        (SELECT CAST(MULTISET (
                      SELECT
                          address_code,
                          address,
                          city,
                          state,
                          zip
                        FROM addresses
                      WHERE person_id = p.person_id) AS addresses_type
                    )
          FROM dual
        )
    )
  BULK COLLECT INTO the_people
  FROM
    person p
  ;

  dbms_output.put_line(the_people.COUNT);
  dbms_output.put_line(the_people(1).name);
  dbms_output.put_line(the_people(1).addrs(1).address);
  dbms_output.put_line(the_people(1).addrs(2).address);

  dbms_output.put_line(the_people(2).name);
  dbms_output.put_line(the_people(2).addrs(1).address);
END;

块产生的示例输出以测试解决方案是否有效:

2
棕色的
乙
BB
史密斯
乙
于 2013-11-07T00:22:16.390 回答