PL/SQL编程

编写代码实现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

可以在此段代码执行前后分别获取当前时间,检查其两种方式所用时间的差别

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值