Oracle

Oracle:根據位置條件(循環)將數據假離線到不同的文件

  • October 23, 2017

我正在嘗試解決這樣的問題

declare
 filename varchar2(100);
begin
 for condition in (select fieldN from mytable) loop
   filename := 'data_for_value'||condition.fieldN||'txt';
   spool filename
   select some_data from some_table where fieldN = condition.fieldN;
   spool off
 end loop;
end;

為了將表中的不同數據部分導出到不同的文件中,但我無法做到正確,我已閱讀內容並嘗試執行類似的操作:

set serveroutput on
set pagesize 0
set numwidth 2
set trimspool on

DECLARE
 filename varchar2(100);
BEGIN
 for field2 in (select field2 from blau2) loop
   filename := 'COST_TRAN_BASE '||field2.field2||'.txt';

   spool "run_query.sql" REPLACE

   select distinct 'spool "' || filename || '.txt"' || chr(10) ||
             'select field1, field3 from blau2 where field2 = ' || field2.field2|| ';' || chr(10) ||
             'spool off' cmd
   from blau2;
   spool off
   @"run_query.sql"
 end loop;
END;

但無濟於事。我有一種感覺,我不允許spool在我嘗試的地方使用命令(我最近開始在 Oracle 環境中工作,SQL*Plus 和 PL/SQL 之間的界限仍然有點模糊(你現在可以殺了我)我的無知:’)))

我只是在與不可能的事情作鬥爭嗎?丁:

編輯:

在 Balazs Papp 的初步幫助和我的後續調查下,我想出了這個系統: 使用這個文件:

basic_script.txt
-----------------
SET PAGESIZE 0
SET TRIMSPOOL ON

spool RUN_QUERY.sql REPLACE

select distinct 'set heading off' || chr(10) ||
       'spool "BLAU2 ' || field2 || '.txt"' || chr(10) ||
               'select field1||chr(9)|| field3 from blau2 where field2 = ' || 
field2 || ';' || chr(10) ||
               'spool off'
   from blau2;

spool off
-----------

還有這個其他文件:

basic_script_condition.sql:
-----------
set feedback off
set trimspool on
set recsep off
set serveroutput on

col some_column new_value script_name
select decode((select count(*) from (select distinct FIELD2 from BLAU2)),1,'exit.sql','RUN_QUERY.sql') some_column from dual;
@&script_name
-----------

在一個簡單的 .bat 程序中從命令行呼叫它們:

basic_launcher.bat:
-------------
echo exit | sqlplus lmartin/lmartin @"BASIC_SCRIPT.txt"
echo exit | sqlplus lmartin/lmartin @"BASIC_SCRIPT_CONDITION.sql"
-------------

只有在有數據要導出的情況下,才會生成並執行導出表中不同部分數據的腳本BLAU2(如果沒有要導出的數據,basic_script 會生成一個 .sql 文件,no rows selected其內容可能會重複 N 次,並且執行將失敗,因此basic_script_condition.sql控制此行為)。

SQL> create table t1 (c1) as select mod(rownum, 4) from dual connect by level <= 12;

只是為了有一些樣本數據。

$ cat run.sql
set heading off feedback off echo off termout off pagesize 0
spool select.sql
select distinct 'spool c1_' || c1 || '.txt ' || chr(10)|| 'select c1 from t1 where c1 = ' || c1 || ';' || chr(10) || 'spool off' from t1 order by 1;
spool off
@select.sql
!rm select.sql
exit

$ sqlplus -s bp/bp @run.sql

結果:

$ grep "" *txt
c1_0.txt:         0
c1_0.txt:         0
c1_0.txt:         0
c1_1.txt:         1
c1_1.txt:         1
c1_1.txt:         1
c1_2.txt:         2
c1_2.txt:         2
c1_2.txt:         2
c1_3.txt:         3
c1_3.txt:         3
c1_3.txt:         3

引用自:https://dba.stackexchange.com/questions/188921