1. 程式人生 > >關於Oracle中instr和wm_concat函式的使用

關於Oracle中instr和wm_concat函式的使用

先建立兩張表

instr是字元查詢函式,如果找到會返回第一次出現的位置,我們可以用作模糊查詢,例如:

select * from table2 where instr(table1Id, '1') > 0

結果為:

可以看到查詢出來的是table1Id列包括1的字串。

我們可以通過table2中的table1Id去查詢table1的名字,例如我們查詢table2中id= 2的資料包含table1中的哪些名字:

select * from table1 t where instr(';' || (select table1Id from table2 where id = 1) || ';', ';' || t.id || ';') > 0;

結果為:

table2中id=1的table1Id為"2;3",所以查詢出來的是table1中id為2和3的資料。

關於wm_concat函式,該函式可以把列值以","號分隔起來,並顯示成一行。例如:

select wm_concat(t.name) from table1 t

可是結果發現為plsql中為<clob>,只需要再使用to_char函式就可以了

select to_char(wm_concat(t.name)) from table1 t

結果為:

我們再以上面select * from table1 t where instr(';' || (select table1Id from table2 where id = 1) || ';', ';' || t.id || ';') > 0;這條語句為例將查詢結果一行輸出:

select to_char(wm_concat(t.name)) from table1 t where instr(';' || (select table1Id from table2 where id = 1) || ';', ';' || t.id || ';') > 0;

結果為: