达梦数据库的过程包使用
过程包即Package,它是存储过程的延伸,包的实现主要包括包头和包体,其中包头主要用于定义接口,包体主要用以实现包体中声明的存储过程、函数等。如果业务中需要用到大量的存储过程,则需要用过程包对存储过程进行进一步的包装,Package 分为Package声明以及Packge body,需要先声明存储过程,存储过程中相关的数据,在Package body中实现声明中的存储过程。
1、查看所有角色
首先创建一张测试的表来测试
create table tab_package_cs (id int, name varchar(100), city varchar(100));
insert into tab_package_cs values(10,‘fuzhou‘,‘福州‘);
2、开始创建包
现在我们开始创建包,创建包分两部分内容:包头和包体,创建包前是需要先对包里的动作做定义申明,也就是我们说的包头,然后再建包体。我们创建一个包来做实验,这个包里有我们可以存储多个存储过程,每个过程又都可以执行一段自己的代码,我们分别在包里设置新删改查表的过程。
create or replace package pkp_package_cs is
e_nocs exception;
cscount int;
pcur cursor;
procedure addcs(pname varchar(100), pcity varchar(100));
procedure removecs(pname varchar(100), pcity varchar(100));
procedure removecs(pid int);
function getcscount return int;
procedure cslist;
end pkp_package_cs;
/
3、创建包体内容语句
create or replace package body pkp_package_cs as
procedure addcs(pname varchar(100), pcity varchar(100)) as
begin
insert into tab_package_cs values(11, pname, pcity);
cscount = cscount + sql%rowcount;
end addcs;
procedure removecs(pname varchar(100), pcity varchar(100)) as
begin
delete from tab_package_cs where name like pname and city like pcity;
cscount = cscount - sql%rowcount;
end removecs;
procedure removecs(pid int) as
begin
delete from tab_package_cs where id = pid;
cscount = cscount - sql%rowcount;
end removecs;
function getcscount return int as
begin
return cscount;
end getcscount;
procedure cslist as
declare
v_id int;
v_name varchar(100);
v_city varchar(100);
begin
if cscount = 0 then
raise e_nocs;
end if;
open pcur for select id, name, city from tab_package_cs;
loop
fetch pcur into v_id,v_name,v_city;
exit when pcur%notfound;
print (‘no.‘ + (cast (v_id as varchar(100))) + ‘ ‘ + v_name + ‘????‘ + v_city );
end loop;
close pcur;
end cslist;
begin
select count(*) into cscount from tab_package_cs;
end pkp_package_cs;
/
4、调用包
首先我们来使用下这个包,调用包里插入表的过程
call pkp_package_cs.addcs (‘xiamen‘, ‘厦门‘);
查询表的数据情况
select * from tab_package_cs;
首先我们来使用下这个包,调用包里删除记录的过程
call pkp_package_cs.removecs (‘xiamen‘, ‘厦门‘);
select * from tab_package_cs;
5、包的管理
编译包,当对包体做修改里可以重新编译
alter package pkp_package_cs compile;
删除包主体和包头,顺序要先删除包体再删除包头
drop package body pkp_package_cs;
drop package pkp_package_cs;
原文地址:https://blog.51cto.com/14615334/2463430