Oracle Spool的用法小結

來源:互聯網
上載者:User

 在生產中常會遇到需要將數量比較大的表值匯入到本地文字檔中. 方法有很多種,比較常用的就是spool命令: 要輸出符合要求格式的資料檔案只需在select時用字元串連來標準格式。比如有如下表

    SQL>; select id,username,password from myuser;//測試表

    1 John    1234

    2 Jack    12345

    3 Rose    2345

    4 Joe        384657

    5 Tom        384655

    6 Jordan     384455

    要輸出符合1,John,1234,這樣的資料格式就用select id||','||username||','||password||',' from myuser這樣的語句。

    SQL>; select id||','||username||','||password||',' from myuser;

    1,John,1234,

    2,Jack,12345,

    寫個下面這樣的指令碼就行可以輸出符合要求格式的資料至檔案中,不會含有其它不需要東西,只有資料部分。

    --指令檔名為expmyusr.sql,存資料的檔案名稱為e:/exp.txt

    set echo on            --是否顯示執行的命令內容  set feedback off       --是否顯示 * rows selected  set heading off        --是否顯示欄位的名稱set verify off         --是否顯示替代變數被替代前後的語句。filset trimspool off      --去欄位空格

    set pagesize 1000      --頁面大小set linesize 50//linesize設定盡量根據需要來設定,大了產生的檔案也大

    define fil= 'e:/exp.txt'

    prompt *** Spooling to &fil

    spool &fil

    select id||','||username||','||'"'||password||'"' from myuser;

    spool off;

    --執行過程

    SQL>; @e:/expmyusr.sql

    *** Spooling to e:/exp.txt

    1,John,"1234"

    2,Jack,"12345"

    3,Rose,"2345"

    4,Joe,"384657"

    5,Tom,"384655"

    6,Jordan,"384455"

    檢查可知結果符合要求。

    ·Oracle SPOOL的兩種方法之對比

    通常情況下,我們使用SPOOL方法,將資料庫中的表匯出為文字檔的時候會採用兩種方法,如下述:

 

 

方法一:採用以下格式指令碼

    set colsep '' ------設定資料行分隔符號

    set trimspool on

    set linesize 120

    set pagesize 2000

    set newpage 1

    set heading off

    set term off

    spool 路徑+檔案名稱

    select * from tablename;

    spool off

 

 

 

方法二:採用以下指令碼

 

    set trimspool on

    set linesize 120

    set pagesize 2000

    set newpage 1

    set heading off

    set term off

    spool 路徑+檔案名稱

    select col1||','||col2||','||col3||','||col4||'..' from tablename;

    spool off

    比較以上方法,即方法一採用設定分隔字元然後由sqlplus自己使用設定的分隔字元對欄位進行分割,方法二將分隔字元拼接在SELECT語句中,即手工控制輸出格式。

    在實踐中,我發現通過方法一匯出來的資料具有很大的不確定性,這種方法匯出來的資料再由sql ldr匯入的時候出錯的可能性在95%以上,尤其對大批量的資料表,如100萬條記錄的表更是如此,而且匯出的資料檔案狂大。

    而方法二匯出的資料檔案格式很規整,資料檔案的大小可能是方法一的1/4左右。經這種方法匯出來的資料檔案再由sqlldr匯入時,出錯的可能性很小,基本都可以匯入成功。

    因此,實踐中我建議大家使用方法二手工去控制spool檔案的格式,這樣可以減小出錯的可能性,避免走很多彎路。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.