1. 程式人生 > >轉換一個字段中含有多個另外一張表的id | | 行轉列

轉換一個字段中含有多個另外一張表的id | | 行轉列

ret .net sub 模式 end posit tex 匹配 replace

1、Oracle Function

--入參:表 id

/*

cxcyxm02 :操作表,含有一個存儲另一張表(xs0101)多個主鍵id的字段

 ids :操作表的主鍵 id

*/

CREATE OR REPLACE FUNCTION cxcyxmcyry(ids VARCHAR2) RETURN VARCHAR2 IS
tempcyryxx VARCHAR2(1000);
cyryxx VARCHAR2(1000);
cxcylength number;
i number;
BEGIN
i := 0;
select LENGTH(t.cymc) - LENGTH(REGEXP_REPLACE(t.cymc, ‘,‘, ‘‘)) + 1 as leng
into cxcylength
from cxcyxm02 t
select nvl(xm ||‘/‘|| xh, ‘‘)
into tempcyryxx
where cxcyxm02id = ids;
while i < cxcylength loop
if i = 0 then
from xs0101
where xs0101id = (select substr(concat(t.cymc, ‘,‘),
0,
instr(concat(t.cymc, ‘,‘), ‘,‘, 1, 1) - 1)
from cxcyxm02 t
where t.cxcyxm02id = ids);
else
select nvl(xm || xh, ‘‘)
into tempcyryxx
from xs0101
where xs0101id =
(select substr(concat(t.cymc, ‘,‘),
instr(concat(t.cymc, ‘,‘), ‘,‘, 1, i) + 1,
instr(concat(t.cymc, ‘,‘), ‘,‘, 1, i + 1) -
instr(concat(t.cymc, ‘,‘), ‘,‘, 1, i) - 1)
from cxcyxm02 t
where t.cxcyxm02id = ids);
end if;
i := i + 1;
if i = cxcylength then
cyryxx := cyryxx || tempcyryxx;
else
cyryxx := cyryxx || tempcyryxx || ‘,‘;
end if;
end loop;
return cyryxx;

END cxcyxmcyry;

2. Oracle自帶函數

connect by level 是Oracle中一組關鍵字,是用來實現遞歸查詢的,譬如說實現查詢 1,2,3,4 .....n 的數字可以使用connect by level;

select level +1 from dual where connect by level <=10 ;
這種方式可以實現查詢1到n的數字,共有n行;
select level from dual connect by level < 10;

REGEXP_SUBSTR函數格式如下:
function REGEXP_SUBSTR(String, pattern, position, occurrence, modifier)
__srcstr :需要進行正則處理的字符串
__pattern :進行匹配的正則表達式
__position :起始位置,從第幾個字符開始正則表達式匹配(默認為1)
__occurrence :標識第幾個匹配組,默認為1
__modifier :模式(‘i‘不區分大小寫進行檢索;‘c‘區分大小寫進行檢索。默認為‘c‘。)
實際應用如下:在Oracle中,使用一條語句實現將‘34,56,-23‘拆分成‘34‘,‘56‘,‘-23‘的集合

SELECT REGEXP_SUBSTR(‘34,56,-23‘, ‘[^,]+‘, 1, LEVEL, ‘i‘) AS STR
FROM DUAL
CONNECT BY LEVEL <= LENGTH(‘34,56,-23‘) -
LENGTH(REGEXP_REPLACE(‘34,56,-23‘, ‘,‘, ‘‘)) + 1;


Oracle 行轉列pivot 、列轉行unpivot 的Sql語句總結
http://blog.csdn.net/xiaokui_wingfly/article/details/42419207

轉換一個字段中含有多個另外一張表的id | | 行轉列