1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Oracle 主キーを変えつつ、レコードをコピーする方法

Posted at

例えば、既存のユーザーレコードをもとに、ID(主キーカラム)やその他一部のカラムだけ変えてコピーを作る際の雛形です。

他のテーブルを参照することもできるため、「あるレコードを元に、権限や種別の組み合わせを網羅したデータを用意する」など、大量に作成する場面にも応用がききます。

この方法では無名ブロックを書かないといけませんが、
ID 毎に INSERT 文をベタで書く方法と比べると、変更するカラムが明確になります。

-- 部署ごとにテストユーザーを作成する方法

set serveroutput on -- debug
begin
  -- バリエーションに応じてループを回す
  for d in (select * from DEPARTMENT order by DEPARTMENT_ID) loop
    dbms_output.put_line(d.DEPARTMENT_ID); -- debug

    -- 雛形レコードを rowtype な変数 u に格納する
    for u in (select * from USERS where USER_ID = 'test-user-templ') loop
      -- 主キーを変更する
      u.ID := 'test-user-' || d.DEPARTMENT_ID;
      -- その他、変更するものを明記する。
      u.DEPARTMENT_ID := d.DEPARTMENT_ID;
      u.NAME2 := d.NAME;
      u.NOTE := 'テスト';

      insert into USERS values u;
    end loop;

  end loop;
end;
/
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?