另外一种表现形式:
declare
x number;
begin
x :=0;
loop
x:=x+1;
exit when x>=3;
dbms_output.put_line('循环体内 x ='||x);
end loop;
dbms_output.put_line('循环体外 x ='||x);
end;
While循环:
declare
x number ;
begin
x:=0;
while x<=3 loop
x:=x+1;
dbms_output.put_line('循环内'||x);
end loop;
dbms_output.put_line('循环外'||x);
end;
/
以下代码演示了while 循环得使用。声明了销量的 monthly_value 和 daily_value,并将其初始化为0。While执行循环,直至每月销量的值大于等于4000
set serveroutput on
declare
monthly_value number :=0;
daily_value number :=0;
begin
while monthly_value <= 4000
loop
monthly_value := daily_value * 31;
daily_value := daily_value +10;
dbms_output.put_line('每日销量:' || daily_value);
end loop;
dbms_output.put_line('每月销量' || monthly_value);
end;
/
For循环语句:
begin
for i in 1..5 loop
dbms_output.put_line('循环 I 的值 = '||i);
end loop;
dbms_output.put_line('end loop');
end;
/
Reverse(递减) 的使用
begin
for i in reverse 1..5 loop
dbms_output.put_line('循环 I 的值 = '||i);
end loop;
dbms_output.put_line('end loop');
end;
/
以下代码显示了25个偶数
set serveroutput on begin for eve_number in 1..25 loop dbms_output.put_line(eve_number*2); end loop; end; /
Oracle 中异常的处理:
预定义异常:
返回多行异常:
declare
firstname varchar2(20);
begin
select first_name into firstname from employees2 where division_id ='SAL';
dbms_output.put_line('first_name=' || firstname);
exception
when too_many_rows then
dbms_output.put_line('不能返回多行数据');
end;
/
用户自定义异常:
以下代码演示了用户接受输入的类别。IF 语句将用户输入的类别与指定的类别相匹配。如果指定的类别中不存在将引发typeException 异常
declare
typeException exception;
temptype varchar2(20);
begin
temptype :='&type';
if temptype not in ('java','c++','c#') then
raise typeException;
else
dbms_output.put_line('temptype = '||temptype);
end if;
exception
when typeException then
--dbms_output.put_line('没有找到相应的类型');
raise_application_error(-20000,'没有找到相应的类型');
end;
存储过程的使用:
过程是执行某些操作的子程序,它是执行特定任务的模块,它可以被赋予参数,存储在数据库中。以下代码
1. 创建存储过程语法:
CREATE [OR REPLACE] PROCEDURE[( )] IS|AS BEGIN [EXCEPTION ] END;
以下代码演示了如何创建一个不带参数的存储过程:
create or replace procedure pro_emp
as
firstName varchar2(20);
lastName varchar2(20);
salary number(20);
begin
select first_name,last_name,salary into firstName,lastName,salary from employees2 where employee_id = 1;
dbms_output.put_line('firstName = '||firstName);
dbms_output.put_line('lastName = ' ||lastName);
dbms_output.put_line('salary = ' ||salary);
exception
when no_data_found then
dbms_output.put_line('数据没有找到');
end;
执行以上存储过程:
execute pro_emp ;
过程参数模式:参数传递的模式有三种IN , OUT , IN OUT
IN 是参数的默认模式,这种模式定义的参数在程序运行的时候已经具有值,在过程序体中这个值不会改变。
OUT 模式定义的参数只在过程内部赋值。
IN OUT 模式定义的参数当过程运行时可能已经具有值,但是在过程体中也可以修改
以下创建了带参数的过程:
create or replace procedure mypro(employeeid in number,divisionid in out va rchar2,jobid out varchar2) as tempdivid varchar2(20); tempjobid varchar2(20); begin select division_id,job_id into tempdivid,tempjobid from employees2 where employee_id =employeeid; divisionid :=tempdivid; jobid :=tempjobid; end;
执行以上过程:
declare cdivisionid varchar2(20); cjobid varchar2(20); cempid number(10); begin cempid :=1; mypro(cemp