Oracle 函数不为未返回的行返回值
我创建了一个函数,该函数以电影id作为输入,并根据id返回股票信息。该函数主要起作用,但如果我想从数据库中不存在的电影中检索信息(不返回任何行),则不会返回任何信息。不知道为什么 当我调用一个不返回任何行的ID时,不会给我一个错误,这样异常处理就无法工作Oracle 函数不为未返回的行返回值,oracle,plsql,Oracle,Plsql,我创建了一个函数,该函数以电影id作为输入,并根据id返回股票信息。该函数主要起作用,但如果我想从数据库中不存在的电影中检索信息(不返回任何行),则不会返回任何信息。不知道为什么 当我调用一个不返回任何行的ID时,不会给我一个错误,这样异常处理就无法工作 create or replace function stock_info (p_id IN NUMBER ) return VARCHAR2 IS cursor c1 is select movi
create or replace function stock_info
(p_id IN NUMBER
)
return VARCHAR2
IS
cursor c1 is
select movie_id, movie_title, movie_qty
from mm_movie
where p_id = movie_id;
lv_movie_info VARCHAR2(100);
BEGIN
for i in c1 loop
if p_id = i.movie_id then
lv_movie_info := i.movie_title || ' is available: ' || i.movie_qty || ' on the shelf';
else
lv_movie_info := 'no data found';
end if;
end loop;
return lv_movie_info;
END STOCK_INFO;
/
当没有数据时,您没有得到任何东西的原因是循环没有执行。从逻辑上讲,For表达式表示“为游标中返回的每一行执行以下循环”,但游标中没有行,因此它从不执行循环。此外,该结构实际上表明您期望给定的p_id有多个。如果不是这样,您可以一起消除光标。假设p_id是主键,则您有0行或1行,因此:
create or replace function stock_info (p_id in number)
return text
is
lv_movie_info varchar2(100);
begin
select i.movie_title || ' is available: ' || i.movie_qty || ' on the shelf'
into lv_movie_info
from mm_movie i
where p_id = movie_id;
return lv_movie_info;
exceptions
when no_data_found
then return 'no data found';
end stock_info;
当然,如果确实需要更多的一行,则需要游标,但是if is not as the were子句保证它是真的。对于0行,循环将不会执行,因此“未找到数据”消息需要在“结束循环”之后
Belayer您使用的游标语句从in参数中获取数据。i、 例如,在光标中,根据传递的电影id选择限制 在传递不在数据库中的电影id时,游标select语句不会获取任何记录,因此流甚至不会进入for循环 如果您想返回未找到的数据-在传递不在数据库中的电影id时,有两种解决方法 1.在循环之前,让select语句根据您的需求将标志设置为Y或N(如果存在)。 2.如果不使用for cursor,则有一个选项用于选中“未找到…”。。。 样本:
declare
cursor c1 is select * from table_sample; -- empty table
c_rec c1%rowtype;
begin
open c1;
fetch c1 into c_rec;
if c1%notfound then
dbms_output.put_line('not found');
end if;
close c1;
end;
-- output
not found