BREAK statement in PL/pgSQL

心不动则不痛 提交于 2019-12-19 05:08:20

问题


How to have the break statement in PostgreSQL? I have the structure like this:

for()
 {
 for()
 {
  if(somecondition)
  break;
 }
}

As per my understanding it should only break the inner for loop?


回答1:


There is no BREAK in PL/pgSQL.

EXIT terminates the loop.
CONTINUE continues at the next iteration of the loop.
You can attach a <<label>> to loops and add it as parameter to each of these commands. Then you terminate / continue the labeled loop. Else, it concerns the inner loop.
RETURN exits from the function (so not applicable in a DO statement).

All of this applies to procedural elements of PL/pgSQL, not SQL.
Code example using all three:

  • Loop in function does not work as expected



回答2:


Note, that: Yes! you need the "WHEN", even if you end up (like me ;-)) with something like

LOOP
  ...
  IF l_my_var = 'some condition' THEN
    -- this is ok, bla
    IF l_debug_level >= 2 THEN
      RAISE NOTICE 'debug 2: skipping a duplicate %, l_my_var;
    END IF;
    -- do something
    CONTINUE WHEN TRUE; -- https://stackoverflow.com/questions/15173194/break-statement-in-pl-pgsql
  ELSE
    -- do something
  END IF;
  ...

which looks somewhat twisted with both IF and WHEN.

Remark to the editor: One could make the link behind "CONTINUE" more precise: https://www.postgresql.org/docs/9.6/plpgsql-control-structures.html#AEN66440



来源:https://stackoverflow.com/questions/15173194/break-statement-in-pl-pgsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!