当前位置: 代码迷 >> 综合 >> Oracle 存储过程及函数中游标+动态的sql处理
  详细解决方案

Oracle 存储过程及函数中游标+动态的sql处理

热度:18   发布时间:2024-01-20 17:31:51.0

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

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

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

      

create or replace function fun_getJLDHByYHBH(tmp_yhbh nvarchar2) return nvarchar2 isresult nvarchar2(255);str_kh varchar2(2);str   VARCHAR2 (500);--定义一个动态游标type cur is ref cursor;  --声明一个动态游标变量my_dept_rec cur;strJLDH   VARCHAR2 (20);
beginif tmp_yhbh is null or tmp_yhbh='' thenreturn 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;