3

IDフィールドが共通のテーブルが2つあります。

最初のテーブルのすべてのレコードをカーソルでフェッチしています。次に、カーソルからの各IDに基づいて、2番目のテーブルから値を取得し、それを返します。

どうすればそれができますか...助けてください!!!

4

1 に答える 1

2

宿題?

これは基本的なSQLです。通常、2つのテーブルを結合します。

begin
  for r_row in (select b.*
                  from tab1 a 
                       inner join tab2 b
                               on b.id = a.id)
  loop
    null; -- do whatever
  end loop;
end;
/

既存のカーソルがあり、それを変更できない場合

たとえば、列your_cursorを返すだけの場所です。ID

begin
  open your_cursor;
  loop
    fetch your_cursor into v_id;
    exit when your_cursor%notfound;
    for r_row in (select * from tab2 b where b.id = v_id)
    loop
      null; -- do whatever here.
    end loop;
  end loop;
end;
/

編集:コメントによる:

いくつかのサンプルデータ:

SQL> create table table1 (id number primary key, name varchar2(20));

Table created.

SQL> create table table2 (id number, col1 varchar2(20), col2 varchar2(20));

Table created.

SQL> insert into table1 values (1, 'test');

1 row created.

SQL> insert into table1 values (2, 'foo');

1 row created.

SQL>
SQL> insert into table2 values (1, 'John', 'Smith');

1 row created.

SQL> insert into table2 values (1, 'Peter', 'Jones');

1 row created.

SQL> insert into table2 values (1, 'Jane', 'Doe');

1 row created.

SQL> insert into table2 values (2, 'Nina', 'Austin');

1 row created.

SQL> insert into table2 values (2, 'Naman', 'Goyal');

1 row created.

SQL> commit;

Commit complete.

戻り構造を保持する型を作成します。テーブルのデータ型と一致する必要があるデータ型に注意してくださいtable1table2%typeは機能しないため、一致していることを確認してください)

SQL> create type my_obj as object (
  2    id number,
  3    name varchar2(20),
  4    col1 varchar2(20),
  5    col2 varchar2(20)
  6  );
  7  /

Type created.

SQL> create type my_tab as table of my_obj;
  2  /

Type created.

次に、関数を作成します(実際のコードでそのようになっている場合は、これをパッケージに入れることができます)。

SQL> create function function1
  2    return my_tab pipelined
  3  is
  4  begin
  5    for r_row in (select t1.id, t1.name, t2.col1, t2.col2
  6                    from table1 t1
  7                         inner join table2 t2
  8                                 on t1.id = t2.id)
  9    loop
 10      pipe row(my_obj(r_row.id, r_row.name, r_row.col1, r_row.col2));
 11    end loop;
 12  end;
 13  /

Function created.

SQL>
SQL> select *
  2    from table(function1);

        ID NAME                 COL1                 COL2
---------- -------------------- -------------------- --------------------
         1 test                 John                 Smith
         1 test                 Peter                Jones
         1 test                 Jane                 Doe
         2 foo                  Nina                 Austin
         2 foo                  Naman                Goyal

必要に応じて、その関数table(function1('a', 'b'));などに入力を渡すことができます。

于 2013-01-08T09:59:40.927 に答える