1、测试表和数据:
create table test(id int , s varchar2(100)); begin for k in 1..1000 loop insert into test values(k,'test'||k); end loop; end; /
2、在本地创建一个目录,如D:/myoracledata
在sql plus中执行如下语句
create or replace directory MY_DIR as 'D:/myoracledata';
3、在sql plus中执行如下脚本。下面代码是 100行换一个文件,文件名前缀为data
declare row_result varchar2(1024); selectsql varchar2(1024); qrycursor SYS_REFCURSOR; txt_handle UTL_FILE.file_type; filenum number; num number; MAX_NUM number; FILENAME_PREFIX varchar2(10); BEGIN MAX_NUM:=100; FILENAME_PREFIX:='data'; filenum:=1; num:=0; selectsql := ' select id||'',''||s from test'; txt_handle := UTL_FILE.FOPEN('MY_DIR','data'||filenum||'.txt','w'); open qrycursor for selectsql; loop fetch qrycursor into row_result; exit when qrycursor%notfound; UTL_FILE.PUT_LINE(txt_handle,row_result); num:=num+1; if num=MAX_NUM then filenum:=filenum+1; UTL_FILE.FCLOSE(txt_handle); txt_handle := UTL_FILE.FOPEN('MY_DIR',FILENAME_PREFIX||filenum||'.txt','w'); num:=0; end if; end loop; close qrycursor; UTL_FILE.FCLOSE(txt_handle); end; /