张三李四王五赵六 2020-05-11 15:45 采纳率: 0%
浏览 349

db2如何创建一个多重循环查询+递归查询的自定义函数

创建一个自定义函数,传入四个参数l_class,l_fault,l_id,l_type
如果传入的l_id为空则走这边
if l_id is null then
1.查询三张表的数据用union all拼接成一个结果集,获取到符合条件的结果集(不需要返回)

这里需要定义一个类似java的list,将查询出来的结果集加入到list中

select id,name,type,s from
(
select id,name,'t1' type,s from t1 where name=l_class
union all
select id,name,'t2' type,s from t2 where name=l_class
union all
select id,name,'t3' type,s from t3 where name=l_class
)
order by s fetch first 10 rows only

2.如果有数据,那么就遍历结果集(不需要返回)
for li in (上面的语句) loop

if li.type='t1' and s>=0 then

再次循环,递归查询这张表的所有子数据,通过id查询需要的结果集

WITH RPL (parentid, id, name) AS
(
SELECT ROOT.parentid, ROOT.id, ROOT.name FROM t1 ROOT where ROOT.id=li.id
UNION ALL

SELECT CHILD.parentid, CHILD.id, CHILD.name FROM RPL PARENT, t1 CHILD WHERE PARENT.id= CHILD.parentid
)
select RPL.id, RPL.name from RPL

for li in (上面的语句) loop

select id,title,'t1' type from t4 where itemid=li.id and title like '%l_fault%'
(加入到list中)

if li.type='t2' and s>=0 then

select id,content,'t2' type from t5 where classid=li.id and content like '%l_fault%'
(加入到list中)

if li.type='t3' and s>=0 then
select id,content,'t3' type from t6 where classid=li.id and content like '%l_fault%'
(加入到list中)

将这三个结果集拼成一个(list),取前10条返回,则l_id is null分支结束

如果l_id不为null则返回一条结果

if l_id is not null then

1.判断类型,查询不同的表

if l_type = 't1'

select conten from xxx where id=l_id(返回一条结果)

if l_type = xxx

select xxx form xxx where xx=l_id

l_id为null分支结束,整个函数流程完成

  • 写回答

1条回答 默认 最新

  • zqbnqsdsmd 2020-05-13 01:32
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案