我有以下程序,我的第二个选择查询返回多个记录, 我应该如何打印所有值..目前它只打印第一个值。 你能建议吗?
实施例。实际产出:
123
890
4599
电流输出: 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 $$;
答案 0 :(得分:0)
您已在循环查询结果:
[ <<label>> ]
FOR target IN query LOOP
statements
END LOOP [ label ];
还有FOR-IN-EXECUTE
:
[ <<label>> ]
FOR target IN EXECUTE text_expression [ USING expression [, ... ] ] LOOP
statements
END LOOP [ label ];
请参阅documentation on Looping Through Query Results。
在你的情况下,它将是:
FOR v_nk IN EXECUTE sqlquery LOOP
raise notice 'Value: %', v_nk;
END LOOP;
答案 1 :(得分:0)
即使你已经将v_nk声明为RECORD,当在PL / pgSQL的上下文中使用时,select into确实会在标量值中选择一个值。请参阅:https://www.postgresql.org/docs/9.6/static/sql-selectinto.html
如果你想通过加注通知打印所有记录,你可以像这样循环:
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;