0
CREATE OR REPLACE FUNCTION "getArticulos"(refcursor)
RETURNS refcursor AS
$BODY$
BEGIN
    CREATE TEMP TABLE "Temporal" AS
    SELECT a."idArticulo", SUM("Stock") AS "Stock"
    FROM "ArticuloMarca" AS am, "Articulo" AS a
    WHERE a."idArticulo" = am."idArticulo"
    GROUP BY a."idArticulo"
    ORDER BY a."idArticulo";
    OPEN $1 FOR
        SELECT DISTINCT(a."idArticulo"), a."Nombre", a."Descripcion", a."idFamilia", f."Nombre" AS "Familia",a."idTipo", t."Nombre" AS "Tipo", tmp."Stock", a."MinStock", a."MaxStock"
        FROM "Articulo" AS a, "ArticuloMarca" AS am, "Familia" AS f, "Tipo" AS t, "Temporal" AS tmp
        WHERE a."idFamilia" = f."idFamilia" AND a."idTipo" = t."idTipo" AND a."idArticulo" = tmp."idArticulo"
        ORDER BY a."idArticulo";
    RETURN $1;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

那是我的功能,但我一直试图不使用 TEMP TABLE,我需要一些我不必在会话中删除的东西。

我试过使用 RECORD,一种叫做 refcursor 的东西,但我只得到一行,我需要整个结果。知道我可以使用什么吗?¿

我尝试在 RETURN $1 之后和之前添加 DROP TABLE "Temporal";但它不起作用。

4

2 回答 2

3

我认为您不需要为简单的查询创建 TEMP 表(甚至不需要创建函数)。更重要的是,如果您使用的是提供WITH 查询的 Postgresql 9.x ,您应该阅读相关内容。

于 2012-04-14T22:03:31.597 回答
1

请检查文档的这一部分。目前还不清楚你想要实现什么,但我猜你需要一个集合返回函数。

我希望这段代码可以满足您的需要:

CREATE OR REPLACE FUNCTION "getArticulos"(
    OUT "Articulo"."idArticulo",
    OUT "Articulo"."Nombre",
    OUT "Articulo"."Descripcion",
    OUT "Articulo"."idFamilia",
    OUT "Familia"."Nombre",
    OUT "Articulo"."idTipo",
    OUT "Tipo"."Nombre",
    OUT int4, -- I cannot get the source table for “Stock” column
    OUT "Articulo"."MinStock",
    OUT "Articulo"."MinStock"
    )
RETURNS SETOF record
AS $BODY$
BEGIN
    RETURN QUERY
    WITH "Temporal" AS (
    SELECT a."idArticulo", SUM("Stock") AS "Stock"
    FROM "ArticuloMarca" AS am, "Articulo" AS a
    WHERE a."idArticulo" = am."idArticulo"
    GROUP BY a."idArticulo"
    ORDER BY a."idArticulo")
        SELECT DISTINCT(a."idArticulo"), a."Nombre", a."Descripcion", a."idFamilia", f."Nombre" AS "Familia",a."idTipo", t."Nombre" AS "Tipo", tmp."Stock", a."MinStock", a."MaxStock"
        FROM "Articulo" AS a, "ArticuloMarca" AS am, "Familia" AS f, "Tipo" AS t, "Temporal" AS tmp
        WHERE a."idFamilia" = f."idFamilia" AND a."idTipo" = t."idTipo" AND a."idArticulo" = tmp."idArticulo"
        ORDER BY a."idArticulo";
END;
$BODY$
LANGUAGE plpgsql VOLATILE COST 100;

由于显而易见的原因,我无法测试此功能。此外,请考虑更改LANGUAGESQL,因为 plpgsql 开销没有理由执行此操作。

于 2012-04-14T21:50:48.737 回答