我有这样的查询:
select data_name
into v_name
from data_table
where data_table.type = v_t_id
通常,此查询应该只返回一行。当v_t_id
上没有匹配项时,程序将失败并显示“未找到数据”例外。
我知道我可以在PL / SQL中处理这个问题,但我想知道是否有办法只在查询中执行此操作。作为测试,我试过了:
select case
when subq.data_name is null then
'UNKNOWN'
else
subq.data_name
end
from (select data_name
from data_table
where data_table.type = '53' /*53 does not exist, will result in 0 rows. Need fix this...*/
) subq;
...但这显然不起作用(因为subq
为空,与subq.data_name is null
不同)。这是可能的还是我应该检查我的PL / SQL解决方案?
(oracle 10g)
答案 0 :(得分:18)
有办法让这更简单,更清洁,但这基本上说明了这项技术:
SELECT data_name
FROM data_table
WHERE data_table.type = v_t_id
UNION ALL
SELECT NULL AS data_name
FROM dual
WHERE NOT EXISTS (
SELECT data_name
FROM data_table
WHERE data_table.type = v_t_id
)
当union的第一部分为空时,第二部分将包含一行,当第一部分不为空时,第二部分将不包含任何行。
如果查询需要花费很多时间,请使用以下内容:
SELECT * FROM (
SELECT data_name
FROM data_table
WHERE data_table.type = v_t_id
UNION ALL
SELECT NULL AS data_name
FROM dual
) WHERE data_name is not null or ROWNUM = 1
答案 1 :(得分:9)
我更愿意处理异常。但是,这可以在您指定时使用:
select min(data_name) data_name
into v_name
from data_table
where data_table.type = v_t_id
请注意,如果查询返回更多而不是1行,这也会“有效” - 即不会引发TOO_MANY_ROWS。
答案 2 :(得分:1)
select coalesce(data_table.data_name, d.data_name) data_name
into v_name
from
(SELECT 'UNKNOWN ' as data_name FROM DUAL) d
LEFT JOIN data_table
ON data_table.type = v_t_id
or a.data_table.data_name is null
答案 3 :(得分:1)
这是我使用LEFT OUTER JOIN的简单解决方案:
CREATE TABLE data_table(data_name VARCHAR2(20), data_type NUMBER(2));
INSERT INTO data_table(data_name, data_type) VALUES('fifty-one', 51);
SELECT coalesce(data_name, 'unknown')
FROM dual
LEFT OUTER JOIN (SELECT data_name FROM data_table WHERE data_type = 53) o
ON 1 = 1;
SELECT coalesce(data_name, 'unknown')
FROM dual
LEFT OUTER JOIN (SELECT data_name FROM data_table WHERE data_type = 51) o
ON 1 = 1;
答案 4 :(得分:0)
如果您总是期望零行或一行,那么您可以使用组函数,即:
select dump(max(dummy)) from dual
where dummy = 'Not Found'
在找不到记录的情况下,您将始终获得至少一行和NULL值。
答案 5 :(得分:0)
https://stackoverflow.com/a/4683045/471149答案很好,但有更短的解决方案
select * from my_table ce, (select 150 as id from dual) d
where d.id = ce.entry_id (+)