PL/SQL实例
1.定义变量和常量的区别在于关键字(constant) ,有的是常量
(1)定义变量
a int:=100;
(2)定义常量
a constant int:=100;
2、流程控制语句
2-1. 选择语句
2-1-1 if…then语句
DECLARE
deptno VARCHAR2(50);//定义两个字符串常量
loc VARCHAR2(50);
begin
deptno:='编号';//给两个字符串赋值
loc:='所在位置';
if length(deptno)<length(loc)then //比较两个字符串长度
//输出比较后的结果
dbms_output.put_line('字符串“'||deptno||'”的长度比字符串“'||loc||'”的长度小');
end if;
end;
2-1-2 if …then …else
DECLARE
deptno VARCHAR2(50);
loc VARCHAR2(50);
begin
deptno:='编号11111';
loc:='所在位置';
if length(deptno)<length(loc)then
dbms_output.put_line('字符串“'||deptno||'”的长度比字符串“'||loc||'”的长度小');
else
dbms_output.put_line('字符串“'||deptno||'”的长度比字符串“'||loc||'”的长度大');
end if;
end;
2-1-3 if…then …elsif
DECLARE
deptno VARCHAR2(50);
loc VARCHAR2(50);
begin
deptno:='编号11';
loc:='所在位置';
if length(deptno)<length(loc)then
dbms_output.put_line('字符串“'||deptno||'”的长度比字符串“'||loc||'”的长度小');
elsif length(deptno)=length(loc) then
dbms_output.put_line('字符串“'||deptno||'”的长度比字符串“'||loc||'”的长度相等');
else
dbms_output.put_line('字符串“'||deptno||'”的长度比字符串“'||loc||'”的长度大');
end if;
end;
2-1-4 case…when
DECLARE
season int:=3;
aboutinfo VARCHAR2(50);
begin
case season
when 1 then
aboutinfo:=season||'季度包括1、2、3月份';
when 2 then
aboutinfo:=season||'季度包括4、5、6月份';
when 3 then
aboutinfo:=season||'季度包括7、8、9月份';
when 4 then
aboutinfo:=season||'季度包括10、11、12月份';
else
aboutinfo:=season||'季度不合法';
end case;
dbms_output.put_line(aboutinfo);
end;
2-2 循环语句
2-2-1 loop循环
declare
i int:= 0;
sum_i int :=0;
begin
loop //循环开始
i := i + 1;//循环体
sum_i := i + sum_i;
exit when i =100; //结束循环的条件
end loop;
dbms_output.put_line( '前100个自然数的和是'||sum_i);
end;
2–2-2 while
declare
i int:= 0;
sum_i int :=0;
begin
while i<=99 loop
i := i + 1;
sum_i := i + sum_i;
end loop;
dbms_output.put_line( '前100个自然数的和是'||sum_i);
end;
2-2-3 for
declare
sum_i int :=0;
begin
for i in reverse 1..100 loop //reverse 可有可无,有i初始是100递减,否则相反
dbms_output.put_line(i);
if mod(i,2)=0 then //判断是否为偶数
sum_i :=sum_i+i;
end if;
end loop;
dbms_output.put_line( '前100个自然数的偶数和是'||sum_i);
end;