在Oracle中调用函数的过程中的循环游标

时间:2016-11-16 05:40:15

标签: oracle-sqldeveloper

表格是:

F TIME1                                                                       END_TIME                          
- --------------------------------------------------------------------------- ----------------------
C 16-NOV-16 09.45.32.000000 AM                                                17-NOV-16 09.45.32.000000 AM      
A 16-NOV-16 10.14.54.000000 AM                                                16-NOV-16 11.14.54.000000 AM      
A 16-NOV-16 10.14.56.000000 AM                                                16-NOV-16 11.14.56.000000 AM      

我创建了一个函数..

CREATE OR REPLACE FUNCTION datediff
(
time1 TIMESTAMP
, time2 TIMESTAMP
)
RETURN number
as
tot number;
BEGIN
SELECT(extract(DAY FROM time2-time1)*24*60*60)+
(extract(HOUR FROM time2-time1)*60*60)
 into tot from tt ;

RETURN tot;
END;

然后我在程序中调用函数...

CREATE OR REPLACE PROCEDURE P1
IS 
  CURSOR c1
   IS    
   select count(*) as cnt,time1,end_time
   from tt group by time1,end_time ;

  a number;
BEGIN
  FOR i IN c1
  LOOP
    declare
      a number;
    BEGIN
      insert into y1 values(i.cnt,datediff(i.time1,i.end_time)) ;

      --display(i.cnt||'        '||a);

    /* EXCEPTION
         WHEN OTHERS THEN
            dbms_output.put_line('Error updating record ' || SUBSTR (SQLERRM, 1, 250));*/
    END;

  END LOOP;

END P1;

我得到的错误是......

SQL> exec p1
BEGIN p1; END;
*
ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at "ANU.DATEDIFF", line 11
ORA-06512: at "ANU.P1", line 14
ORA-06512: at line 1

这适用于表中的单个记录,但不适用于多个记录..?请指导..

1 个答案:

答案 0 :(得分:0)

问题在于您的datediff功能。

每当PL / SQL中有SELECT ... INTO ...语句时,SELECT查询必须返回一行。如果它根本不返回任何行,则会出现ORA-01403 no data found错误,如果它返回多行,则会出现上面显示的ORA-01422 exact fetch returns more than requested number of rows错误。

那么,如何让您的查询返回一行?好吧,您可以首先注意到您没有从表tt中选择任何值。您返回的所有查询都是tt中每行的相同值。如果tt有一行,则查询会返回一次值。如果tt有三行,则查询返回相同的值三次。所有这些都是不必要的,因为您只需要一个值,无论tt中有多少行。

因此,请SELECT使用built-in table dual代替tt dualSELECT(extract(DAY FROM time2-time1)*24*60*60)+ (extract(HOUR FROM time2-time1)*60*60) into tot from dual; 表中只有一行:

datediff

但是,在您的情况下,您甚至不需要查询:可以重写您的CREATE OR REPLACE FUNCTION datediff ( time1 TIMESTAMP , time2 TIMESTAMP ) RETURN number as BEGIN RETURN (extract(DAY FROM time2-time1)*24*60*60)+ (extract(HOUR FROM time2-time1)*60*60); END; / 函数以执行计算并返回值:

function multiArrayIndex(index, ...args) {
    var arrays = args.slice();
    var output = [];
    
    for (var i = 0, curIndex = index; i < arrays.length; i++) {
        var curArray = arrays[i];
        var valueIndex =(curIndex % curArray.length);
        output.push(curArray[valueIndex]);
        curIndex = Math.ceil(curIndex / curArray.length);
    }
    return output;
}
demoP = document.getElementById("demo");
for(var i = 32; i>=1; i--){
	demoP.innerHTML = demoP.innerHTML + i + " - " + multiArrayIndex(i, [0,1,2,3], [0,1,2,3], [0,1] ) + "<br />";
}