Article Directory
1 Overview
The characteristics of the stored procedure:
1. 存储过程是 '预编译' 过的,并且经优化后存储于 sql 内存中,
使用时无需再次编译,提高了工作效率
2. 存储过程的代码直接存放于数据库中一般由客户端直接通过存储过程名进行调用,
减少了 '网络流量(I/0)',加快了系统执行速度。
3. 使用存储过程可以减少 sql 注入式攻击,提高了系统的 '安全性'。
执行存储过程的用户要具有一定权限才能使用存储过程
2 Grammar
2.1 Create
create or replace procedure schema.过程名(变量名 in|out 数据类型) is|as -- 此处 is 和 as 等同
声明语句段;
begin
执行语句段;
exception
异常处理语句段;
end 过程名;
Parameter description (in | out):
1. 无参数时: 不用带 '()',如: scott.proc_no_parameter
2. 有参数时
(1) 仅有入参:in,其中 in 也可以省略。以下两种方法等同('推荐第二种:不用考虑变量类型问题')
scott.proc_in_parameter(p_ename IN VARCHAR2)
scott.proc_in_parameter(p_ename IN scott.emp.ename%TYPE)
(2) 仅有出参:out,其中 out 不可以省略
scott.proc_out_parameter(p_ename OUT scott.emp.ename%TYPE)
(3) 既有入参 in,也有出参 out
-- 多个参数时
scott.proc_with_parameter(p_empno IN scott.emp.empno%TYPE,
p_ename OUT scott.emp.ename%TYPE)
-- 一个参数时:既是入参,也是出参
scott.proc_with_parameter(p_empno IN OUT scott.emp.empno%TYPE)
Tips: The
stored procedure is a named block, the is | as keyword replaces the declare of an unnamed block
2.2 Call
1. 在 pl/sql 中调用存储过程('任何情况均适用')
declare
begin
procedure; -- 若有参,则加上 "()"
end;
2. 在命令窗口(请注意:仅在 '无参' 或 '仅有入参' 时适用)
exec procedure;
execute procedure; -- exec 是 execute 的缩写
call procedure;
说明:exec 和 call 的区别:
(1) exec 只能在命令窗口执行
(2) call 即可以在命令窗口执行又可以在 pl/sql 程序窗口中执行
但必须有括号,即使没有参数
3 example
--********************************************************
-- 功能:根据 empno 查询 ename
-- 参数:p_empno 员工号
-- p_ename 员工姓名
-- p_flag 程序执行标识(Y:成功,N:失败)
-- p_message 程序执行描述信息
--********************************************************
CREATE OR REPLACE PROCEDURE scott.proc_scott_emp(p_empno IN scott.emp.empno%TYPE,
p_ename OUT scott.emp.ename%TYPE,
p_flag OUT VARCHAR2,
p_message OUT VARCHAR2) IS
BEGIN
p_flag := 'Y';
p_message := '执行成功';
SELECT e.ename
INTO p_ename
FROM scott.emp e -- empno
WHERE e.empno = p_empno;
EXCEPTION
WHEN OTHERS THEN
p_flag := 'N'; -- 执行失败
p_message := 'ERROR, ' || p_empno || ' 不存在!';
END proc_scott_emp;
/
Enter the "test window", perform Debug, observe the program executes each step
Call the stored procedure: