张三李四王五赵六 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
    关注
    评论

报告相同问题?

悬赏问题

  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面