Oracle_0813
PLSQL中的控制、循环语句
if …else
--if...else
declare
avgsal scott.emp.sal%type;
begin
select avg(sal) into avgsal from emp;
if(avgsal >1000) then
dbms_output.put_line('高收入');
end if;
end;
case
–case在一组选择之中根据条件比较的结果执行其中一个分支的操作。
case
when 值1 then;
when 值2 then;
else
end case;
第一种用法:
declare
avgsal scott.emp.sal%type;
begin
select avg(sal) into avgsal from emp;
case
when avgsal>=3000 then dbms_output.put_line('高收入企业');
when avgsal>=2500 then dbms_output.put_line('一般收入企业');
when avgsal>=1950 then dbms_output.put_line('低级收入企业');
else
dbms_output.put_line('临时上班');
end case;
end;
select avg(sal) from emp;
第二种用法:
select ename,empno,job,
case job
when 'MANAGER' then '高级管理员'
when 'PRESIDENT' then '高级管理员'
else 'ptyg'
end tip
from emp;
loop
--1到10的和
declare
-- 定义变量
sums integer:=0;
i integer:=1;
begin
loop
sums:= sums+i;
if i=10 then
exit;
else
i:=i+1;
end if;
end loop;
dbms_output.put_line(sums);
end;
--9*9乘法表
declare
begin
for i in 1..9 -- for ......in
loop
for j in 1..i
loop
dbms_output.put(j||'*'||i||'='||to_char(i*j)||' '); --- \\ 表示的是 拼接 字符串
end loop;
dbms_output.put_line('');
end loop;
end;
游标*
cursor 游标名称 is select …
open 游标名称; --打开游标
--------------------*游标*---------------
--fetch移动该指针
--cursor游标关键字
cursor 游标名称 is select ...查询哪张表。
open 游标名称; --打开游标,不打开游标就不会移动,数据不会读取
declare
--定义游标
cursor myempcs is select * from emp;
begin
open myempcs;--打开
fetch myempcs into myemp;--移动
dbms_output.put_line(myemp.ename);
close myempcs; --关闭游标
end;
--读取数据靠的是指针的移动
begin
open myempcs;
fetch myempcs into emp;
dbms_output.put_line(emp.ename);
close myempcs;
end;
备注 :游标不可以单独存在,必须在PL/SQL代码块里面执行。
%found 判断图取得数据是否为所有匹配的数据类型
--if mycursor%found then
--if mycursor%notfound then
-- 利用 %isopen 判断游标是否打开
if mycursor%isopen then
declare
cursor myemp is select * from emp;
mycurrent myemp%rowtype;
begin
open myemp;
if myemp%isopen then
fetch myemp into mycurrent;
dbms_output.put_line(mycurrent.empno||' '||mycurrent.ename);
else
dbms_output.put_line('查无此数据');
dbms_output.put_line('游标没有打开');
end if;
close myemp;
end;
--%rowcount 通过游标知道在数据库里面有多少条数据
declare
cursor mycursor is select * from emp ;
currecord mycursor%rowtype ;
begin
open mycursor;
loop
fetch mycursor into currecord ;
exit when mycursor%notfound;
dbms_output.put_line(mycursor%rowcount);
end loop;
close mycursor;
end;
存储过程*
Procedure:
- 储存指的是储存数据的思想
- 过程是一种函数思想
两者整合之后,储存过程是基于函数的一种plsql语句块,可以读取存放到内存的数据。
效率很高–DBA的权限操作
--存储过程案例
create procedure ys--定义存储过程
declare
cursor cs is select * from emp;
y cs%rowtype;
begin
open cs;
loop
fetch cs into y;
dbms_output.put_line(y.ename||y.empno);
end;