现在的位置: 首页 > 综合 > 正文

PL/SQL编程(四)

2013年04月18日 ⁄ 综合 ⁄ 共 2360字 ⁄ 字号 评论关闭
文章目录

七、pl/sql基础语法—条件循环等

1. if条件

1)if—then

--编写一个过程,输入雇员名,如果该雇员工资低于2000,就增加10%

create or replace procedure test_pro(name varchar2) is

--定义部分

v_sal emp.sal%type;

begin

--执行部分

select sal into v_sal from emp where ename=name;

if v_sal<2000 then

update emp set sal=sal+sal*10% where ename=name;

end if;

end;

 

2)if—then—else

--编写一个过程,输入雇员名,如果该雇员的补助不是0就在原来的基础上增加100;如果补助为0就把补助设为200

create or replace procedure test_pro(name varchar2) is

--定义部分

v_comm emp.comm%type;

begin

select comm into v_comm from emp where ename=name;

if v_comm <> 0 then

update emp set comm=comm+100 where ename=name;;

else

update emp set comm=200 where ename=name;

end if;

end;

 

3)if—then—elsif—then

--编写一个过程,输入雇员编号,如果该雇员的职位是PRESIDENT就给他工资增加1000;如果该雇员的职位是MANAGER工资就增加500

--其他职位的雇员员工工资增加200

create or replace procedure test_pro(no number) is

--定义部分

v_job emp.job%type;

begin

--执行部分

select job into v_job from emp where empno=no;

if v_job='PRESIDENT' then

update emp set sal=sal+1000 where empno=no;

elsif v_job='MANAGER' then

update emp set sal=sal+500 where empno=no;

else

update emp set sal=sal+200 where empno=no;

end if;

end;

 

 

2. 循环—loop

1)loop是pl/sql中最简单的循环,以loop开头,以end loop结尾。这种循环至少会被执行一次。

--案例

--现有一张users表,结构为用户id和用户名2个字段组成

--请编写一个过程,可以输入用户名,并循环添加用户到users表中,用户编号从1开始

create or replace procedure test_pro(userName varchar2) is

--定义一个索引

v_index_num number :=1;

begin

loop

insert into users(userId,userName) values(v_index_num,userName);

--判断是否要退出循环

exit when v_index_num>=10;

--自增

v_index_num=v_index_num+1;

end loop;

end;

 

2)while循环

loop循环至少要执行一次,而对于while循环来说,只有条件为true时,才会执行循环体语句,while循环以while…loop开始,以end loop结束。

--案例

--现有users表,结构同上。请编写一个过程,输入用户名,并循环添加10个用户到users表中

--用户编号从11开始

create or replace procedure test_pro(userName varchar2) is

--定义变量

v_index_num number:=11;

begin

--循环

while v_index_num>=20 loop

--插入用户名

insert into users(userId,userName) values(v_index_num,userName);

--自增

v_index_num=v_index_num+1

end loop;

end;

 

3)for循环

for循环的基本结构如下:

begin

for i in reverse 1..10 loop

insert into users values(i,'test');

end loop;

end;

其中,控制变量i在隐含中有个自增1的过程。缺点,不灵活。

 

3. 顺序控制语句

1)goto语句

goto语句用于跳到特定的标号去执行语句。

注意:乱用goto语句会增加程序的复杂性,并使得应用程序可读性变差,所以在做一般应用程序开发时,建议大家不要使用goto语句。

基本语法如下,goto lable,其中lable是已经定义好的标号。

declare

i number:=1;

begin

loop

dbms_output.putline('输出i='||i);

if i=10 then

goto end_loop;

end if;

i:=i+1;

end loop;

<<end_loop>>

dbms_output.putline('循环结束');

end;

 

2)null语句

null语句不会执行任何操作,并且会直接将控制传递到下一条语句。

使用null语句的主要好处是可以提高pl/sql的可读性。

declare

v_sal emp.sal%type;

v_ename emp.ename%type;

begin

select enmae,sal into v_ename,v_sal from emp where empno=&no;

if v_sal < 3000 then

update emp set sal=sal*1.1 where ename=v_ename;

else

null;

end if;

end;

 

抱歉!评论已关闭.