存储过程
存储过程(Stored Procedure)是在大型数据库系统中,一组为了完成特定功能的 SQL 语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。存储过程是数据库中的一个重要对象,任何一个设计良好的数据库应用程序都应该用到存储过程。过程相当于 java 中的方法,定义用于完成某种特定操作,PL/SQL: 匿名块 过程有名称,会存在与数据库系统中。
创建存储过程语法
create [or replace] PROCEDURE 过程名[(参数名 in/out 数据类型)]
AS/IS
begin
-- PLSQL 子程序体;
End [过程名];
无参过程
create or replace procedure pro_insert
as
begin
for v_index in 1..5 loop
insert into test_emp(empno) values(v_index);
end loop;
commit;
end;
测试无参过程
begin
mypro –-- 过程名称
end;
有参过程
create or replace procedure mypro(v_id in number,v_sal in number)
is
--定义变量 不需要使用 DECLARE
v_count binary_integer;
pemp test_emp%rowtype;
begin
select count(*) into v_count from test_emp where empno=v_id;
if v_count>0 then
select * into pemp from test_emp where empno = v_id;
update test_emp set sal=v_sal where empno=v_id;
commit;
end if;
--- 异常处理
exception
when others then dbms_output.put_line(sqlcode||'---'||sqlerrm);
dbms_output.put_line('涨工资前' || pemp.sal || '涨工资后' ||pemp.sal);
end;
测试有参过程
Begin
Mypro(7788,8000);
end;
在定义有参过程是需要使用关键字 in 来标识这是一个入参。
mypro(v_id in number,v_sal in number)
有返回值的过程
create or replace procedure query_sal(v_id in number,v_sal out number)
is
begin
select sal into v_sal from temp_emp where empno=v_id;
end;
在参数列表中使用关键字 out 标识当前过程的返回值变量和类型
query_sal(v_id in number,v_sal out number)
测试有输出参数的过程
declare
v_sal number; --- 申明变量 用于接受过程返回的值
begin
---- 调用过程---
query_sal(7788,v_sal);
dbms_output.put_line(v_sal);
end;
更多相关知识敬请关注我哦,谢谢!