1

I need to get N records from a table and the query I need to execute might return less record than N. Therefore, I'd like to execute the query multiple times until I have exactly N records. I was messing around with table functions and I had something like this:

CREATE OR REPLACE FUNCTION make_dataset(n INTEGER) 
RETURNS SETOF data
AS $$
BEGIN
  WHILE $1 > 0
    RETURN QUERY SELECT * FROM data LIMIT $1;
    -- How to update n from the amount of rows returned by the above?
  END LOOP;
  RETURN;
END $$ 
LANGUAGE plpgsql;

However, I don't know how to update n based on the amount of rows returned by the query. Is there any way to achieve this?

Note: The query has been simplified for brievety. It's not a SELECT * and might return less row than expected, hence why I'm looking at table functions with a loop.

1 Answer 1

1

Use GET DIAGNOSTICS.

CREATE OR REPLACE FUNCTION make_dataset(n INTEGER) 
RETURNS SETOF my_table
AS $$
DECLARE i integer;
BEGIN
  WHILE n > 0 LOOP
    RETURN QUERY SELECT * FROM my_table LIMIT n;
    GET DIAGNOSTICS i:= ROW_COUNT;
    n:= n- i;
  END LOOP;
  RETURN;
END $$ 
LANGUAGE plpgsql;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.