我如何 运行 具有迭代的查询或作为 SQL Plus/SQL-PL 中的函数?

How can I run a query with iteration or as a function in SQL Plus/SQL-PL?

SQL 的新手而且对迭代和函数如何使用它有点困惑。希望有人可以告诉我如何使用以下脚本完成它:

set embedded on
set echo off
set colsep ,
set pagesize 0
set linesize 1000
set numwidth 10
set headsep off
spool <my_file_path>.csv;
select * from (select /*csv*/ row_number() over (order by t.objectid) as id, t.objectid as transformer_id, t.gps_x as lon, t.gps_y as lat, s.electricmeternumber, s.serviceindex, s.accountnumber,
case 
     when t.phasedesignation = 0 then 'unknown'
     when t.phasedesignation = 1 then 'C'
     when t.phasedesignation = 2 then 'B'
     when t.phasedesignation = 3 then 'BC'
     when t.phasedesignation = 4 then 'A'
     when t.phasedesignation = 5 then 'AC'
     when t.phasedesignation = 6 then 'AB'
     when t.phasedesignation = 7 then 'ABC'
     end as phase_designation
from mvtransformer t, vservicepoint_meterinfo s 
where t.objectid = s.transformerobjectid) where id > some value x and id <= some value x;
spool off; 

所以我想做的是多次重复这个脚本,每次都改变 x 和文件路径。在 SQL Plus 中解决此问题的最佳方法是什么?

谢谢!

您可以声明一些替代变量,将您的查询放在它自己的脚本中,然后多次调用该脚本来填充相关变量。

例如类似于:

多次调用脚本:

spool &&filename..csv;

SELECT *
FROM   (SELECT /*csv*/
               row_number() over(ORDER BY t.objectid) AS id,
               t.objectid AS transformer_id,
               t.gps_x AS lon,
               t.gps_y AS lat,
               s.electricmeternumber,
               s.serviceindex,
               s.accountnumber,
               CASE
                 WHEN t.phasedesignation = 0 THEN 'unknown'
                 WHEN t.phasedesignation = 1 THEN 'C'
                 WHEN t.phasedesignation = 2 THEN 'B'
                 WHEN t.phasedesignation = 3 THEN 'BC'
                 WHEN t.phasedesignation = 4 THEN 'A'
                 WHEN t.phasedesignation = 5 THEN 'AC'
                 WHEN t.phasedesignation = 6 THEN 'AB'
                 WHEN t.phasedesignation = 7 THEN 'ABC'
               END  AS phase_designation
              FROM   mvtransformer           t,
                     vservicepoint_meterinfo s
              WHERE  t.objectid = s.transformerobjectid)
WHERE  id > &&val1
AND    id <= &&val2;
spool off; 

调用脚本

set embedded on
set echo off
set colsep ,
set pagesize 0
set linesize 1000
set numwidth 10
set headsep off

define val1=10
define val2=20
define filename=your_filename1

@script_to_loop_over

define val1=30
define val2=40
define filename=your_filename2

@script_to_loop_over

...

N.B。 .用于表示SQL*Plus中代入变量名的结束。看起来您正在使用 SQL Developer/SQLCli,它可能会或可能不会将此视为与 SQL*Plus 相同。如果不是,则需要改用 spool &&filename.csv