2017-05-04 205 views
0

嗨,我想創建一個只一行返回多個值功能:甲骨文PLSQL返回一行類型

create or replace TYPE foo_type AS OBJECT (
col1 NUMBER    , 
col2 VARCHAR2(150 BYTE) 
); 

CREATE FUNCTION foo_function() RETURN foo_type 
as 
row_type foo_type; 

select 
b1, -- NUMBER TYPE    
b2 -- VARCHAR2(150 BYTE) TYPE 
into 
row_type 
from 
table_xxx 
where 
rownum=1; --Only one row! 

return row_type; 

END foo_function; 

如果我編譯收到的:ORA-00947不夠值

我已經試過:

select 
b1, -- NUMBER TYPE    
b2 -- VARCHAR2(150 BYTE) TYPE 
into 
row_type.col1, 
row_type.col2 
from 
table_xxx 
where 
rownum=1; --Only one row! 

而且功能編譯但是當ID運行:

select foo_function() from dual; 

甲骨文回報:ORA-06530引用未初始化的複合

回答

1

你將它定義爲在數據庫級對象,所以這個對象必須被初始化。

row_type := foo_type(null,null) 

但更恰當的解決方案在這裏將被改變選擇以下:

select 
foo_type(b1,b2) -- Create a foo_type from the select 
into 
row_type -- throw this initialized foo_type into your variable row_type 
from 
table_xxx 
where 
rownum=1; --Only one row! 

你可以做這一點與null值做你的選擇,如下之前初始化

+1

答案是確定的,但關於'你將它定義爲在數據庫級別的對象,我不能同意你的觀點,所以這個對象即使是子程序級別定義的類型變量也必須初始化。 – Seyran

1
select b1, b2 
into row_type 
from table_xxx 
where rownum=1; 

拋出ORA-00947 not enough values,因爲有兩個值b1b2但只有一個變量請將row_type插入。

你可以這樣做:

CREATE FUNCTION foo_function() RETURN foo_type 
as 
    row_type foo_type; 
BEGIN      -- missing BEGIN 
    select foo_type (b1, b2) -- You need to put the values into a foo_type object 
    into row_type 
    from table_xxx 
    where rownum=1; 

    return row_type; 
END foo_function; 

或者:

CREATE FUNCTION foo_function() RETURN foo_type 
as 
    row_type foo_type := foo_type(NULL, NULL); -- Initialise the object. 
BEGIN 
    select b1,   b2 
    into row_type.col1, row_type.col2 
    from table_xxx 
    where rownum=1; 

    return row_type; 
END foo_function; 
+0

感謝我現在在做: 從雙重選擇foo_function();我反悔:[foo_type] 我如何顯示所有值插入返回的記錄? (SELECT foo.function2)FROM(SELECT foo.function()AS foo FROM DUAL) –

+0

@MicheleM'SELECT foo.col1,foo.col2 FROM(SELECT foo_function()as foo FROM DUAL)' – MT0

+0

對於do:SELECT col3,col4,(SELECT foo.col1,foo.col2 FROM foo FROM DUAL))從tab_yyy - tab_yyy有列col3和col4 –