我们在实际的项目开发过程中,经常会遇到类似的情况:要求在不同的数据库表分块中,查询某些字段的数据信息并按照字符串的方式显示出来,如何解呢?

游标+动态sql的方式无疑是最好的解答;首先根据需求动态地建立sql语句,其次将执行的结果存储在游标当中,采用游标循环读取数据的方式获取数据,并以字符串打包返回;

上代码,大家可以直接复用(存储过程及函数中,参数不能定义长度):

create or replace function fun_getJLDHByYHBH(tmp_yhbh nvarchar2) return nvarchar2 is

result nvarchar2(255);

str_kh varchar2(2);

str VARCHAR2 (500);

--定义一个动态游标

type cur is ref cursor;

--声明一个动态游标变量

my_dept_rec cur;

strJLDH VARCHAR2 (20);

begin

if tmp_yhbh is null or tmp_yhbh='' then

return result;

end if;

select substr(tmp_yhbh,1,2) into str_kh from dual;

--使用连接符拼接成一条完整SQL

str := 'select JLDH from yh_test_'||str_kh||' where yhbh='||tmp_yhbh;

--动态执行sql将数据结果存储到游标中

open my_dept_rec for str ;

loop

--获取游标数据到字符串中

fetch my_dept_rec into strJLDH;

exit when my_dept_rec%notfound;

dbms_output.put_line(strJLDH);

--insert into tmp(usrmsisdn) values(mobile);

if result is null then

result:= strJLDH;

else

result:= result||' 、 '||strJLDH;

end if;

end loop;

--关闭游标

close my_dept_rec;

return result;

end;

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐