0
1

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.

PL/SQLブロックでデータ投入

0
Posted at

大量のデータ投入が必要で、
突貫でPL/SQLブロックでツールを作成したので覚え書き。

PL/SQLブロックとは

sqlplusで実行できるプログラム。
ストアドプロシージャと違って、プロシージャの作成は不要。
と理解している。

PL/SQLブロックの構成

DECLARE
 宣言部
 
BEGIN
 実行部

EXCEPTION  
 例外処理
 
END;
/

パーティション単位で投入

リストパーティションのパーティション単位でトランザクションを切ってデータの投入および更新を行った。
パーティション名がhoge_01,hoge_02のように連番だったので次のように対処。

上手くいった例

パーティション名を文字列連結すると動的なSQLにすることができる。
登録・更新の場合は、sql_stmtをinsert/updateに読み替えよう。

--part_nameには、for loopでhoge_01やhoge_02のようなパーティション名の文字列を作成し代入

sql_stmt := 'select hoge from table_name partition (' || :part_name || ') t where・・・';

EXECUTE IMMEDIATE sql_stmt into vHoge using part_name;

end loop;

失敗した例

partition句がハマったポイント。
partition句にはバインド変数が使えない。
パーティション名をバインド変数で渡そうとするとエラーになる。

--part_nameには、for loopでhoge_01やhoge_02のようなパーティション名の文字列を作成し代入

select hoge into vHoge from table_name partition (:part_name) t where・・・
--part_nameには、for loopでhoge_01やhoge_02のようなパーティション名の文字列を作成し代入

sql_stmt := 'select hoge from table_name partition (:part_name) t where・・・';

EXECUTE IMMEDIATE sql_stmt into vHoge using part_name;

PK単位で投入

カーソルforループ

アカウントのようなPKの単位でトランザクション切ってデータの投入および更新を行った。
カーソルを使ってアカウント毎に処理。
宣言部でカーソルにPKを読み込む。この例ではaccount。

DECLARE
 cursor cur is
 select account from table_name where ・・・;

カーソルforループで処理。
where句にPK(この例ではaccount)を指定。
forループ内でselectするなり、updateするなり、insertするなり、deleteするなり、好きにすればいい。

BEGIN
 for c in cur loop
 
  --カーソル変数.項目名で参照
  select hoge from table_name where account = c.account;
   
  commit;
  
 end loop;

END;
/

ツールを作って楽しましょ。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?