PLSQL将数据写入指定文件及目录路径无效解决办法
--创建文件路径
create or replace directory test_file as 'D:\oracle_test';
--给用户授权路径读写权限
declare
v_file utl_file.file_type;--定义一个文件变量v_file,类型是file_type
begin
v_file:=utl_file.fopen('test_file','test.sql','W');
--给文件变量赋予一个初值test.sql,最后一个参数W表示写入
for i in
(select code||' '||name res from t_test)
loop
utl_file.put_line(v_file,i.res);
end loop;
utl_file.fclose(v_file);--关闭文件
create or replace directory test_file as 'D:\oracle_test';
--给用户授权路径读写权限
grant read,write on directory test_file to gwn;
--在对应路径下新建要写入的文件test.sql
--将数据写入文件中declare
v_file utl_file.file_type;--定义一个文件变量v_file,类型是file_type
begin
v_file:=utl_file.fopen('test_file','test.sql','W');
--给文件变量赋予一个初值test.sql,最后一个参数W表示写入
for i in
(select code||' '||name res from t_test)
loop
utl_file.put_line(v_file,i.res);
end loop;
utl_file.fclose(v_file);--关闭文件
end;
此时报错目录路径无效
为验证该问题,加入了异常抛出
declare
v_tmp varchar2(60);
v_file utl_file.file_type;
v_file_name varchar2(30);
begin
v_file_name := 'test.sql';
v_file := utl_file.fopen('test_file',v_file_name,'w');
if (utl_file.is_open(v_file)) then
select code||' '||name
into v_tmp from t_test;
utl_file.put_line(v_file, v_tmp);
else
raise_application_error(-20001,'file open failure!');--将应用程序专有的错误从服务器端转达到客户端应用程序
end if;
utl_file.fclose(v_file);
end;
执行后仍是报相同错误。
多次验证后发现是大小写的问题,将语句“v_file := utl_file.fopen('test_file',v_file_name,'w');”中test_file改为大写TEST_FILE,(create directory语句中可以不用改)就可以了。