PLSql -- 递归查询的另几种实现方式(函数/存储过程)

问题

这是一个树结构,查询教师“胡明星”的所有主管及姓名:(无主管的教师也需要显示),显示(教师编号、教师名称、主管编号、主管名称)

解决此问题的SQL语句见 Sql – 练习3 递归查询

解决1

 declare
  v_tno hand_teacher.teacher_no%type;
  v_mno hand_teacher.teacher_no%type;
begin
  select teacher_no
    into v_tno
    from hand_teacher
   where hand_teacher.teacher_name = '胡明星';

  -- produce
  dbms_output.put_line('------ procedure ----');
  dbms_output.put_line('Start with  ' || v_tno);

  search_manager(v_tno);

  --function
  dbms_output.put_line('------ function -----');
  dbms_output.put_line('Start with  ' || v_tno);

  while v_tno <> '0' loop
    v_mno := v_tno;

    v_tno := search_manager_F(v_tno);
  end loop;

exception
  when no_data_found then
    dbms_output.put_line('1111--no_data_found');
  when others then
    dbms_output.put_line(SQLCODE);
    dbms_output.put_line(SQLERRM);
end;
 -- function
create or replace function search_manager_F(t_no in hand_teacher.manager_no%type)
  return hand_teacher.manager_no%type is
  Result_value hand_teacher.manager_no%type;
begin
  select nvl(manager_no, '0')
    into Result_value
    from hand_teacher
   where teacher_no = t_no;

  if Result_value = '0' then
    dbms_output.put_line('END');
  else
    dbms_output.put_line(t_no || ' reports to ' || Result_value);
  end if;

  return(Result_value);

exception
  when no_data_found then
    dbms_output.put_line('2222--no_data_found');
  when others then
    dbms_output.put_line(SQLCODE);
    dbms_output.put_line(SQLERRM);

end search_manager_F;
--procedure
create or replace procedure search_manager(t_no in hand_teacher.teacher_no%type default 't003') is
  m_no hand_teacher.manager_no%type;
begin

  select nvl(manager_no, '0')
    into m_no
    from hand_teacher
   where teacher_no = t_no;

  if m_no = '0' then
    dbms_output.put_line('END');
  else
    dbms_output.put_line(t_no || ' reports to ' || m_no);
    search_manager(m_no);
  end if;

exception
  when no_data_found then
    dbms_output.put_line('2222--no_data_found');
  when others then
    dbms_output.put_line('2222--others');
end search_manager;

结果1

这里写图片描述

解决2

利用 Oracle WITH语句的解决

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值