使用自定义类型时 PostgreSQL 仅返回一行

标签 postgresql plpgsql postgresql-9.4

我有一个返回自定义类型(伪代码)的 plpgsql 函数:

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”变量,则返回多行,因此它按预期工作。

最佳答案

使用 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)

关于使用自定义类型时 PostgreSQL 仅返回一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33143222/

相关文章:

postgresql - 具有动态列名的 Postgres 选择

function - 将表名和列名定义为 plpgsql 函数中的参数?

django - 保存新的 Django 模型对象给出重复键

postgresql - Postgres : ERROR: operator does not exist: inet << inet[] when doing a subquery

SQL删除具有不同值的重复行,但保留并在单行中显示它们

postgresql - 如何设置表默认 autovacuum_analyze_threshold

带时区的 Postgresql date_trunc 将时区移动 1 小时

java - 如何向数据库表中添加两个表组合的条目

postgresql - 使用 plpgsql 将列 bytea 更改为各种版本的 Postgres 中的文本

PostgreSQL 9.4 - 比较 NULL 值