我有很多记录,我的简单查询返回,但当我使用函数时,它只给我第一条记录,
首先我使用以下方法创建自己的数据类型:
CREATE TYPE my_type (usr_id integer , name varchar(30));
我的功能是
CREATE OR REPLACE function test() returns my_type as $$
declare rd varchar := '21';
declare personphone varchar := NULL;
declare result my_type;
declare SQL VARCHAR(300):=null;
DECLARE
radiophone_clause text = '';
BEGIN
IF rd IS NOT NULL then
radiophone_clause = 'and pp.radio_phone = '|| quote_literal(rd);
END IF;
IF personphone IS NOT NULL then
radiophone_clause = radiophone_clause|| 'and pp.person_phone = '|| quote_literal(personphone);
END IF;
radiophone_clause = substr(radiophone_clause, 5, length(radiophone_clause)- 4);
EXECUTE format('select pt.id,pt.name from product_template pt inner join product_product pp on pt.id=pp.id where %s ;', radiophone_clause) into result.id,result.name ;
return result;
END;
$$ LANGUAGE plpgsql;
在此函数中,我返回 my_type ,它仅返回第一行如何返回多于一行,
要从 plpgsql 函数返回复合类型集,您应该:
- 将函数的返回类型声明为
setof composite_type
,
- use
return query
(or return next
) 操作说明(文档).
我仅在更改返回类型的情况下编辑了您的代码(这只是一个示例):
DROP function test(); -- to change the return type one must drop the function
CREATE OR REPLACE function test()
-- returns my_type as $$
returns setof my_type as $$ -- (+)
declare rd varchar := '21';
declare personphone varchar := NULL;
-- declare result my_type;
-- declare SQL VARCHAR(300):=null;
DECLARE
radiophone_clause text = '';
BEGIN
IF rd IS NOT NULL then
radiophone_clause = 'and pp.radio_phone = '|| quote_literal(rd);
END IF;
IF personphone IS NOT NULL then
radiophone_clause = radiophone_clause|| 'and pp.person_phone = '|| quote_literal(personphone);
END IF;
radiophone_clause = substr(radiophone_clause, 5, length(radiophone_clause)- 4);
RETURN QUERY -- (+)
EXECUTE format('select pt.id,pt.name from product_template pt inner join product_product pp on pt.id=pp.id where %s ;', radiophone_clause)
; -- (+)
-- into result.id,result.name;
-- return result;
END;
$$ LANGUAGE plpgsql;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)