我如何在Postgres中返回查询结果?

时间:2016-10-06 17:30:52

标签: sql postgresql plpgsql

我在PostgreSQL中有功能,当我想返回结果时我得到了错误:

    ERROR:  query has no destination for result data
    HINT:  If you want to discard the results of a SELECT, use PERFORM instead.

以下是我的功能摘要(此处复制/粘贴所有代码的时间太长)

CREATE OR REPLACE FUNCTION "schema"."test"(IN Id int8,)

 RETURNS TABLE("Id" uuid, "SiteId" uuid, "Domain" varchar,
 "JumpCost" numeric, "CPMCost" numeric, "PaymentModel" int8, "ComputedEpm" numeric,
 "ClickedCampaignId" int8, "MainRubricId" int8, "ShowSlider" bool,
 "ShowGoods" bool, "ShowTeaser" bool, "BidLimitCoeff" numeric,
 "RtbActiveSiteStatByBannerId" int8, "ShowType" int8, "MinAge" int8) AS

$BODY$

DECLARE
     rtbCampaignEpmCoeff NUMERIC(18,6);
     maxRubricShows int;   
     showsRubricAddedPerClick int;
     siteLossLimitPerRubric NUMERIC(18,6);
     rtbMinRubricVisitsToShow int;
     showAdsToUsersWithoutInterests boolean;

BEGIN
......

DO
$do$
......
$do$;

PERFORM   "Id", "SiteId", "Domain", "JumpCost", "CPMCost", "PaymentModel",
5 as ComputedEpm, "ClickedCampaignId", "MainRubricId", "ShowSlider", 
"ShowGoods", "ShowTeaser", "BidLimitCoeff", "RtbActiveSiteStatByBannerId",
"ShowType", "MinAge" 

FROM mytable

ORDER BY "FromClick" DESC, "Similarity" DESC, "rn", random()
LIMIT 1;

END;

$BODY$
LANGUAGE plpgsql
COST 100
CALLED ON NULL INPUT
SECURITY INVOKER
VOLATILE;

如你所见,我用过" PERFORM"返回结果,但失败了,我解释了错误。

另外,我使用"返回查询.."并得到同样的错误。

" MYTABLE"是我在函数中创建的临时表。

如何归还此结果?

1 个答案:

答案 0 :(得分:2)

也许是这样的?

CREATE OR REPLACE FUNCTION my_function(user_id integer)
  RETURNS TABLE(id integer, firstname character varying
                          , lastname  character varying) AS
$$
DECLARE
    ids character varying;
BEGIN
    ids := '';

    --Some code which build the ids string, not interesting for this issue

    RETURN QUERY EXECUTE 'SELECT users.id, users.firstname, users.lastname
    FROM public.users WHERE ids IN (' || ids || ')';
END;
$$ LANGUAGE plpgsql;