1. 程式人生 > >【oracle】oracle使用utl_file和sqlloard實現A表資料遷移至B表資料(欄位數和順序不一樣)

【oracle】oracle使用utl_file和sqlloard實現A表資料遷移至B表資料(欄位數和順序不一樣)

oracle使用utl_file和sqlloard實現A表資料遷移至B表資料(欄位數和順序不一樣)

資料庫版本:11.2.0.4;系統版本:CentOS Linux 6.8

使用utl_file方式從A表匯出部分欄位至文字,再使用sqlload方式載入進B表;
表test欄位:    tid,tname,tphone,taddr,tlog
表test_t欄位:    tid,tphone,tname

--建立directory
$ sqlplus / as sysdba
SQL> create directory UTL_DATA as '/data';
SQL> grant read,write on directory utl_data to test;
注:因11g以後使用directory替換utl_file授權test使用者可執行utl_file
 

SQL> grant execute on utl_file to test;

$ sqlplus test/123
SQL> declare
v_filehandle UTL_FILE.FILE_TYPE;
begin
v_filehandle:=utl_file.fopen('UTL_DATA','output_test.txt','w');
utl_file.putf(v_filehandle,'---export data from table test:', systimestamp);
utl_file.new_line(v_filehandle);
for i in (select * from test.test where rownum <= 100) loop
utl_file.putf(v_filehandle,'%s,%s,%s\n',i.tid,i.tphone,i.tname);
end loop;
utl_file.fclose(v_filehandle);
end;
/

PL/SQL procedure successfully completed.

使用sqlloard匯入目標表test_t

--建立控制檔案
# vi /data/test.txt
test.txt內容如下:
LOAD DATA
INFILE '/data/output_test.txt'
INTO TABLE test_t
TRUNCATE
fields terminated by ','
trailing nullcols
(tid,tphone,tname)

SQL> sqlldr test/123 control=/data/test.txt log=/data/log.txt bad=/data/log_bad.txt data=/data/output_test.txt
注:control=指定控制檔案和路徑  log=匯入日誌檔案儲存  bad=錯誤資訊  data=資料檔案