Q:

Returning cursor results

I have the following procedure :
CREATE OR REPLACE FUNCTION findKNN()
RETURNS Text AS $body$
DECLARE
    cur refcursor;
    tempcur refcursor;
    gid_ integer;
    _var1 integer;
    _var2 integer;
BEGIN
    open cur for execute('select gid from polygons');
    loop
    fetch cur into gid_;
    open tempcur for SELECT g1.gid , g2.gid FROM polygons AS g1, polygons AS g2
    WHERE g1.gid = gid_  and g1.gid <> g2.gid ORDER BY g1.gid , ST_Distance(g1.the_geom,g2.the_geom)
        LIMIT 5;
             loop
                 fetch tempcur into _var1 , _var2;
                     -- how to return _var1 , _var2 here ? 
                 end loop;
          end loop;
                close cur;
    END;
$body$
LANGUAGE plpgsql;

But I don't know how to return the result out of this procedure. The query returns 5 rows for each execution within outer cursor loop. How can I retrieve these five rows for each query execution? 

A:

Unless you are trying to do something more complicated that is not in your question, you can radically simplify to:
CREATE OR REPLACE FUNCTION find_knn()
    RETURNS TABLE(gid1 integer, gid2 integer)  AS
$body$
BEGIN

    RETURN QUERY
    SELECT g1.gid , g2.gid
    FROM   polygons g1
    JOIN   polygons g2 ON g1.gid <> g2.gid
    -- WHERE  g1.gid = <some_condition>  -- ???
    ORDER  BY g1.gid, st_distance(g1.the_geom, g2.the_geom)
    LIMIT  5;

END;
$body$    LANGUAGE plpgsql;

Or even:
CREATE OR REPLACE FUNCTION find_knn()
    RETURNS TABLE(gid1 integer, gid2 integer)  AS
$body$
    SELECT g1.gid , g2.gid
    FROM   polygons g1
    JOIN   polygons g2 ON g1.gid <> g2.gid
    -- WHERE  g1.gid = <some_condition>  -- ???
    ORDER  BY g1.gid, st_distance(g1.the_geom, g2.the_geom)
    LIMIT  5;
$body$    LANGUAGE sql;

Call:
SELECT * FROM x.find_knn();

The manual about Returning From a Function.
The manual about CREATE FUNCTION.

Retrieve a small slice of a huge join
(Answer to comment.)
There is many ways to pick a small slice of a huge join without actually evaluating the whole join. In most cases you don't even have to worry about it. For instance, run this at home:
EXPLAIN ANALYZE
SELECT *
FROM   huge_tbl t1
CROSS  JOIN huge_tbl t2
LIMIT  5

You will see that only 5 rows will be processed, not the whole cross join.
The same is true for a CTE:
WITH a AS (
    SELECT *
    FROM   huge_tbl t1
    CROSS JOIN huge_tbl t2
    )
SELECT *
FROM   a
LIMIT  5

Some limitations apply. I quote the excellent manual:

PostgreSQL's implementation evaluates only as many rows of a WITH
  query as are actually fetched by the parent query.

To make absolutely sure, you could apply the LIMIT (or a fitting WHERE clause) at the source:
SELECT *
FROM   (SELECT * FROM huge_table LIMIT 1) t1
CROSS  JOIN (SELECT * FROM huge_table LIMIT 5) t2;

