【20150711】周總結【批量更新trick,UTF_FILE的文件操作,cur與循環

1、批量表更新的trick


使用拼接方法進行表結構轉移

將表名存放在一個文本清單中每行一個
使用外表讀取文本清單,設置外表名爲table_list
使用語句
select 'drop table '||TABLE_NAME||';'||chr(10)
       ||'create table '||TABLE_NAME||' tablespace TEST_DATA'||' as select * from remote_user.'||TABLE_NAME||'@REMOTE_INSTANCE;'        
from table_list;
自動生成更新語句後
將語句複製入指令窗批量執行即可


2、ORACLE中執行文件操作——使用UTF_FILE包


UTL_FILE下的常用函數


使用方式UTL_FILE.function


a.定義文件句柄


v_filehandle     UTL_FILE.file_type;


b.打開文件與關閉文件


  v_filehandle := utl_file.fopen(v_path, v_filename, 'w');--注意PATH定義或輸入時要大寫!
  utl_file.fclose(v_filehandle);

path 需要預先在庫中定義並賦予權限


期間使用v_filehandle文件句柄進行操作


上面的'w'爲打開參數,常用的如下


'r' ——read方式打開

'w'——write方式打開,並清除此前的文件記錄

'a'——append,write 方式打開,在此前的文件記錄前附加信息 --當文件不存在時等同於'w'模式



c.文件讀取


使用get_line可逐行讀取


e.g. v_filehandle := utl_file.fopen(p_path, p_filename, 'r');
18   loop
19     begin
20       utl_file.get_line(v_filehandle, v_text);
21     exception
22       when no_data_found then
23         exit;
24     end;


每次執行一次讀取位置轉到下一行


d.文件輸出


有put,put_line


其區別爲
No line terminator is appended by PUT; 
use PUT_LINE to write a complete line with a line terminator.


UTL_FILE.PUT_line(v_filehandle,'Hello world\n');


3、Cur 與循環的聯合應用

使用語句如

 cursor cur is
    select column_name, data_type
      from user_tab_columns
     where upper(table_name) = upper(sta_target)
     order by column_id asc;

定義cursor


使用

line cur%rowtype;

定義一個cursor cur 所讀取的row的變量以將cur中的信息取出


使用

open cur;

開始使用cursor,此時從第一條記錄開始,每次fetch 將會移動cursor到下一條記錄並準備讀取

 使用loop進行循環,其方式爲執行loop .... end loop;中間的語句。其中需要注意的是隊exit 的定義
  loop
    fetch cur into line;
    exit when cur%notfound;

.....

  end loop;

在使用完cursor後需要使用

close cur;

將cursor的狀況重置


整個過程如下

 cursor cur is
    select column_name, data_type
      from user_tab_columns
     where upper(table_name) = upper(sta_target)
     order by column_id asc;

  line cur%rowtype;

  open cur;

  loop
    fetch cur into line;
    exit when cur%notfound;

.....(讀取line.column進行操作)

  end loop;

close cur;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章