plsql里用游标与if语句写存储过程比较字段大小的方法

运用场景

我有一张很多商品的四周销售表,

表的字段有商品代码、第一周、第二周、第三周、第四周的销售,现在想把这四周的最大销量找出来。

方法:

第一步,先创建一个字段有:商品代码、最大值这两列的表;

第二步,写存储过程,用loop循环if判断写入刚创建的表;

过程如下:

create or replace procedure P_yryp_zxsb_max is  --字段比大小
begin
  delete from yryp_zxsb_max;  --清除创建表中所有记录
  commit;
  insert into yryp_zxsb_max  --插入要查的所有商品代码
  select gbbarcode,0,0 from luckman@house;
  commit;
  declare                              --申明变量
  v_dm  yryp_zxsb.dm%type;
  v_sl1 yryp_zxsb.sl1%type;
  v_sl2 yryp_zxsb.sl1%type;
  v_sl3 yryp_zxsb.sl1%type;
  v_sl4 yryp_zxsb.sl1%type;
  cursor c_yryp is select dm,sl1,sl2,sl3,sl4 from yryp_zxsb;   --给游标赋值
  begin
    open c_yryp;      --打开游标
    loop     --循环开始
      fetch c_yryp into v_dm,v_sl1,v_sl2,v_sl3,v_sl4;    --给变量赋值
      exit when c_yryp%notfound;                  --当游标找不到数时退出
      if v_sl1>v_sl2 and v_sl1>v_sl3 and v_sl1>v_sl4   then        
        update  yryp_zxsb_max set hmax=v_sl1 where yryp_zxsb_max.dm=v_dm;    --把1放进创建的表
      elsif
        v_sl2>v_sl3 and v_sl2>v_sl1 and v_sl2>v_sl4 then        
        update  yryp_zxsb_max set hmax=v_sl2 where yryp_zxsb_max.dm=v_dm;   --把2放进创建的表
      elsif
        v_sl3>v_sl4 and v_sl3>v_sl1 and v_sl3>v_sl2 then         
        update  yryp_zxsb_max set hmax=v_sl3 where yryp_zxsb_max.dm=v_dm;  --把3放进创建的表
      elsif
        v_sl4>v_sl1 and v_sl4>v_sl2 and v_sl4>v_sl3 then   

        update  yryp_zxsb_max set hmax=v_sl4 where yryp_zxsb_max.dm=v_dm; --把4放进创建的表
      end if;      --if语句结束
      end loop;    --循环结束
      close c_yryp;   --关闭游标
      commit;
  end;
end P_yryp_zxsb_max;

检验:

select t.dm,t.sl1,t.sl2,t.sl3,t.sl4,w.hmax
 from yryp_zxsb t,yryp_zxsb_max w where t.dm=w.dm

 

posted @ 2021-03-29 14:44  蜕变大哥  阅读(650)  评论(0)    收藏  举报