2017-08-30 92 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類型,那麼它應該工作。 –