编写代码实现1+2+3+...+100等于多少。
1.
declare
n int;
result int;
begin
n:=0;
result:=0;
while n<=100 loop
result :=result+n;
n:=n+1;
end loop;
dbms_output.put_line('结果是'||result);
end;
2.写一个存储过程。
create or replace procedure p_sumk(x int)
as
temp int;
result int;
begin
temp:=0;
result:=0;
while temp<=x loop
result :=result+temp;
temp:=temp+1;
end loop;
dbms_output.put_line('结果是'||result);
end;
exec p_sumk(100);//执行存储过程
3.写一个函数
create or replace function sumk(x int) return int
as
temp int;
result int;
begin
temp:=0;
result:=1;
while temp<=x loop
result :=result+temp;
temp:=temp+1;
end loop;
dbms_output.put_line('结果是'||result);
return result;
end;
select sumk(100) from dual;
四、存储过程与函数的应用 1、编写将指定部门号的所有员工薪水增加指定值的存储过程,并调用此存储过程将30号部门的薪水增加1000 编写存储过程 sp_AlterSalByDeptno(pSalDelta,pDeptno) 调用存储过程将30号部门的薪水增加1000元 execute sp_AlterSalByDeptno(1000,30) 与使用update语句进行对比 create or replace procedure sp_AlterSalByDeptno(pSalDelta int,pDeptno int) as begin update emp set sal=sal+pSalDelta where deptno=pDeptno; end; execute sp_AlterSalByDeptno(1000,30) 2、编写求指定部门号的所有员工平均薪水的函数,并调用此函数计算30号部门的平均薪水 编写函数 f_GetAvgSalByDeptno(pDeptno) 调用函数求出30号部门的平均薪水并显示tempSal:=f_GetAvgSalByDeptno(30) 与使用select语句进行对比 create or replace function f_GetAvgSalByDeptno(pDeptno int) return int as tempsal int; begin select avg(sal) into tempsal from emp where deptno=pDeptno; return tempsal; end; declare temsal int default 10; begin temsal:=f_GetAvgSalByDeptno(30); DBMS_OUTPUT.PUT_LINE('结果是'||temsal); end; 3、结论 需要频繁重复的数据库操作通常会编制专门的存储过程或函数 存储过程应用: 先创建存储过程(编写sql语句,将编写的代码编译后保存在数据库中,同时存储了编写的plsql语句和对应的编译后的机器操作指令),再使用存储过程(直接调用机器操作指令) sql语句:update emp set sal=sal+1000 where deptno=30;先检查sql是否正确,再转换成机器操作指令,最后执行机器操作 对比: while deptno in(10,20,30) loop execute alterSalBydeptno(delta,target); ---1 每次只需直接执行 update emp set sal=sal+delta where deptno=target; ---2 每次执行都要检查、转换、执行 DeptnoMoveNext(); end loop 可以在此段代码执行前后分别获取当前时间,检查其两种方式所用时间的差别