A.创建包规格部分
格式:Create [or replace] Package 包名
IS|AS
变量声明;
类型定义;
异常声明;
游标声明;
函数说明;
过程说明;
Pragma restrict_references(过程名或函数名,WNDS[,WNPS][,RNDS][,RNPS]) --编译指令 限定函数的操作
End [包名];
B.创建包主体部分
格式: Create [or replace] package body 包主体名 --包主体名一定要是已经定义的包名
IS|AS
变量声明; --具体的实现部分
类型定义;
异常声明;
游标声明;
函数说明;
过程定义;
End [包主体名];
6. 示例
示例1.创建程序包的规格说明部分
Create or replace Package StudentPackage
is
Type curRefStudent is Ref Cursor Return Student%rowtype;
Procedure SelectStudent(FindID in Student.stuid%type);
Procedure InsertStudent(NewStudent in Student%rowType);
Procedure UpdateStudent(NewStudent in Student%rowType);
Procedure DeleteStudent(DelID in Student.stuid%type);
Procedure ReturnStudent(inOutstu in out curRefStudent);
Function RegurnRecordCount Return Number;
End studentPackage;
示例2.创建程序包的主体部分
Create or replace Package Body StudentPackage IS
Procedure SelectStudent(FindID in Student.stuid%type) as --注意没有Create
/*实现查询过程的定义*/
Cursor findCur is select * from student where stuid=FindID;
Begin
For S in FindCur Loop
DBMS_output.put_line(S.stuID||' '||s.StuName||' '||S.Sex);
End Loop;
Exception
When No_Data_Found Then
DBMS_output.Put_Line('没有查到ID为'||FindID||'的记录!');
When Others Then
DBMS_output.Put_Line('查询过程中发生意外情况');
End SelectStudent; --结束查询过程
/*实现插入过程的定义*/
Procedure InsertStudent(NewStudent in Student%rowType) as
iRec Integer;
Not_Exists_Student Exception; --预定义异常
Begin
Select count(*) into iRec from student where stuid=NewStudent.stuID;
IF iRec>0 Then
Raise Not_Exists_Student;
Else
insert into student values(NewStudent.stuid,NewStudent.stuName,NewStudent.sex);
commit;
End IF;
Exception
When Not_Exists_Student Then
DBMS_output.Put_Line('要插入的编号:'||NewStudent.stuid||'的记录已经存在');
When Others Then
DBMS_output.Put_Line('插入记录操作过程中出现错误');
End InsertStudent;--结束插入过程
/*实现更新过程的定义*/
Procedure UpdateStudent(NewStudent in Student%rowType) as
iRec Integer;
Begin
select Count(*) into iRec From student Where stuid=NewStudent.stuid;
IF iRec =0 Then
DBMS_output.Put_Line('编号为:'||NewStudent.stuid||'的记录不存在,修改失败');
ELSE
Update student Set Stuname=NewStudent.stuName,Sex=NewStudent.Sex
WHERE stuid=NewStudent.stuID;
Commit;
End IF;
| 广告合作:400-664-0084 全国热线:400-664-0084 Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15080520号-20 珠峰网 版权所有 All Rights Reserved
|