我有一个表t1
,其中包含两列,即company
和employee name
。我想为每个公司生成txt文件,文件应该包含在这些公司工作的员工。
有关如何执行此操作的任何建议将不胜感激。
CREATE TABLE T1(COMPANY VARCHAR2(10) , ENAME VARCHAR2(100));
INSERT INTO T1
SELECT 'A' , 'SSS' FROM DUAL
UNION
SELECT 'B' , 'AAA' FROM DUAL
UNION
SELECT 'C' , 'FFF' FROM DUAL
UNION
SELECT 'A' , 'KKK' FROM DUAL
UNION
SELECT 'B' , 'LLL' FROM DUAL
UNION
SELECT 'C' , 'EEE' FROM DUAL
UNION
SELECT 'A' , 'UUU' FROM DUAL
UNION
SELECT 'B' , 'WWW' FROM DUAL
UNION
SELECT 'C' , 'TTT' FROM DUAL
UNION
SELECT 'A' , 'MMM' FROM DUAL;
commit;
A.txt
KKK
MMM
SSS
UUU
B.txt
AAA
LLL
WWW
C.txt
EEE
FFF
TTT
由于
谢谢,我尝试了你的建议,我在v_out.sql上获取数据,但文件没有生成。我在v_out.sql结束时收到错误
错误
Elapsed: 00:00:00.02
not spooling currently
SP2-0734: unknown command beginning "Elapsed: 0..." - rest of line ignored.
查询
set termout off
set echo off
set feedback off
spool v_out.sql
select * from
(
with files as ( select distinct company from t1 )
select
'set termout off '||chr(10)||
'set serveroutput on '||chr(10)||
'set echo off '||chr(10)||
'set feedback off '||chr(10)||
'spool '||company||'.dat'||chr(10)||
'select * from t1 where company = '''||company||''';'||chr(10)||
'spool off'
from files
);
/
spool off
@v_out.sql;
此查询中有什么问题?
答案 0 :(得分:3)
设置测试数据:
SQL> CREATE TABLE T1(COMPANY VARCHAR2(10) , ENAME VARCHAR2(100));
Table created.
SQL>
SQL> INSERT INTO T1
2 SELECT 'A' , 'SSS' FROM DUAL
3 UNION
4 SELECT 'B' , 'AAA' FROM DUAL
5 UNION
6 SELECT 'C' , 'FFF' FROM DUAL
7 UNION
8 SELECT 'A' , 'KKK' FROM DUAL
9 UNION
10 SELECT 'B' , 'LLL' FROM DUAL
11 UNION
12 SELECT 'C' , 'EEE' FROM DUAL
13 UNION
14 SELECT 'A' , 'UUU' FROM DUAL
15 UNION
16 SELECT 'B' , 'WWW' FROM DUAL
17 UNION
18 SELECT 'C' , 'TTT' FROM DUAL
19 UNION
20 SELECT 'A' , 'MMM' FROM DUAL;
10 rows created.
SQL>
SQL> commit;
Commit complete.
SQL>
以下是查询:
SQL> with files as ( select distinct company from t1 )
2 select
3 'spool '||company||'.dat'||chr(10)||
4 'select * from t1 where company = '''||company||''';'||chr(10)||
5 'spool off'
6 from files;
'SPOOL'||COMPANY||'.DAT'||CHR(10)||'SELECT*FROMT1WHERECOMPANY='''||COMPANY||'
-----------------------------------------------------------------------------
spool A.dat
select * from t1 where company = 'A';
spool off
spool B.dat
select * from t1 where company = 'B';
spool off
spool C.dat
select * from t1 where company = 'C';
spool off
现在您只需将THAT输出到文件,然后运行该文件。