Ich在postgres函数中遇到问题:
CREATE OR REPLACE FUNCTION getVar(id bigint) RETURNS TABLE (repoid bigint, suf VARCHAR, nam VARCHAR) AS $$ declare rec record; BEGIN FOR rec IN (WITH RECURSIVE children(repoobjectid,variant_of_object_fk, suffix, variantname) AS ( SELECT repoobjectid, variant_of_object_fk, '' as suffix,variantname FROM b2m.repoobject_tab WHERE repoobjectid = id UNION ALL SELECT repo.repoobjectid, repo.variant_of_object_fk, suffix || '..' , repo.variantname FROM b2m.repoobject_tab repo, children WHERE children.repoobjectid = repo.variant_of_object_fk) SELECT repoobjectid,suffix,variantname FROM children) LOOP RETURN next; END LOOP; RETURN; END;
它可以编译,但如果你试着调用它
select * from getVar(18)
我有8个空行,有3列。
如果我使用硬编码的id参数执行以下部分过程:
WITH RECURSIVE children(repoobjectid,variant_of_object_fk, suffix, variantname) AS ( SELECT repoobjectid, variant_of_object_fk, '' as suffix,variantname FROM b2m.repoobject_tab WHERE repoobjectid = 18 UNION ALL SELECT repo.repoobjectid, repo.variant_of_object_fk, suffix || '..' , repo.variantname FROM b2m.repoobject_tab repo, children WHERE children.repoobjectid = repo.variant_of_object_fk) SELECT repoobjectid,suffix,variantname FROM children
我完全知道,我需要8行数据:
repoobjectid suffix variantname 18 19 .. for IPhone 22 .. for Nokia 23 .... OS 1.0
等等。
出了什么问题?请帮忙。
提前完成
答案 0 :(得分:1)
我认为如果你正在做“返回表”,你需要在做“返回下一步”之前分配到表的“列”。如下所示:
repoid := rec.repoid;
suf := rec.suf;
nam := rec.nam;
就在你的“返回下一步”之前。由于您没有分配这些内容,因此它们将返回为null。
答案 1 :(得分:1)
以下是从表中返回行的函数的示例代码,我认为它可能会有所帮助。
首先,带有样本数据的样本表:
CREATE TABLE sample_table (id smallint, description varchar, primary key (id));
INSERT INTO sample_table (id, description) VALUES (1, 'AAAA');
INSERT INTO sample_table (id, description) VALUES (2, 'BBBB');
INSERT INTO sample_table (id, description) VALUES (3, 'CCCC');
INSERT INTO sample_table (id, description) VALUES (4, 'DDDD');
INSERT INTO sample_table (id, description) VALUES (5, 'EEEE');
然后,返回类型描述返回的行的字段:
CREATE TYPE return_type AS
(id smallint,
description varchar);
ALTER TYPE return_type OWNER TO postgres;
然后是函数本身:
CREATE OR REPLACE FUNCTION report(p_id integer)
RETURNS SETOF return_type AS
$BODY$
DECLARE
retorno return_type%ROWTYPE;
BEGIN
FOR RETORNO IN SELECT * FROM sample_table WHERE id = p_id LOOP
RETURN NEXT RETORNO;
END LOOP;
RETURN;
END
$BODY$
LANGUAGE 'plpgsql' VOLATILE
COST 100
ROWS 1000;
ALTER FUNCTION report(p_id integer) OWNER TO postgres;
这里是函数调用:
SELECT * FROM report(1);