use*_*724 5 sql postgresql plpgsql postgresql-9.1 set-returning-functions
我有很多我的简单查询返回的记录,但是当我使用函数时,它只给了我第一条记录,
首先,我使用以下方法创建自己的数据类型,
CREATE TYPE my_type (usr_id integer , name varchar(30));
Run Code Online (Sandbox Code Playgroud)
我的功能是,
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;
Run Code Online (Sandbox Code Playgroud)
在此函数中,我返回仅返回第一行的 my_type 如何返回多于一行,
要从 plpgsql 函数返回复合类型集,您应该:
setof composite_type, return query(或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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1865 次 |
| 最近记录: |