Bri*_*oux 3 sql oracle plsql oracle12c
我正在使用 Oracle 12c。
我有一张员工表,如下所示:
EMPLOYEE_NAME | DEPARTMENT_NAME
--------------|----------------
Jim | Sales
Barb | Marketing
Paul | Sales
Frank | Sales
Cindy | Accounting
Carl | Marketing
... and so on ...
Run Code Online (Sandbox Code Playgroud)
如果 PL/SQL 允许的话,我想做这样的事情:
FOREACH dept IN (SELECT DISTINCT DEPARTMENT_NAME FROM EMPOLYEES) DO
SPOOL 'list_' || :dept || '.txt';
SELECT EMPLOYEE_NAME
FROM EMPLOYEES
WHERE DEPARTMENT_NAME = :dept;
SPOOL OFF;
DONE;
Run Code Online (Sandbox Code Playgroud)
这将产生一组如下文件:
list_Sales.txt:
Jim
Paul
Frank
Run Code Online (Sandbox Code Playgroud)
列表_营销.txt
Barb
Carl
Run Code Online (Sandbox Code Playgroud)
列表_会计.txt
Cindy
Run Code Online (Sandbox Code Playgroud)
... 等等 ...
关于如何实现这一目标有什么想法吗?
谢谢。
spool是一个客户端命令,它在 PL/SQL 块中没有任何意义;并且您无法从 PL/SQL 写入客户端计算机上的文件。您可以使用(如 @kfinity 建议和 @Barbaros\xc3\x96zhan 所示)写入服务器utl_file,但这可能不适合您的情况。
如果您想坚持在客户端计算机上进行假脱机操作,并且不想将输出后处理到多个文件中(如 @KaushikNayak 建议的那样),您可以使用另一级别的假脱机来生成脚本,例如:
\n\nspool temp_script.sql\n\nselect distinct 'spool list_' || department_name || '.txt' || chr(10)\n || 'select employee_name from employees where department_name = '''\n || department_name || ''' order by employee_name;' || chr(10)\nfrom employees;\n\nspool off\n\n@temp_script.sql\nRun Code Online (Sandbox Code Playgroud)\n\n作为使用默认 HR 模式员工和部门表的更详细的示例:
\n\nset pages 0\nset lines 500\nset trimspool on\nset feedback off\nset echo off\n\nspool temp_script.sql\n\nprompt set pages 0\nprompt set lines 500\nprompt set trimspool on\nprompt set feedback off\nprompt set echo off\n\nselect distinct 'spool list_' || department_name || '.txt' || chr(10)\n || 'select employee_name from employees where department_name = '''\n || department_name || ''' order by employee_name;' || chr(10)\nfrom employees;\n\nprompt spool off\n\nspool off\n\n@temp_script.sql\nRun Code Online (Sandbox Code Playgroud)\n\n在这种情况下,内容temp_script.sql最终类似于:
set pages 0\nset lines 500\nset trimspool on\nset feedback off\nset echo off\nspool list_Administration.txt\nselect first_name || ' ' || last_name from employees where department_id = 10 order by last_name, first_name;\nspool list_Marketing.txt\nselect first_name || ' ' || last_name from employees where department_id = 20 order by last_name, first_name;\nspool list_Purchasing.txt\nselect first_name || ' ' || last_name from employees where department_id = 30 order by last_name, first_name;\n...\nspool list_Payroll.txt\nselect first_name || ' ' || last_name from employees where department_id = 270 order by last_name, first_name;\nspool off\nRun Code Online (Sandbox Code Playgroud)\n\n每个部门一个文件,例如list_Accounting.txt:
William Gietz\nShelley Higgins\nRun Code Online (Sandbox Code Playgroud)\n\n和list_Executive.txt:
Lex De Haan\nSteven King\nNeena Kochhar\nRun Code Online (Sandbox Code Playgroud)\n\n在此示例中,有几个空文件,但如果我将初始查询连接到两个表中,则不会有;当您查询单个表时,这也不会发生在您身上。
\n| 归档时间: |
|
| 查看次数: |
5728 次 |
| 最近记录: |