我們在實際的項目開發過程中,經常會遇到類似的情況:要求在不同的數據庫表分塊中,查詢某些字段的數據信息並按照字符串的方式顯示出來,如何解呢?
遊標+動態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;