分几个步骤
1,创建输出路径,比如你要在/orcl/dir目录下输出,你就先要建立好这个路径,并在root用户下 chmod 777 /orcl/dir
2,sqlplus下以sysdba登录,执行以下语句
3,create or replace directory TESTFILE as '/orcl/dir';
4,grant read,write on directory TESTFILE to 你要生成文件的用户;
5,alter system set utl_file_dir='/orcl/dir' scope=spfile;
6、SQL> startup force;
7、SQL> show parameter utl_file
6,最重要的一步开始了,创建存储过程
create
or
replace
PROCEDURE
SP_OUTPUT
is
file_handle utl_file.file_type;
Write_content VARCHAR2(1024);
Write_file_name VARCHAR2(50);
v_id
int
;
v_form varchar2(10);
cursor
cur_sp_out
is
select
id,form
from
a
where
to_char(日期,
'yyyymmdd'
)=to_char(sysdate-1,
'yyyymmdd'
);
--如果表里有日期字段的话这么用就行
begin
open
cur_sp_out;
loop
fetch
cur_sp_out
into
v_id,v_form;
exit
when
cur_sp_out%notfound;
write_file_name := to_char(SYSDATE-1,
'YYYYMMDD'
)||
'.txt'
;
--如果这个地方要修改文件名的话,在sysdate处减1就好,其他不用改
file_handle := utl_file.fopen(
'TMP'
,write_file_name,
'a'
);
write_content := v_id||
' '
||v_form;
--write file
IF utl_file.is_open(file_handle)
THEN
utl_file.put_line(file_handle,write_content);
END
IF;
--close file
utl_file.fclose(file_handle);
end
loop;
close
cur_sp_out;
end
;
|
我建立了一个跟你一样的测试表,数据如下
create
table
a(id
int
,
form varchar2(10));
insert
into
a
values
(1,
'你好'
);
insert
into
a
values
(2,
'你很好'
);
|
然后执行存储过程
begin
SP_OUTPUT;
end
;