A Day In The Life

とあるプログラマの備忘録

SQL文の動的生成

OraclePL/SQLSQL文を動的に生成して実行するサンプルです。

declare
 wk_sql varchar2(1000);
 usertable user_tables%rowtype;
 cursor cu is select * from user_tables;
begin
 open cu;
 loop
  fetch cu into usertable;
  exit when cu%notfound;
  wk_sql := 'delete from ' || usertable.table_name;
  EXECUTE IMMEDIATE wk_sql;
 end loop;
 close cu;
 commit;
end;

実行するとユーザーの持っているテーブルのデータがすべて消えます。

Deleteの代わりにTruncate TableでもOKです。

データをインポートする時に使ったりできます。