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

You can do it in one query:

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;

Sample output produced by the block to test if the solution works:

2
Brown
B
BB
Smith
E
于 2013-11-07T00:22:16.390 に答える