---
title: "PLSQL(语法--异常处理--游标--存储过程--触发器--oracle分页)"
author: "simple1024"
date: "2011-03-29T23:23:33Z"
tags: []
categories: ["数据库"]
slug: "plsql-oracle"
draft: false
lastmod: "2011-03-29T23:23:33Z"
id: 979654
url: "https://simple1024.iteye.com/blog/979654"
---

## 《PL/SQL编程》

 /\*procedural language/sql\*/  
\--1、过程、函数、触发器是pl/sql编写的  
\--2、过程、函数、触发器是在oracle中的  
\--3、pl/sql是非常强大的数据库过程语言  
\--4、过程、函数可以在java程序中调用

--提高效率：优化sql语句或写存储过程  
\--pl/sql移植性不好

--IDE(Integration Develop Environment)集成开发环境

--命令规则：  
\--变量(variable)           v_  
\--常量(constant)           c_  
\--指针、游标(cursor)         \_cursor  
\--例外、异常(exception)    e_

--可定义的变量和常量：  
  --标量类型：scalar  
  --复合类型：composite    --存放记录、表、嵌套表、varray  
  --参照类型：reference  
  --lob(large object)  
 

## 《PL/SQL 基本语法》

--例：创建存储过程  
create or replace procedure pro\_add  
is  
begin  
  insert into mytest values('韩xx','123');  
end;  
exec pro\_add; --调用

--查看错误信息  
show error;  
\--调用过程  
exec 过程(c1,c2,...);  
call 过程(c1,c2,...);  
\--打开/关闭输出选项  
set serveroutput on/off  
\--输入  
&

--块结构示意图  
declare   --定义部分，定义常量、变量、游标、例外、复杂数据类型  
begin     --执行部分，执行pl/sql语句和sql语句  
exception --例外处理部分，处理运行的各种错误  
end;      --结束

--《实例演示》  
declare  
  v\_ival number(4) :=100; --声明并初始化变量  
  --v\_dtm date;  
  v\_dtm syslogs.dtm%type; --取表字段类型  
  v\_content varchar(512);  
begin  
  v\_ival := v\_ival * 90;  --赋值运算  
  insert into syslogs values(seq\_syslogs.nextval,10,sysdate,'v\_ival='||v\_ival,user);--数据库存储  
  dbms\_output.put\_line('v\_ival'||v\_ival);  
   
  select count(\*) into v\_ival from syslogs;--使用select查询赋值  
\--select ename,sal into v\_name,v\_sal from emp where empno=&aa;  
  insert into syslogs values (seq\_syslogs.nextval,10,sysdate,'日志条数='||v\_ival,user);  
  dbms\_output.put\_line('日志条数'||v\_ival);  
    
  --获取日志序号==11的日志时间和日志内容  
  select dtm , content  
  into v\_dtm,v\_content  
  from syslogs  
  where logid=14;  
   
  insert into syslogs values (seq\_syslogs.nextval,'10',sysdate,'v\_dtm='||v\_dtm||'v\_content='||v\_content,user);  
  dbms\_output.put\_line('v\_dtm='||v\_dtm||'v\_content='||v\_content);  
  --修改日志序号=11的日志记录人  
  update syslogs  
  set whois='PL/SQL.'||v\_ival  
  where logid = 14;  
   
  --delete syslogs where logid=15;  
   
  --分支流程控制  
  if v\_ival&gt;50 then  
    dbms\_output.put\_line('日志需要清理了~');  
  else  
    dbms\_output.put\_line('日志空间正常！');  
  end if;  
   
  --Loop循环  
  v\_ival :=0;  
  loop  
      exit when v\_ival&gt;3;  
           --循环体  
           v\_ival := v\_ival+1;  
           dbms\_output.put\_line('loop循环：'||v\_ival);  
  end loop;  
   
  --While循环  
  v\_ival := 0;  
  while v\_ival &lt; 4  
  loop  
     --循环体  
     v\_ival := v\_ival+1;  
     dbms\_output.put\_line('while循环：'||v\_ival);  
  end loop;  
   
  --For循环  
  for v\_count in reverse 0..4 loop  --reverse递减  
      dbms\_output.put\_line('for循环：'||v\_count);    
  end loop;  
  commit;--提交事物  
end;

select * from syslogs;

 

 

## 《PL/SQL 异常处理》

--PL/SQL异常处理：oracle内置异常，oracle用户自定义异常  
declare  
   v\_title logtypes.tid%type;  
   v\_ival number(9,2);  
   --自定义的异常  
   ex\_lesszero exception ;  
begin  
  --select title into v\_title  
  --from logtypes     --;  too\_many\_rows  
  --where tid = 30 ;  --NO\_DATA\_FOUND 异常  
   
  v\_ival := 12/-3;  
   
  if v\_ival &lt; 0 then  
    --直接抛出异常  
    --raise ex\_lesszero ;  
    --使用系统存储过程抛出异常  
    raise\_application\_error(/\*错误代码，-20000~-20999\*/-20003,/\*异常描述\*/'参数不能小于0！');  
  end if;   
  commit;  
exception  
  --异常处理代码块  
  when no\_data\_found then  
    dbms\_output.put\_line('发生系统异常：未找到有效的数据！');  
  when too\_many\_rows then  
    dbms\_output.put\_line('发生系统异常：查询结果超出预期的一行！');  
  when ex\_lesszero then  
    dbms\_output.put\_line('发生用户异常：数值不能为负！'||sqlcode||'异常描述：'||sqlerrm);  
  when others then --other例如Exception  
    rollback;  
    dbms\_output.put\_line('发生异常！'||sqlcode||'异常的描述：'||sqlerrm);  
end;

 

 

## 《PL/SQL 游标的使用》

declare  
    --游标的声明  
    cursor myCur is  
           select tid,title from logtypes ;  
    --定义接收游标中的数据变量  
    v\_tid   logtypes.tid%type;  
    v\_title logtypes.title%type;  
    --通过记录来接受数据  
    v\_typercd myCur%rowtype ;  
begin  
    --打开游标  
    open myCur ;  
    --取游标中的数据  
    loop  
      --遍历游标中的下一行数据  
      fetch myCur into v\_tid,v\_title ;  
      --检测是否已经达到最后一行  
      exit when myCur%notfound ;  
      --输出游标中的数据  
      dbms\_output.put\_line('读取tid='||v\_tid||' title='||v\_title);  
    end loop;  
    --关闭游标  
    close myCur;  
     
    --打开游标  
    open myCur ;  
    loop  
      fetch myCur into v\_typercd ;  
      exit when myCur%notfound ;  
      dbms\_output.put\_line('--//读取tid='||v\_typercd.tid||' title='||v\_typercd.title);  
    end loop;  
    --关闭游标  
    close myCur ;  
     
    --for循环游标  
    for tmp\_record in myCur loop  
      dbms\_output.put\_line('++//读取tid='||tmp\_record.tid||' title='||tmp\_record.title);  
    end loop;

end;

 

 

## 《PL/SQL 存储过程★》

--            可以声明入参in，out表示出参，但是无返回值。  
create or replace procedure prc\_writelog(/\*日志类型\*/ tid in number ,  
                              /\*日志内容\*/ content in varchar2 ,  
                              /\*错误码  \*/ i\_ret out number ,  
                              /\*错误描述\*/ s\_ret out varchar2 )  
is

begin  
      insert into syslogs values (seq\_syslogs.nextval , tid ,sysdate ,content ,user);  
      commit;  
      i\_ret := 1 ;  
      s\_ret := '记录日志成功！' ;  
exception  
    when others then  
         rollback ;  
         i\_ret := -1 ;  
         s\_ret := '记录日志失败：'||sqlerrm ;   
end;

--测试  
declare  
  iRet number(4) ;  
  sRet varchar2(128) ;  
begin  
  prc\_writelog(10,'测试存储过程',iRet,sRet);  
  dbms\_output.put\_line('iRet:'||iRet||'sRet'||sRet);  
end;

select * from syslogs;

 

 

## 《PL/SQL 触发器》

 

--触发器 是一种基于数据库特定事件的 由数据库自动执行的pl/sql块  
\--触发的事件源：database 【启动、停止、用户联机...】  
\--              表名【insert/update/delete】  
\--触发时机 before/after  
\--语句级、行级（需要知道数据,对数据库运行速度有影响）  
create or replace trigger tri\_logtypes  
after insert or update or delete --在所有的表的事件发生后执行  
on logtypes  
for each row --行级 （:new , :old）  
declare  
    iret number(4);  
    sret varchar2(128);  
begin  
    --不要有事物的管理  
    --:new 新数据 记录型  
    --:old 原有的数据 记录型  
    --prc\_writelog(10,'触发器执行了！',iret,sret);  
    if inserting then  
        insert into syslogs values(seq\_syslogs.nextval,10,sysdate,'触发器执行添加数据！',user);  
    elsif updating then  
        if :new.title &lt;&gt; :old.title then  
           raise\_application\_error(-20001,'不允许修改日志类型名称数据！');    --抛出异常  
        end if;  
        insert into syslogs values(seq\_syslogs.nextval,10,sysdate,'触发器执行更新数据！',user);  
    elsif deleting then  
        raise\_application\_error(-20001,'不允许删除表中的数据！');  
        insert into syslogs values(seq\_syslogs.nextval,10,sysdate,'触发器执行删除数据！',user);  
    end if;  
end ;

--test!  
insert into logtypes values(30,'test log');  
delete from logtypes where tid = 30;  
update logtypes set title = 'test log' where tid = 30;

select * from syslogs order by dtm desc;  
select * from logtypes ;

 

 

## 《案例》

 

--创建表  
create table emp2 (  
  name varchar2(30),  
  sal number(8,2)  
);  
insert into emp2 values('simple',99999);  
insert into emp2 values(&a,&b);

--存储过程案例：  
\--修改员工工资  
create or replace procedure pro\_input(t\_name in varchar2,  
                           t\_sal in number)  
is  
begin  
  update emp2 set sal = t\_sal where name=t\_name;  
end;  
\--Test!  
declare  
begin  
  pro\_input('simple',2000);  
end;  
select * from emp2;

--函数案例：  
create or replace function fun\_test(t\_name varchar2)  
return number is yearSal number(7,2);  
begin  
  select sal\*12 into yearSal from emp2 where name = t\_name;  
  return yearSal;  
end;

--包案例：  
create package pac\_test  
is                           --创建一个包pac\_test  
  procedure pro\_input(t\_name varchar2,t\_sal number); --声明该包有一个过程 pro\_input  
  function fun\_test(t\_name varchar2) return number;  --声明该包有一个函数 fun\_test  
end;

--包体案例:  
create package body pac\_test  
is  
  procedure pro\_input(t\_name in varchar2,t\_sal in number)  
  is  
  begin  
    update emp2 set sal = t\_sal where name=t\_name;  
  end;  
   
  function fun\_test(t\_name varchar2)  
  return number is yearSal number(7,2);  
  begin  
    select sal\*12 into yearSal from emp2 where name = t\_name;  
    return yearSal;  
  end;  
end ;  
\--调用包中的函数或过程  
call pac\_test.pro\_input('summer',1000);  
call pac\_test.fun\_test  
select pac\_test.fun\_test('simple') from dual;

--案例：  
select * from emp2;  
\--下面以输入员工工号，显示雇员姓名、工资、个人所得税  
\--税率（0.03）。  
declare  
  c\_tax\_rate number(3,2):=0.03;  --常量，税率  
  --v\_name varchar2(30);  
  v\_name emp2.name%type;  
  --v\_sal number(8,2);  
  v\_sal emp2.sal%type;  
  v\_tax\_sal number(8,2);  
begin  
  --执行  
  select name,sal into v\_name,v\_sal from emp2 where name = &na;  
  --计算所得税  
  v\_tax\_sal:=v\_sal\*c\_tax\_rate;  
  --输出  
  dbms\_output.put\_line('姓名：'||v\_name||' 工资'||v\_sal||' 交税'||v\_tax\_sal);   
end;

--pl/sql记录实例  
declare  
  --定义一个pl/sql记录类型 emp\_record\_type ，类型包含2个数据，t\_name,t\_sal  
  type emp\_record\_type is record(t\_name emp2.name%type,t\_sal emp2.sal%type);  
  --定义一个 record\_test 变量，类型是 emp\_record\_type  
  record\_test emp\_record\_type;  
begin  
  select name,sal into record\_test from emp2 where name = 'simple';  
  dbms\_output.put\_line('员工工资:'||record\_test.t\_sal);  
end;

--pl/sql表实例  
declare  
  --定义了一个pl/sql表类型 emp\_table\_type 该类型是用于存放 emp.name%type元素类型 的数组  
  -- index by binary\_integer 下标是整数  
  type emp\_table\_type is table of emp2.name%type index by binary\_integer;  
  --定义一个 table\_test 变量  
  table\_test emp\_table\_type;  
begin  
  --table\_test(0)下标为0的元素  
  select name into table\_test(0) from emp2 where name='summer';  
  dbms\_output.put\_line('员工:'||table\_test(0));  
end;

--案例  
\--显示该部门的所有员工和工资  
declare  
  --定义游标类型 emp\_cursor  
  type emp\_cursor is ref cursor;  
  --定义一个游标变量  
  cursor\_test emp\_cursor;  
  --定义变量  
  v\_name emp2.name%type;  
  v\_sal emp2.sal%type;  
begin  
  --执行  
  --把cursor\_test 和一个select结合  
  open cursor\_test for  
  select name,sal from emp2;  
  --循环取出  
  loop  
    --fetch取出 游标 给 v\_name,v\_sal  
    fetch cursor\_test into v\_name,v\_sal;  
    --判断工资  
    if v\_sal&lt;1000 then  
      update emp2 set sal = v\_sal+1000 where sal=v\_sal;  
    end if;  
    --判断cursor\_test是否为空  
    exit when cursor\_test%notfound;  
    dbms\_output.put\_line('姓名：'||v\_name||' 薪水：'||v\_sal);  
  end loop;  
end;

select * from emp2;

--《分页》案例：  
\--建表  
drop table book;  
create table book(  
  bookId number(5),  
  bookName varchar2(50),  
  publishHouse varchar2(50)  
);  
\--编写过程  
create or replace procedure pro\_pagination( t\_bookId in number,  
                            t\_bookName in varchar2,  
                            t\_publishHouse in varchar2)  
is  
begin  
  insert into book values(t\_bookId,t\_bookName,t\_publishHouse);  
end;  
\--在java中调用  
\--select * from book;  
\--insert into book values(11,'流星','蝴蝶');  
\--commit;  
\--有输入和输出的存储过程  
create or replace procedure pro\_pagination2( i\_id in number,  
                                             o\_name out varchar2,  
                                             o\_publishHouse out varchar2  
                                             )  
is  
begin  
  select bookName,publishHouse into o\_name,o\_publishHouse from book where bookId = i\_id;  
end;  
\--Test!  
declare  
  err book.bookname%type;  
  err2 book.publishhouse%type;  
begin  
  pro\_pagination2(10,err,err2);  
  dbms\_output.put\_line(err||' '||err2);  
end;  
\--返回结果集的过程  
\--1、创建一个包  
create or replace package testpackage  
as  
  type cursor\_test is ref cursor;  
end testpackage;  
\--2、建立存储过程  
create or replace procedure pro\_pagination3(  
                                            o\_cursor out testpackage.cursor\_test)  
is  
begin  
  open o\_cursor for  
  select * from book;  
end;  
\--3、如何在java中调用

--Test!  
declare  
  err testpackage.cursor;  
begin  
  pro\_pagination2(10,err);  
  dbms\_output.put\_line(err);  
end;

## &lt;Oracle的分页&gt;

 

select t1.\*,rownum rn from (select * from emp) t1;

select t1.\*,rownum rn from (select * from emp) t1 where rownum&lt;=10;  
\--在分页的时候，可以把下面的sql语句当做一个模板使用  
select * from (select t1.\*,rownum rn from (select * from emp) t1 where rownum&lt;=10) where rn&gt;=6;

--开发一个包  
\--1、创建一个包  
create or replace package testpackage  
as  
  type cursor\_test is ref cursor;  
end testpackage;  
\--开始编写分页的过程  
create or replace procedure fenye(tableName in varchar2,  
                                  pageSize in number, --每页显示记录数  
                                  pageNow in number,  
                                  myRows out number,--总记录数  
                                  myPageCount out number,--总页数  
                                  p\_cursor out testpackage.cursor\_test)  
is  
  --定义sql语句 字符串  
  v\_sql varchar2(1000);  
  --定义2个整数  
  v\_begin number:=(pageNow-1)\*pageSize+1;  
  v\_end number:=pageNow\*pageSize;  
begin  
  v\_sql:='select * from (select t1.\*,rownum rn from (select * from '||tableName||' order by sal) t1 where rownum&lt;='||v\_end||') where rn&gt;='||v\_begin||'';  
  --把游标和sql关联  
  open p\_cursor for v\_sql;  
  --计算myRows和myPageCount  
  --组织一个sql  
  v\_sql:='select count(\*) from '||tableName||'';  
  --执行sql，并把返回的值，赋给myRows  
  execute immediate v\_sql into myRows;  
  --计算myPageCount  
  if mod(myRows,pageSize)=0 then  
    myPageCount:=myRows/pageSize;  
  else  
    myPageCount:=myRows/pageSize+1;  
  end if;  
  --关闭游标  
  --close p\_cursor;  
end;  
\--使用java测试