欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

OraclePL/SQL编程基础实例2

程序员文章站 2022-11-25 21:38:58
if 循环 控制语句 if--then endif if----then ----else endif if-----then --elsif then ----...
if 循环 控制语句

if--then endif

if----then ----else endif

if-----then --elsif then ----else endif

--编写一个过程,可以 输入一个雇员名,如果该雇员的工资低于2000就给他增加10%
create or replace procedure sp_pro6(spname varchar2) is
v_sal emp.sal %type;
begin
select sal into v_sal from emp where ename =spname;
--判断
if v_sal<2000 then
update emp set sal=sal*1.1 where ename =spname;
end if;
end;
--======####案例s33 编写一个过程,可以 输入一个雇员名,如果该雇员的补助不是0就在原基础上增加100,如果是0就加200
create or replace procedure sp_pro7(spname varchar2) is
v_comm emp.comm %type;
begin
select comm into v_comm from emp where ename =spname;
--判断
if v_comm<>0 then
update emp set comm=comm+100 where ename =spname;
else
update emp set comm=comm+200 where ename =spname;
end if;
end;

----========循环 loop end loop
-----案例 编写一个过程 可输入用户名 并添加10个用户到users表中 用户编号从1来时增加
--建个表
create table users1(uid1 number,uname varchar2(40));

create or replace procedure sp_pro8(spname varchar2) is
--定义变量
v_num number :=1;
begin
loop
insert into users1 values(v_num,spname);
--判断是否退出循环
exit when v_num =10;
--自增
v_num:=v_num+1;
end loop;
end;

----------------===while ...loop end loop

----===案例 从11 开始 添加10个用户
create or replace procedure sp_pro8(spname varchar2) is
--定义变量
v_num number :=11;
begin
while v_num<=20
loop
--执行
insert into users1 values(v_num,spname);
--自增
v_num:=v_num+1;
end loop;
end;
---------------------for
begin for i in reverse 1.. 10 loop
insert into users1 values(v_num,spname);
end loop;
end;

-----------------顺序控制语句 goto null
goto label

<<label>>

-----=-----------返回结果集的过程----=======
---1.----创建 一个 包 在该包中 定义一个 类型 test_cursor 是个游标
create or replace package testpackage as
type test_cursor is ref cursor;
end testpackage;
-----2.创建过程
create or replace procedure sp_pro9 (spno in number,p_cursor out testpackage.test_cursor)
is
begin
open p_cursor for select * from emp where deptno=spno;
end;

-----3.如何在java中调用
---1.创建 callablestatement cs =ct.preparecall([call sp_pro9(?,?)]);
---- cs.setint(1,10);
----cs.registeroutparameter(2,oracle.jdbc.oracletypes.cursor);
--执行--cs.execute();
--得到结果集
/*resultset rs=(resultset)cs.getobject(2);

while(rs.next()){
....
}*/

---------------------例外处理---------
case_not_found
data_not_found
cursor_already_open
dup_val_on_index 唯一索引重复
invaild_cursor 在不合法的游标上执行操作 比如 从没有打开的游标取值 或关闭没有打开的游标
invalid_number
too_many_rows select into 的时候 返回超过一行
zero_pide 2/0
value_error 变量长度不足以容纳实际长度

-----自定义例外
create or replace procedure ex_test(spno number)
is
--定义一个例外
myex exception;
begin
update emp set sal=sal+1000 where empno=spno;
--sql%notfound 表示没有update
--raise myex 触发myex
if sql%notfound then
raise myex;
end if;
exception
when myex then
dbms_output.put_line('没有更新任何用户');

end;

-----------------------------视图---------------
--视图不能添加索引
create view myview as select * from emp where sal<1000;
select * from myview;