首先我们看一个简单之例子,下面这个例子是统计从1至100的总和.
declare
i number:=0; /*声明变量井给初值*/
t number:=1;
error_message exception; /*声明一个出错处理*/
begin
for t in 1..100 loop
i:=i+t;
end loop;
if i>=5050 then
raise error_message; /*引发错误处理*/
else
insert into c_nt(c_t) values(i);
end if;
exception
when error_message then
insert into c_nt(c_t) values(0);
end;
² 从上例中可以看出PL/SQL语法的一般规则.
PL/SQL中语句以分号(;)结尾.
开始程序块的PL/SQL语句(如IF…或BEGIN语句)没有分句.
文本值括在单引号(‘ ‘)内,而不是(“ “).
过程只允许最后有一个出口..
² PL/SQL程序可以分为三个部分
DECLARE部分用于变量、常量、函数、过程、Cursor.
BEGIN部分包含PL/SQL块中要执行的代码 用于程序处理,其中可以调用函数、过程.
Exception 部分用于出错处理.
下面我们再看一个例子:
declare
i number :=1;
t number :=1;
p number :=1;
/*create table c_ny(c_t number,cou_t number);*/
function aa(xx number)return number is /* define function*/
tt number;
ct number:=1;
j number:=1;
begin
while j<=xx loop
ct:=ct+j;
j:=j+1;
end loop;
return ct;
end aa;
begin
/*create table c_nt(c_t number,cou_t number);*/
commit;
while i<=200 loop
t:=t+i;
i:=i+1;
p:=aa(i); /* calling function*/
insert into c_nt values(t,p);
commit;
end loop;
end;
/
说明:
1.在定义变量可以赋初值,赋初值有两种方法,一为上程序所示,另一种为如下所示:
Declare
I number default 92;
T number default 0;
2.定义常量
Declare
I constant number:=1;
T constant number:=9;
3.定义函数
function function_name(parameter type)return type is
…declare variant
begin
…
…
end function_name;
在上面的例子中我们定义了一个函数aa,在begin模块部分引用了此函数aa().
4.定义过程
procedure procedure_name(parameter IN type) is
…declare variant
begin
…
…
exception
…
…
end procedure_name;
见下例:
declare
/*t_emp c_nt%rowtype;*/
i number:=1;
t number:=1;
procedure te_t(t_t number) is /*定义一个函数*/
begin
insert into c_nt1(t_1) values(t_t);
end te_t;
begin
for i in 1..100 loop
te_t(i);
end loop;
end;
/
5.定义Cursor
declare
/*t_emp c_nt%rowtype;*/
t_emp1 number;
t_emp2 number;
cursor tes_t1
is select * from c_nt;
begin
open tes_t1;
delete from c_nt1;
commit;
loop
fetch tes_t1 into t_emp1,t_emp2;
exit when tes_t1%notfound;
insert into c_nt1 values(t_emp1,t_emp2);a