我有一个复杂的查询,必须使用一个名为SubUnitRate
的数字。此变量来自具有特殊条件的另一个表。总之,我们有:
DECLARE
SUBUNITRATE NUMBER;
BEGIN
SELECT NVL (NULLIF (CU.SUBUNITRATE, 0), 1)
INTO SUBUNITRATE
FROM CURRENCYS CU
JOIN ACCOUNTS ACC ON CU.ID = ACC.CURRENCY
WHERE ACC.ID = :ACCOUNTID;
END;
SELECT SUBUNITRATE * 100 FROM DUAL;
我的目标是获得(在简单情况下)的结果:
SELECT SUBUNITRATE * 100 FROM DUAL;
但这怎么可能?
答案 0 :(得分:2)
PL / SQL块不能将查询结果作为查询返回。相反,您可以打印出结果。
那么,这会做你想做的吗?
DECLARE
SUBUNITRATE NUMBER;
BEGIN
SELECT NVL(NULLIF(CU.SUBUNITRATE, 0), 1)
INTO SUBUNITRATE
FROM CURRENCYS CU JOIN
ACC
ON CU.ID = ACC.CURRENCY
WHERE ACC.ID = :ACCOUNTID;
DBMS_OUTPUT.PUT_LINE(SUBUNITRATE * 100)
END;
答案 1 :(得分:2)
假设您想在同一个查询中多次使用SUBUNITRATE的值,您可以使用WITH子句:
with cte as (
select case
when CU.SUBUNITRATE = 0 then 1
else CU.SUBUNITRATE
end as SUBUNITRATE
FROM CURRENCYS CU
JOIN ACCOUNTS ACC ON CU.ID = ACC.CURRENCY
WHERE ACC.ID = :ACCOUNTID
)
select cte.SUBUNITRATE * 100
from cte;
答案 2 :(得分:0)
不需要PL。 APC的解决方案,简化并以您可以直接在您的查询中使用的形式(无论您在哪里说... = subunitrate,说... =(从cte中选择sur)而不是 - 包括括号):
with cte_prelim as (select subunitrate from ... etc.),
cte (sur) as select case when subunit rate is null or subunitrate = 0 then 100
else subunitrate * 100 end from cte_prelim)
select... (your query where you need to use the value)