我有一个Oracle数据库,我想将数据导出到一个文件。但是,文件名,扩展名和分隔符将从表中获取值。问题是我无法使用表中的值。你能建议我这样做吗?或者,如果我可以批量执行此操作?
表(id,路径,文件名,扩展名,分隔符)
script.sql
conn ....
variable fullpath varchar2(20);
variable filename varchar2(10);
variable extension varchar2(5);
variable sep varchar2(1);
begin
select filename, path, extension,separator
into :filename, :fullpath, :extension, :sep
from Table;
end;
/
set separator sep
spool fullpath||filename||'.'||extension;
... select queries...
spool off;
此致
答案 0 :(得分:1)
SPOOL是一个SQLPlus命令,因此您无法动态地在PlSQL块中使用它。
一种方法是在运行时创建第二个脚本,根据您的查询动态构建,然后运行它来完成工作。 例如:
conn ...
set serveroutput on
set feedback off
variable fullpath varchar2(20);
variable filename varchar2(10);
variable extension varchar2(5);
variable sep varchar2(1);
/* spool to a fixed file, that will contain your dynamic script */
spool d:\secondScript.sql
begin
select 'filename', 'd:\', 'txt', '|'
into :filename, :fullpath, :extension, :sep
from dual;
/* write the second script */
dbms_output.put_line('set colsep ' || :sep);
dbms_output.put_line('spool ' || :fullpath || :filename || '.' || :extension);
dbms_output.put_line('select 1, 2, 3 from dual;');
dbms_output.put_line('spool off');
end;
/
spool off
/* run the second script */
@d:\secondscript.sql
这给出了:
SQL> sta C:\firstScript.sql
Connected.
set colsep |
spool d:\filename.txt
select 1, 2, 3 from dual;
1| 2| 3
----------|----------|----------
1| 2| 3
<强> d:\ FILENAME.TXT 强>:
1| 2| 3
----------|----------|----------
1| 2| 3
答案 1 :(得分:1)
您可以使用the new_value
clause的替换变量和the column
command。
conn ....
column spool_path new_value sub_spool_path noprint
column sep new_value sub_sep noprint
set verify off
set termout off
select path || filename ||'.'|| extension as spool_path, separator as sep
from Table;
set termout on
set separator &sub_sep
spool &sub_spool_path
... select queries...
spool off;