一、定义
存储过程是一组为了完成特定功能的SQL语句,经编译后存储在数据库中。
点击查看优缺点。
二、存储过程简单入门
第一个存储过程 :打印hello word, my name is stored procedure内容
1
2
3
4
5
create or replace procedure myDemo01
as
begin
dbms_output.put_line(
'hello word, my name is stored procedure'
);
end;
create or replace procedure:关键字用来创建或覆盖一个原有的存储过程。
myDemo01:自定义的存储过程的名字。 as:关键字。 注: 在存储过程(PROCEDURE)和函数(FUNCTION)中没有区别;
在视图(VIEW)中只能用AS不能用IS;
在游标(CURSOR)中只能用IS不能用AS。
begin:关键字。 dbms_output.put_line('hello word, my name is stored procedure'); 输出内容。 end;关键字。
存储过程的调用 :
1
2
3
4
5
6
7
8
declare
begin
myDemo01;
end;
begin
myDemo01; --在此处也可使用myDemo01();完成存储过程的调用
end;
1
call myDemo01();--call 存储过程名可完成调用,注意括号不能少
1
2
3
4
SQL> set serveroutput on --可以再command命令窗口执行
SQL> exec mydemo01 --下面是输出结果
hello word, my name is stored procedure
PL/SQL procedure successfully completed
三种方式可以完成存储过程的调用,分别为声明declare关键字和不声明declare关键字;call和Commond窗口执行命令。执行的结果如下所示
第二个存储过程 :变量声明,赋值
1
2
3
4
5
6
7
8
9
create or replace procedure myDemo02
as
name varchar(10);--声明变量,注意varchar需要指定长度
age
int
;
begin
name:=
'xiaoming'
;--变量赋值
age:=18;
dbms_output.put_line(
'name='
||name||
', age='
||age);--通过||符号达到连接字符串的功能
end;
第三个存储过程 :带有参数的存储过程
1
2
3
4
5
6
7
8
9
create or replace procedure myDemo03(name
in
varchar,age
in
int
)
as
begin
dbms_output.put_line(
'name='
||name||
', age='
||age);
end;
begin
myDemo03(
'xiaoming'
,18);
end;
在调用存储过程时,如果存储过程没有参数,调用时括号()可以不带。
存储过程带参数需要注意参数的传递参数时的一致性,按顺序依次传递。
第四个存储过程 :实参形参问题
1
2
3
4
5
6
7
8
9
10
11
12
13
create or replace procedure myDemo04(name
in
varchar,age
in
int
)
as
begin
dbms_output.put_line(
'name='
||name||
', age='
||age);
end;
declare
name varchar(10);
age
int
;
begin
name:=
'xiaoming'
;
age:=18;
myDemo04(name=>name,age=>18);--此时不能myDemo04(name=>name,18),不能完成调用。
注;在调用存储过程时,=>前面的变量为存储过程的形参且必须于存储过程中定义的一致,而=>后的参数为实际参数。当然也不可以不定义变量保存实参
第五个存储过程 :in,out参数问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
create or replace procedure myDemo05(name
out
varchar,age
in
int
)
as
begin
dbms_output.put_line(
'age='
||age);
select
'xiaoming'
into
name
from
dual;
end;
declare
name varchar(10);
age
int
;
begin
myDemo05(name=>name,age=>10);
dbms_output.put_line(
'name='
||name);
end;
注:in代表输入,out用于输出,参数默认类型是in类型。
第六个存储过程 :异常问题,执行结果见下图
1
2
3
4
5
6
7
8
9
10
11
12
13
create or replace procedure mydemo0006
as
age
int
;
begin
age:=10/0;
dbms_output.put_line(age);
exception when others then
dbms_output.put_line(
'error'
);
end;
begin
mydemo0006();
end;
总结: 简单学习oracle存储过程,在