我试图在游标中使用c_msisdn值进行选择查询,但是它给出了没有找到数据的错误,但是如果我自己提供的价值就像WHERE MSISDN =' 315XXX'而不是WHERE MSISDN = c_msisdn返回结果。如何在select中使用游标值。
DECLARE
c_msisdn SSM_SMSCDATA.MSISDN%type;
c_status SSM_SMSCDATA.STATUS%type;
c_promo_id SSM_SMSCDATA.PROMO_ID%type;
view_all_status char(50) := '';
unsub_all_status char(50) := '';
services_subscribed char(400) := '';
CURSOR c_smscdata is SELECT MSISDN, STATUS, PROMO_ID FROM SSM_SMSCDATA;
BEGIN
OPEN c_smscdata;
LOOP
FETCH c_smscdata into c_msisdn, c_status, c_promo_id;
SELECT SUBSCRIPTION_ID into services_subscribed FROM (SELECT LISTAGG(SUBSCRIPTION_ID, '-') WITHIN GROUP (ORDER BY MSISDN) AS SUBSCRIPTION_ID
FROM SINGLESUBSCRIPTION
WHERE MSISDN = c_msisdn
GROUP BY MSISDN);
IF c_promo_id = '2' THEN
view_all_status := 'View All';
ELSE view_all_status := 'Unsub All';
END IF;
IF c_status = 3 THEN
unsub_all_status := 'View Successful';
ELSE unsub_all_status := 'Unsuccessful';
END IF;
INSERT INTO SSM_DAILY_REPORT (msisdn,view_all,unsub_all,SERVICES)
VALUES (c_msisdn,view_all_status,unsub_all_status,services_subscribed);
--dbms_output.put_line(c_msisdn || ' ' || c_status || ' ' || c_promo_id);
EXIT
WHEN c_smscdata%notfound;
END LOOP;
CLOSE c_smscdata;
END;
答案 0 :(得分:1)
您获取NO_DATA_FOUND异常的最可能原因是您的ssm_smscdata表中的msisdn值在您的singlesubscription表中不存在。
如果我是你,我不会费心使用游标进行循环。相反,我会在一个INSERT语句中完成所有操作,如下所示:
INSERT INTO ssm_daily_report (msisdn, view_all, unsub_all, services)
SELECT scs.msisdn,
CASE WHEN scs.promo_id = '2' THEN 'View All';
ELSE 'Unsub All'
END view_all_status,
CASE WHEN scs.status = 3 THEN 'View Successful';
ELSE 'Unsuccessful'
END unsub_all_status,
sss.services_subscribed
FROM ssmsmscdata scs
INNER JOIN (SELECT msisdn,
LISTAGG(subscription_id, '-') WITHIN GROUP (ORDER BY msisdn) AS services_subscribed
FROM singlesubscription
GROUP BY msisdn) sss ON sss.msisdn = scs.msisdn;
这样,你就可以避免重新发明嵌套循环连接(释放Oracle以选择它认为最好使用的连接类型,这可能是也可能不是嵌套循环)。您还可以避免游标循环涉及的所有上下文切换和逐行处理,并让Oracle一举完成所有工作。
此外,通过执行内部联接,可以避免出现在ssm_smscdata表中但不会出现单个订阅的棘手问题,因为这些行不会被返回。如果您还需要返回这些行,则需要将上述查询中的INNER JOIN
转换为OUTER JOIN
。