2

I have below program , My 2nd select query returns multiple records, How should I print all the values.. Currently its printing only 1st value. Can you please suggest?

Ex. Actual Output:

123

890

4599

Current Output: 123

DO $$
<<script>>
DECLARE
  student_rec RECORD;
  sqlquery text;
  v_nk RECORD;

BEGIN
FOR student_rec IN 
select nk from course_table;
-- open loop for cursor above
LOOP
sqlquery := 'SELECT col FROM section where rec_nk = ' || '''' ||student_rec.nk ||'''' ;
EXECUTE sqlquery into v_nk; 
raise notice 'Value: %', v_nk;  
END LOOP; 

EXCEPTION when others then    
    raise notice 'Script execution failed.'
                 'Transaction was rolled back.';
    raise notice '% %', SQLERRM, SQLSTATE;

END script $$;

2 Answers 2

3

Even if you have declared v_nk as RECORD, SELECT INTO indeed selects a value into a scalar value, when used in the context of PL/pgSQL. See SELECT INTO documentation for more details.

If you want to print all records with RAISE NOTICE you can loop like this:

sqlquery := 'SELECT col FROM section WHERE rec_nk = ' || '''' || student_rec.nk || '''' ;

FOR v_nk IN EXECUTE sqlquery
    LOOP
        RAISE NOTICE 'Value: %', v_nk;
    END LOOP;
Sign up to request clarification or add additional context in comments.

Comments

0

You already are looping through query result:

[ <<label>> ]
FOR target IN query LOOP
    statements
END LOOP [ label ];

There is also FOR-IN-EXECUTE:

[ <<label>> ]
FOR target IN EXECUTE text_expression [ USING expression [, ... ] ] LOOP
    statements
END LOOP [ label ];

See documentation on Looping Through Query Results.

In your case it would be:

FOR v_nk IN EXECUTE sqlquery LOOP
    RAISE NOTICE 'Value: %', v_nk;
END LOOP;

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.