Search code examples
c#postgresqlcreate-table

PostgreSQL Function TEMP TABLE Alternative Solution


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;

Thats my function, but i've been trying to not use the TEMP TABLE, insted i need something that i dont have to delete in a sesion.

Ive tried with RECORD, something called refcursor, but i get just a row and i need the whole result. Any idea of what can i use?¿

I tried adding DROP TABLE "Temporal" after and before the RETURN $1; but it doesnt work.


Solution

  • I don't think you need to create a TEMP table (nor even to create a function) for a simple query. More so if you are using Postgresql 9.x, which provides WITH queries, you should read about that.