我正面临以下问题。我想执行查询并将所有结果导出到文件中。我的查询保存为varchar2类型,我可以立即执行它并给我所有结果。现在这些结果如何将它们全部转储到文件中。我不想从查询或任何东西中选择特定的列名。它就像是大量收集许多结果并将它们转储到文件中。这是我正在研究的一些伪代码:
这是一种不起作用的方式
Declare
filehandle1 UTL_FILE.FILE_TYPE;
myquery varchar2(4000) := 'Select column1'||'~'||'Column2'||'~'||' from mytable';
Begin
filehandle1 := UTL_FILE.FOPEN ('MYDIR','mydata','W');
FOR emp IN (execute immediate (myquery)) LOOP --This part of course is not working
UTL_FILE.PUT (filehandle1, emp.*); --i dont want to write each column
END LOOP; --i have the columns and formatting ready of the query
UTL_FILE.FCLOSE (filehandle1);
End;
这是另一种不起作用的方式
Declare
filehandle1 UTL_FILE.FILE_TYPE;
myquery varchar2(4000) := 'Select column1'||'~'||'Column2'||'~'||' from mytable';
Begin
filehandle1 := UTL_FILE.FOPEN ('MYDIR','mydata','W');
UTL_FILE.PUT (filehandle1, myquery); --i want just to execute the query and write
UTL_FILE.FCLOSE (filehandle1); --everything in the file
End;
我怎样才能获得所有内容并将其丢入文件中?此外,我必须在plsql块中完成,因此我无法假脱机它们提前感谢
答案 0 :(得分:2)
你可以循环游标:
declare
filehandle1 utl_file.file_type;
myquery varchar2(4000) := 'select column1 ||''~''|| column2 from mytable';
mycursor sys_refcursor;
myresult varchar2(4000);
begin
filehandle1 := utl_file.fopen ('D42', 'mydata', 'w');
open mycursor for myquery;
loop
fetch mycursor into myresult;
exit when mycursor%notfound;
utl_file.put_line(filehandle1, myresult);
end loop;
close mycursor;
utl_file.fclose(filehandle1);
end;
/
或者更简单地说,如果您不需要将查询作为字符串(我不确定您是否实际上是从另一个表中获取该信息,例如,否则我就是' m不确定为什么你将它作为varchar2
变量):
declare
filehandle1 utl_file.file_type;
begin
filehandle1 := utl_file.fopen ('D42', 'mydata', 'w');
for myrec in (select column1 ||'~'|| column2 as result from mytable)
loop
utl_file.put_line(filehandle1, myrec.result);
end loop;
utl_file.fclose(filehandle1);
end;
/
如果我创建并填充表格为:
create table mytable (column1 number, column2 varchar2(10));
insert into mytable (column1, column2) values (1, 'First');
insert into mytable (column1, column2) values (2, 'Second');
然后使用其中任何一个,mydata
文件包含:
1~First
2~Second
如果您想明确使用批量收集,可以执行以下操作:
declare
filehandle1 utl_file.file_type;
myquery varchar2(4000) := 'select column1 ||''~''|| column2 from mytable';
mycursor sys_refcursor;
myresults sys.odcivarchar2list;
begin
filehandle1 := utl_file.fopen ('D42', 'mydata', 'w');
open mycursor for myquery;
loop
fetch mycursor bulk collect into myresults limit 100;
for idx in myresults.first..myresults.last loop
utl_file.put_line(filehandle1, myresults(idx));
end loop;
exit when mycursor%notfound;
end loop;
close mycursor;
utl_file.fclose(filehandle1);
end;
/