2017-08-30 43 views
0

我正在使用Oracle 12c和Oracle SQL Developer创建一个包。我的意图是将一个值从SQL语句传递给包,如SELECT * FROM table(test2.get_ups(0));。我想返回一个表,如在IDE中执行SQL SELECT语句。如何从函数返回表格?

这是我的包装。当我尝试编译我收到以下错误:

PLS-00103: Encountered the symbol "FOR" when expecting one of the following: begin function pragma procedure subtype type <an identifier> <a double-quoted delimited-identifier> current cursor delete exists prior The symbol "begin" was substituted for "FOR" to continue.

我该如何解决这个问题?

这里是包:

CREATE OR REPLACE PACKAGE test2 AS 

    TYPE measure_record IS RECORD(
     x_start VARCHAR2(50), 
     x_end VARCHAR2(50), 
     trip_count NUMBER); 

    TYPE measure_table IS TABLE OF measure_record; 

    FUNCTION get_ups(x number) 
     RETURN measure_table 
     PIPELINED; 
END; 
/
CREATE OR REPLACE PACKAGE BODY test2 AS 

    FUNCTION get_ups(x number) RETURN measure_table 
     PIPELINED as 

     cursor temp_cur is 
      SELECT x1, x2, count(*) FROM t1 WHERE x1 = x; 

      for cur_rec in temp_cur 
      loop 
       pipe row(cur_rec); 
      end loop; 

     RETURN; 
    END get_ups; 
END; 

回答

0

我想你会要么将光标移动到DECLARE部分或使用匿名光标,像这样:

FOR cur_rec IN (SELECT x1, x2, count(*) FROM t1 WHERE x1 = x) 
LOOP 
0

有几个问题:函数定义需要一个BEGIN。此函数必须返回变量的实例而不是游标,并且该查询需要GROUP BY

以下每一项更改都有一条评论。

create table t1(x1 number, x2 number); 

CREATE OR REPLACE PACKAGE test2 AS 

    TYPE measure_record IS RECORD(
     x_start VARCHAR2(50), 
     x_end VARCHAR2(50), 
     trip_count NUMBER); 

    TYPE measure_table IS TABLE OF measure_record; 

    FUNCTION get_ups(x number) 
     RETURN measure_table 
     PIPELINED; 
END; 
/
CREATE OR REPLACE PACKAGE BODY test2 AS 

    FUNCTION get_ups(x number) RETURN measure_table 
     PIPELINED as 

     temp measure_record; --Add temporary variable to hold the cursor values. 

     cursor temp_cur is 
      SELECT x1, x2, count(*) FROM t1 WHERE x1 = x GROUP BY x1, x2; --Add "GROUP BY". 
    BEGIN --Add "BEGIN". 
      for cur_rec in temp_cur 
      loop 
       --Assign the values to the temporary variable. 
       temp.x_start := cur_rec.x1; 
       temp.x_end := cur_rec.x2; 
       temp.trip_count := cur_rec."COUNT(*)"; 
       pipe row(temp); --Pipe the variable, not the cursor. 
      end loop; 

     RETURN; 
    END get_ups; 
END; 
/

select * from table(test2.get_ups(1)); 
+0

总的来说,我同意。游标被参数化,所以它看起来应该稍微有点不同,对吧?就像'cursor temp_cur(x NUMBER)是'... –

+0

@PatrickBacon游标可以引用函数参数,'X'不需要通过游标参数传入。 –

+0

@WernfriedDomscheit 12.2不适用于我。据我所知,PL/SQL记录类型没有默认的构造函数,必须逐个组装。如果记录和表类型被定义为SQL类型,那么它应该工作。 –