Key List 字串(AB),要如何取得對應的 Name List(大學,碩士) 呢?
環境: Oracle 11G
最近同事問說他有一個 Key List 字串(AB),要如何取得對應的 Name List(大學,碩士) 呢?
因為要跟 Table 去 Join 所以必須要將 AB 轉成 Table。
這時就可以使用 CTE 來轉,如下,
with codesTable as (
select 'AB' as org_str from dual
)
select substr(org_str, level, 1) elem
from codesTable
connect by substr(org_str, level, 1) is not null;
即然 Table 有產生出來了,再來就是跟 Code Table 去 Join 就可以了,如下,
-- 先建立 Code Table
create table code1
(
codeValue char(1),
codeName varchar2(30)
);
insert into code1(codevalue, codename) values('A', '大學');
insert into code1(codevalue, codename) values('B', '碩士');
select * from code1;
--跟 code1 join
select *
from
( with codesTable as (
select 'AB' as org_str from dual
)
select substr(org_str, level, 1) elem
from codesTable
connect by substr(org_str, level, 1) is not null ) a
inner join code1 b
on a.elem = b.codevalue;
有成功取得結果後,就可以用 function 去包裝起來,如下,
CREATE OR REPLACE FUNCTION FN_GETMYCODENAMES(
strCODE_IDs IN VARCHAR2 )
RETURN VARCHAR2 IS
intPos int := 0;
strCODE_NAMEs VARCHAR2(1000) := '';
BEGIN
DECLARE CURSOR inputCodes IS
select codename
from
( with codesTable as (
select strCODE_IDs as org_str from dual
)
select substr(org_str, level, 1) elem
from codesTable
connect by substr(org_str, level, 1) is not null ) a
inner join code1 b
on a.elem = b.codevalue;
BEGIN
FOR inputCodes_rec IN inputCodes
LOOP
strCODE_NAMEs := strCODE_NAMEs || inputCodes_rec.codename || ',';
END LOOP;
END;
intPos := LENGTH(strCODE_NAMEs);
if intPos > 0 then
strCODE_NAMEs := SUBSTR(strCODE_NAMEs, 1, intPos -1);
end if;
RETURN strCODE_NAMEs;
END; -- FN_GETMYCODENAMES
使用如下,
select FN_GETMYCODENAMES('AB') from dual;
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^