oracle PL/SQL
PL/SQLは、 Oracleデータベースで使える手続き型プログラミング言語
PL... Procdural Languageの略だとおもふ。
SQLは当然、分岐処理や繰り返し処理などができませんが
PL/SQLならば可能
PL/SQLはDIANAというAda言語の影響が強いので、ALGOL系統の文法や構文に近いそうです。
SQL> SQL> declare 2 s number :=1; 3 e number :=10; 4 begin 5 for hensu in s..e loop 6 insert into test_tbl values(hensu ,to_char(hensu)); 7 commit; 8 end loop; 9 end; 10 / SQL> select count(*) from test_tbl; 10 SQL> select * from test_tbl; 4,4 5,5 6,6 7,7 8,8 9,9 10,10 1,1 2,2 3,3 SQL>
ネストもできる。
Declare Begin Declare -- 宣言 Begin -- 処理 Exception -- エラー処理 End; Exception End;
- if
declare test_var number := 1; begin if test_var = 1 then null; -- null は何もしない時に記述 elsif test_var = 2 then null; end if; end; /
- for
create table test_tbl (col1 number); declare test_var number := 100; begin for test_var in 1..10 loop -- ローカルとしてtest_var変数を暗黙定義. insert into test_tbl values (test_var); end loop; insert into test_tbl values (test_var); commit; end; /
- 前判定 while
declare test_var number := 100; begin while test_var <= 110 loop insert into test_tbl values (test_var); test_var := test_var + 1; -- インクリメント演算は出来ない end loop; commit; end; /
- 後判定 loop
PL/SQLではC言語のように、while文を反復の最後に設定できないのでif文とloop文で行う
。
declare test_var number := 100; begin loop -- 処理を書く. -- 後判定 if test_var = 100 then exit; -- loopを抜ける end if; end loop; end; /
- selectやカーソルなど
select into文
select into文は、1レコードの取得しか出来ません。
複数のレコードの場合はカーソルを使います。