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

来源:互联网 发布:toad oracle数据库管理 编辑:程序博客网 时间:2024/06/07 03:19

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

        游标+动态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;

       

0 0