英文:
PL/SQL function returns multiple rows
问题
create or replace function DEF_ID(
in_checkid IN SQLTEXTDEFN.SQLID%type
)
return varchar2
as
sql_stmt clob;
ret varchar2(254);
begin
begin
execute immediate 'select SQLTEXT from SQLTEXTDEFN where sqlid=:1'
into sql_stmt
using in_checkid;
begin
execute immediate sql_stmt into ret;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 'NO DATA FOUND';
when others then
return substr(sqlerrm,1,200);
end;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 'NO CHECK FOUND';
when others then
return substr(sqlerrm,1,200);
END;
return ret;
end;
The SQLTEXTDEFN table is a table with different SQL statements. When I execute this function a get the response of the SQL statement. In certain cases I get an error:
ORA-01422: exact fetch returns more than requested number of rows
I only want the first row as a result if multiple rows are fetched.
英文:
I Have a function in Oracle SQL Database like this
create or replace function DEF_ID(
in_checkid IN SQLTEXTDEFN.SQLID%type
)
return varchar2
as
sql_stmt clob;
ret varchar2(254);
begin
begin
execute immediate 'select SQLTEXT from SQLTEXTDEFN where sqlid=:1'
into sql_stmt
using in_checkid;
begin
execute immediate sql_stmt into ret;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 'NO DATA FOUND';
when others then
return substr(sqlerrm,1,200);
end;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 'NO CHECK FOUND';
when others then
return substr(sqlerrm,1,200);
END;
return ret;
end;
The SQLTEXTDEFN table is a table with different SQL statements. When I execute this function a get the response of the SQL statement. In certain cases I get an error:
ORA-01422: exact fetch returns more than requested number of rows
I only wants the first row as result if multiple rows are fetched.
答案1
得分: 1
只返回翻译好的部分:
将结果限制为仅一行:
execute immediate 'select SQLTEXT from SQLTEXTDEFN where sqlid=:1 and rownum = 1';
如果SQLTEXT是一个varchar2,只需对其执行MAX函数更加安全:
execute immediate 'select MAX(SQLTEXT) from SQLTEXTDEFN where sqlid=:1';
这将防止重复行和没有行的异常。但如果它是一个CLOB,那么请添加异常处理以静默处理NO_DATA_FOUND。
英文:
Limit your result to only one row:
execute immediate 'select SQLTEXT from SQLTEXTDEFN where sqlid=:1 and rownum = 1'
If SQLTEXT is a varchar2, it's even safer to just do a MAX on it:
execute immediate 'select MAX(SQLTEXT) from SQLTEXTDEFN where sqlid=:1'
That will prevent both exceptions for duplicate rows and no rows. But you can't do that if it's a CLOB. In that case, add exception handling to quietly handle NO_DATA_FOUND.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论