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 $$;
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;