数据库函数练习1

test表数据如下:

ikey      cname   pikey

1           集团       0

2           公司       1

3           部门       2

4           个人       3

试写一递归函数,传入ikey值,遍历取出pikey值。运行时如传入ikey为4,则该函数遍历取出pikey值依次为3、2、1、0,最后返回0显示到前台。

--创建表
drop table test;
drop sequence seq_test;
create sequence seq_test;
create table test(
 ikey number(5) primary key,
 cname varchar2(10),
 pikey number(3)
);
insert into test values(seq_test.nextval,'集团',0);
insert into test values(seq_test.nextval,'公司',1);
insert into test values(seq_test.nextval,'部门',2);
insert into test values(seq_test.nextval,'个人',3);
commit;
select * from test;
--函数
create or replace function func_test(i_int in number)
return number
is
  result number(3);
  temp number(3);
  type ref_cursor is ref cursor;
  v_cursor ref_cursor;
begin
  open v_cursor for 'select pikey from test where ikey<= '||i_int||'order by ikey desc';
  loop
    fetch v_cursor into temp;
    exit when v_cursor%notfound;
    dbms_output.put_line(temp);
    if(temp=0) then
      result:=temp;
      goto label1;
    end if;
  end loop;
  <<label1>>
  close v_cursor;
  return result;
  exception
    when others then 
      if(v_cursor%isopen) then
        close v_cursor;                    
      end if;
      return '';
end;
--测试
declare
  v_pikey number;
begin
  v_pikey :=func_test(4);
  dbms_output.put_line('结果值:'||v_pikey);
end;



转载于:https://www.cnblogs.com/archermeng/p/7537395.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值