使用自定义类型时,PostgreSQL只返回一行
我有一个返回自定义类型(伪代码)的plpgsql函数: 第一个问题是,即使select语句不返回任何内容(entity_id不存在),函数也会返回一个空行(所有值均为空)。 我使用Dapper将结果映射到一个对象,我需要知道是否找到该对象(NULL或not) 第二个问题是,这个函数总是只返回一行,即使我删除了WHERE子句。使用自定义类型时,PostgreSQL只返回一行,postgresql,plpgsql,postgresql-9.4,Postgresql,Plpgsql,Postgresql 9.4,我有一个返回自定义类型(伪代码)的plpgsql函数: 第一个问题是,即使select语句不返回任何内容(entity_id不存在),函数也会返回一个空行(所有值均为空)。 我使用Dapper将结果映射到一个对象,我需要知道是否找到该对象(NULL或not) 第二个问题是,这个函数总是只返回一行,即使我删除了WHERE子句。 如果我将函数签名更改为直接从select返回查询,并删除本地“CustomType”变量,则会返回多行,因此它会按预期工作。使用SETOF和%ROWTYPE组合: /*
如果我将函数签名更改为直接从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)
现在可以用了,谢谢。但是,当返回许多行时,使用循环查询的性能如何?
/*
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)