2015-10-15 36 views
2

我有一個返回自定義類型(僞)一PLPGSQL功能時,只返回一行:PostgreSQL的使用自定義類型

CREATE OR REPLACE FUNCTION my_function(entity_id integer) 
    RETURNS "CustomType" AS 
$BODY$ 

DECLARE 
    result "CustomType";   
BEGIN 

    SELECT 
    INTO result 
     T."Column1" AS "Column1", 
     T."Column2" AS "Column2"       
    FROM "Table1" T 
    WHERE T."EntityId" = entity_id 

--do other stuff here before returning 

RETURN QUERY 
SELECT 
     result."Column1", 
     result."Column2" 
END; 

$BODY$ 
LANGUAGE plpgsql VOLATILE 

的第一個問題是,該函數返回一個空行(所有值空)甚至如果select語句不返回(entity_id不存在)。 我使用Dapper將結果映射到一個對象,我需要知道該對象是否被找到(NULL或不)。

第二個問題是,即使例如我刪除了WHERE子句,該函數總是隻返回一行。 如果我將函數簽名更改爲直接從select返回查詢並刪除本地「CustomType」變量,則會返回多行,因此它按預期工作。

回答

1

使用SETOF和%ROWTYPE組合:

/* 


drop function my_function(int); 

drop table "Table1"; 

drop type "CustomType"; 
*/ 

create type "CustomType" as ("Column1" int, "Column2" int); 

create table "Table1"(a int, b int); 

insert into "Table1"(a,b) values 
(1,2), 
(3,4), 
(5,6); 


CREATE OR REPLACE FUNCTION my_function(entity_id integer) 
    RETURNS SETOF "CustomType" as 
$$ 
DECLARE 
    result "CustomType" % rowtype; 

    singleRow "CustomType"; 
BEGIN 



    FOR RESULT IN EXECUTE 'SELECT 
     t.a, 
     t.b 
    FROM "Table1" t 
    where t.a>= ' || entity_id LOOP 

     RETURN NEXT RESULT; 

    END LOOP; 

--do other stuff here before returning 

    singleRow."Column1" := 7; 
    singleRow."Column2" := 6; 

    return next singleRow; 


    RETURN; 

END 
$$ 
LANGUAGE plpgsql VOLATILE; 


select * from my_function(3) 
+0

它現在,謝謝。但是當返回很多行時,使用LOOP在查詢上執行的性能如何呢? –

相關問題