过程中的事务
定义过程p1
create or replace procedure p1 as begin insert into student values(5,'xdh','m',sysdate); rollback; end;
定义过程p2
执行过程p2
exec p2;
执行完毕发现表中数据没有变更,说明p1中的rollback语句将p2中的update语句也回滚了。
自主事务处理
步骤:
主事务处理启动自主事务处理
主事务处理被暂停
自主事务处理sql操作
中止自主事务处理
恢复主事务处理
pragma autonomous_transaction
用于标记子程序
在p1的as begin当中加入 pragma autonomous_transaction 后执行,发行p2的update语句生效,p1中的事务作为自主事务来处理,不影响主事务。
程序包
相关对象的封装
-程序包规格说明
声明子程序,不包含实现
create package 包名 is|as 变量声明|类型定义|异常声明|游标声明|函数说明|过程说明
pragma restrict_references(函数名,WNDS[,WNPS][,RNDS][,RNPS])
end [包名];
create or replace package StuPackages
is
type curRefStudent is REF CURSOR RETURN student%rowtype;
procedure insertStudent(stuid in student.stu_id%type,stuname in student.stu_name%type,stusex in student.stu_sex%type,studate in student.stu_birthday%type);
Function QueryStudent(stuid in student.stu_id%type) return student%rowtype;
end StuPackages;
-程序包主体
定义子程序,实现声明部分
create package body 包名 is|as 变量声明|类型定义|异常声明|游标声明|函数定义|过程定义
end [包名];
CREATE OR REPLACE PACKAGE BODY STUPACKAGES AS procedure insertStudent(stuid in student.stu_id%type,stuname in student.stu_name%type,stusex in student.stu_sex%type,studate in student.stu_birthday%type) AS i INTEGER; Student_Exist EXCEPTION; BEGIN select count(*) into i from student where stu_id = stuid; if i>0 then raise Student_Exist; else insert into student values(stuid,stuname,stusex,studate); commit; end if; EXCEPTION when Student_Exist then rollback; dbms_output.put_line('the student is already existed!'); when others then rollback; dbms_output.put_line('other error!'); END insertStudent; Function QueryStudent(stuid in student.stu_id%type) return student%rowtype AS studentrow student%rowtype; BEGIN select * into studentrow from student where stu_id = stuid; RETURN studentrow; EXCEPTION when others then rollback; dbms_output.put_line('other error!'); END QueryStudent; END STUPACKAGES;
包调用
包名.类型名;
包名.函数名[参数表];
包名.过程名[参数表];
显示绑定到引用游标变量上的值
Set AutoPrint On;
Variable tempCur RefCursor;
exec 包名.函数名;
declare sturow student%rowtype; begin stupackages.insertstudent(10,'adf','m',sysdate); sturow := stupackages.querystudent(1); dbms_output.put_line(sturow.stu_id); dbms_output.put_line(sturow.stu_name); end;
删除包
Drop Package [body] 包名;
Drop package Body 包名:
函数纯度级别
WNDS 不能写入数据库状态
RNDS 不读取数据库状态
WNPS 不写入程序包状态
RNPS 不读取程序包状态
Pragma restrict_references(函数名,纯度级别);
若函数中违反纯度级别语句,则编译报错。
重载
多个子程序可以具有相同的名字
形参不同
只能位于打包的子程序中
如果子程序的参数仅名称或模式不同,则不能重载,不能给予其返回类型重载子程序
公有项和私有项的区别
公有项:在程序包说明部分定义的变量、过程、函数
私有项:在程序包主体部分定义的变量、过程、函数
公有项 私有项
可以在程序包之外引用 不能在程序包之外引用
是在程序包规格说明中定义的 是在程序包主体中定义的
用于全局目的 用于局部目的