【发布时间】:2019-10-08 06:29:37
【问题描述】:
select语句在SYS_REFCURSOR中没有返回任何记录的情况如何处理?
我正在使用绑定变量的动态 sql 生成过程。
create or replace
procedure test_dynamic_sql
(
last_name varchar2,
rc out sys_refcursor,
jobid varchar2,
sdate date,
edate date,
status out varchar2,
message out varchar2 )
is
q long;
lname varchar2(240);
begin
q := 'select employee_id
from employees e
where 1=1';
if last_name is not null then
q := q || 'and (e.LAST_NAME = :LAST_NAME)';
else
q := q || 'and (1=1 or :LAST_NAME is null)';
end if;
if jobid is not null then
q := q || 'and (e.JOB_ID = :JOBID)';
else
q := q || 'and (1=1 or :JOBID is null)';
end if;
if sdate is not null then
q := q || 'and (e.hire_date >= :sdate)';
else
q := q || 'and (1=1 or :sdate is null)';
end if;
if edate is not null then
q := q || 'and (e.hire_date <= :edate)';
else
q := q || 'and (1=1 or :edate is null)';
end if;
open rc for q using last_name, jobid, sdate, edate;
/*
IF rc%NOTFOUND THEN
STATUS := 'NR';
MESSAGE := 'Not Found';
ELSE
STATUS := 'S';
MESSAGE := 'Found';
END IF;
*/
exception
when others then
STATUS :='E';
message := sqlcode||'-->'||sqlerrm;
end;
我尝试了%NOTFOUND 和%FOUND 属性,但它不起作用。
我也尝试过NO_DATA_FOUND 异常,但它也不起作用。
我需要将状态返回为“S”、“E”、“NR”
- S --> 成功(找到记录时)
- E --> ERROR(发生任何错误时)
- NR--> 无记录(当 0 条记录时)
谢谢!
【问题讨论】:
-
感谢 SKG。您能否确认这里的目标是报告游标是否有任何数据,但您不能/不打算从中
FETCH或使用它的数据? -
您需要在 where 子句中添加的每个条件之间添加一个空格以避免错误。为了检查是否存在,我会将查询更改为返回
SELECT COUNT(1),因此它将返回 0 表示未找到任何行,并添加一个and rownum < 2以限制为获得结果而处理的行。或者,保留所有内容,只需执行一次 FETCH 并检查%ROWCOUNT。 -
目前没有什么可以阻止代码找到两个同名员工。如果传递给此过程的唯一参数是名称,并且所有其他参数都作为 NULL 传递,则代码当前不处理此问题。
-
@alexgibbs 它正在为 out 参数提供输出,我可以使用匿名块打印记录。此代码中是否真的需要 fetch 语句,因为我在 rec 中获取输出,即 sys_refcursor out 参数。我会很感激你的帮助。
-
@CodeNovice 这只是一个示例代码。主要关注的是处理“未找到数据”。在我的原始代码中,将传递唯一的供应商代码。如果有同名的记录,那么问题是什么?它会根据搜索条件返回多条记录,如果我们需要区分,则必须传递其他参数,如加入日期、出生日期等。
标签: oracle plsql sys-refcursor