Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get 10 rows for a single cursor fetch

I have following code,I want to fetch 10 rows from cursor and then save them in an array,

Here, with this code, I just want to know how to get 10 (or some other value) rows from a single fetch.

CREATE OR REPLACE FUNCTION func_fetch_many(num INTEGER)
returns integer as $$
DECLARE
  my_cursor CURSOR FOR SELECT a,b,c FROM t_0038;
  my_array t_0038 ARRAY;
BEGIN
  OPEN my_cursor;
  FETCH 10 FROM my_cursor INTO my_array; --ERROR here
  CLOSE my_cursor;
  foreach r in my_array
  loop
  raise notice 'r is %', r
  end loop;
  return 0;
    
END;
$$ LANGUAGE plpgsql;

When I run the above code, it complains that FETCH can't return multiple rows

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would like to know how to fix this problem, thanks.

>Solution :

The FETCH statement in PostgreSQL’s PL/pgSQL language is designed to fetch a single row at a time, not multiple rows. To achieve your goal of fetching multiple rows into an array, you would need to loop through the cursor and fetch rows one by one, adding them to the array within the loop.
Here’s how you can modify your code to achieve this:

CREATE OR REPLACE FUNCTION func_fetch_many(num INTEGER)
RETURNS integer AS $$
DECLARE
  my_cursor CURSOR FOR SELECT a,b,c FROM t_0038;
  my_record t_0038%ROWTYPE;
  my_array t_0038[]; -- Declare an array of the same type as the cursor query
BEGIN
  OPEN my_cursor;
  FOR i IN 1..num LOOP -- Loop to fetch 'num' rows
    FETCH NEXT FROM my_cursor INTO my_record;
    EXIT WHEN NOT FOUND; -- Exit the loop when no more rows are available
    my_array := my_array || my_record; -- Append the fetched row to the array
  END LOOP;
  CLOSE my_cursor;
  
  FOREACH r IN ARRAY my_array LOOP
    RAISE NOTICE 'a: %, b: %, c: %', r.a, r.b, r.c;
  END LOOP;
  
  RETURN 0;
END;
$$ LANGUAGE plpgsql;

This version initializes an empty array my_array and then appends each fetched row as an array to it. The rest of the code remains similar to the previous version, achieving the same goal of fetching and processing multiple rows from the cursor.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading