2013年1月21日月曜日

[Oracle]PL/SQLのUSINGを使用した条件のバインド変数化

SQL文をリテラルで定義する必要がある場合(例えばテーブル名を変数の内容によって変わる場合など)に、USING句を使用して条件値をバインド変数化することができる。

例えば、以下のようにIDで絞込みを行う場合、IDの条件値を「:id」のようにしバインド変数化する。実際にSQL実行時に条件として指定する値はusing句を使用して条件に埋め込みます。

declare
  id account.id%type;
  type accounts_cur is ref cursor;
  accounts accounts_cur;
  account_rec account%rowtype;
begin
  id := 1;
  open accounts for 'select * from account where id = :id' using id;
  loop
    fetch accounts into account_rec;
    exit when accounts%notfound;
    dbms_output.put_line(account_rec.id);
    dbms_output.put_line(account_rec.name);
  end loop;
  close accounts;
end;