在存储过程中使用游标

时间:2015-04-24 22:22:48

标签: stored-procedures plsql oracle11g

我想使用存储过程和游标找到每个季度的最小值,最大值和平均值。无法弄清楚我哪里出错了。

SET SERVEROUTPUT ON

CREATE OR REPLACE PROCEDURE seven2
IS 
   CURSOR c1 IS 
      SELECT 
         qtrcode as QTR, 
         cast(MIN(salaryoffered) as decimal(4,2)) as MIN,  
         cast(MAX(salaryoffered) as decimal(4,2)) as MAX, 
         cast(AVG(salaryoffered) as decimal(4,2)) as AVG
      FROM 
         interview
      GROUP BY 
         qtrcode
      ORDER BY 
         qtrcode

BEGIN 
   FOR qtrcode in c1
   LOOP 
       dbms_output.put_line(min || ' ' ||max|| ' ' ||avg);
   END LOOP;
END;
/

我们可以在上面的查询中添加填充函数吗?如果是这样的话?

1 个答案:

答案 0 :(得分:0)

为了示例目的,我创建了仅有2列的访谈表,并插入了一些虚拟数据,请参阅过程中的更改,现在工作正常

SQL>
SQL> desc interview
 Name                                                                     Null?    Type
 ------------------------------------------------------------------------ -------- -------------------------------
 SALARYOFFERED                                                                     NUMBER(10,2)
 QTRCODE                                                                           VARCHAR2(4)

SQL>




SQL> CREATE OR REPLACE PROCEDURE seven2
  2  IS
  3     CURSOR c1 IS
  4        SELECT
  5           qtrcode as QTR,
  6           cast(MIN(salaryoffered) as decimal(10,4)) as MIN,
  7           cast(MAX(salaryoffered) as decimal(10,4)) as MAX,
  8           cast(AVG(salaryoffered) as decimal(10,4)) as AVG
  9        FROM
 10           interview
 11        GROUP BY
 12           qtrcode
 13        ORDER BY
 14           qtrcode ;
 15
 16  BEGIN
 17     FOR qtrcode in c1
 18     LOOP
 19             dbms_output.put_line('The qtr is ' || qtrcode.qtr ||' The min sal is '|| qtrcode.min || ' The max sal is ' || qtrcode.max|| ' The avg sal is' ||qtrcode.avg);
 20     END LOOP;
 21  END;
 22  /

Procedure created.



SQL> exec seven2;
The qtr is Q1 The min sal is 137.07 The max sal is 964.66 The avg sal is 580.8748
The qtr is Q2 The min sal is 127.79 The max sal is 938.49 The avg sal is 550.52
The qtr is Q3 The min sal is 231.1 The max sal is 992.45 The avg sal is 672.59
The qtr is Q4 The min sal is 103.19 The max sal is 960.13 The avg sal is 431.318

PL/SQL procedure successfully completed.

SQL>