1. 程式人生 > >2個sql 函數dbms_lob.substr 和 wm_concat

2個sql 函數dbms_lob.substr 和 wm_concat

fonts sselect 神奇 avi fill 基表 values tex fcm

轉自:

http://blog.csdn.net/wenzhongyan/article/details/50315473

http://blog.csdn.net/ojerryzuo/article/details/53927057

1、通過dbms_lob.substr()轉換clob字段為varchar2類型

在查詢dba_stat_extensions視圖的時候,其中extension字段是clob類型,直接通過select語句無法顯示,如下:

技術分享圖片

需要通過dbms_lob.substr()轉換

SELECT owner ,a.table_name,trim(dbms_lob.substr(extension,4000)) as extension FROM dba_stat_extensions a 轉換後顯示如下:

2.

首先讓我們來看看這個神奇的函數wm_concat(列名),該函數可以把列值以","號分隔起來,並顯示成一行,接下來上例子,看看這個神奇的函數如何應用
準備測試數據
SQL> create table test(id number,name varchar2(20));
SQL> insert into test values(1,‘a‘);
SQL> insert into test values(1,‘b‘);
SQL> insert into test values(1,‘c‘);
SQL> insert into test values(2,‘d‘);
SQL> insert into test values(2,‘e‘);
SQL> commit;
效果1 : 行轉列
SQL> select wm_concat(name) from test;
WM_CONCAT(NAME)
-------------------------------------------------------------------------
a,b,c,d,e
效果2: 把結果裏的逗號替換成"|"
SQL> select replace(wm_concat(name),‘,‘,‘|‘) from test;
REPLACE(WM_CONCAT(NAME),‘,‘,‘|‘)
-----------------------------------------------------------------------
a|b|c|d|e
效果3:按ID分組合並name
SQL> select id,wm_concat(name) name from test group by id;
ID NAME
---------- ------------------------------
1 a,b,c
2 d,e
懶人擴展用法:
案例:我要寫一個視圖,類似"create or replace view as select 字段1,...字段50 from tablename" ,基表有50多個字段,要是靠手工寫太麻煩了,有沒有什麽簡便的方法? 當然有了,看我如果應用wm_concat來讓這個需求變簡單
SQL> select ‘create or replace view as select ‘|| wm_concat(column_name) || ‘ from dept‘from user_tab_columns where table_name=‘DEPT‘;
‘CREATEORREPLACEVIEWASSELECT‘||WM_CONCAT(COLUMN_NAME)||‘FROMDEPT‘
--------------------------------------------------------------------------------
create or replace view as select DEPTNO,DNAME,LOC from dept

2個sql 函數dbms_lob.substr 和 wm_concat