-----------------------------------------------------------------------------
*****************************************************************************
第三部分:编写控制结构语句
*****************************************************************************
-----------------------------------------------------------------------------


--1.简单条件分支语句
declare
v_sal number(6,2);
begin
select sal into v_sal from emp
where lower(ename)=lower('&&name');
if v_sal <2000 then
update emp set sal=v_sal+200
where lower(ename)=lower('&name');
end if;
dbms_output.put_line('你输入的员工存在,工资已经调整,请验证!');
end;

 

--2.二重分支语句

declare
v_comm number(6,2);
begin
select comm into v_comm from emp
where empno=&&no;
if v_comm <>0 then
update emp set comm=v_comm+100
where empno=&&no;
else
update emp set comm=200 where empno=&&no;
end if;
dbms_output.put_line('数据处理完毕,请验收');
end;


--3.elsif测试

declare
sal number:=500;
comm number;
begin
 if sal<100 then
 comm:=0;
 elsif sal<600 then
 comm:=sal*0.1;
 elsif sal<1000 then
 comm:=sal*0.15;
 else
 comm:=sal*0.2;
 end if;
 dbms_output.put_line(comm);
end;

--4.case测试

declare
v_sal number:=1000;
v_tax number;
begin
case
when v_sal<1500 then
v_tax:=v_sal*0.03;
when v_sal<2500 then
v_tax:=v_sal*0.04;
when v_sal<3500 then
v_tax:=v_sal*0.05;
when v_sal <8000 then
v_tax:=v_sal*0.04;
end case;
dbms_output.put_line(v_tax);
end;

--5.loop循环
/*案例01:将1到10插入到表temp表*/

create table temp(cola int);
declare
i int:=1;
begin
  loop
  insert into temp values (i);
  exit when i=10;
   i:=i+1;
end loop;
end;

/*案例02:计算1+2+3+...10的结果集*/
--方法1:先求和再加1(推荐)
declare
  res int:=0;
  i int:=0;
begin
  loop
  res:=res+i;
  exit when i=10;
  i:=i+1;
end loop;
dbms_output.put_line('结果是:'|| res);
end;

--或则--

declare
res int:=0;
i int:=1;
begin
loop
res:=res+i;
exit when i=10;
i:=i+1;
end loop;
dbms_output.put_line('结果是:'|| res);
end;

 

--方法2:先加1再求和
declare
res int:=0;
i int:=0;
begin
loop
i:=i+1;
exit when i>10;
res:=res+i;
end loop;
dbms_output.put_line('结果是:'|| res);
end;


--6.while循环
/*案例01:计算1+2+3+...10的结果集*/

--方法1:(推荐)先求和再加1
declare
res int:=0;
i int:=0;
begin
while i<11 loop  --如果小于10则只是循环9次
res:=res+i;  --第一次0+0就相当于没有相加
i:=i+1;
end loop;
dbms_output.put_line('结果是:'|| res);
end;

 


--方法2:先加1再求和
declare
res int:=0;
i int:=0;
begin
while i<10 loop
i:=i+1;
res:=res+i;
end loop;
dbms_output.put_line('结果是:'|| res);
end;

 


/*案例02:*/
declare
i int:=1;
begin
while i<=10 loop
insert into temp values (i);
i:=i+1;
end loop;
end;


--7.for循环
declare
res int:=0;
begin
for i in 1..10 loop
res:=res+i;
end loop;
dbms_output.put_line('结果是:'|| res);
end;

--8.null的使用
declare 
thisday date;
begin
 thisday:=sysdate;
if thisday <to_date('2006-03-12', 'yyyy-mm-dd' )then  /*通过格式转换,最好按照这样的转换*/
 dbms_output.put_line('this is day:' ||to_char(thisday,'yyyy-mm-dd'));
 else
   null;
 end if;
exception
 when no_data_found then
 dbms_output.put_line('没有数据');
end;