PostgreSQL GOTO like keyword to jump to a block

主宰稳场 提交于 2019-12-11 01:26:07

问题


I have a PostgreSQL function

CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
BEGIN
IF i<0 THEN 
RETURN i + 1;
ELSE
  GOTO label1;
END IF
<<label1>>
RETURN null;
END;
$$ LANGUAGE plpgsql;

In this function I have to GOTO to a label1, but GOTO keyword is not working, can u please help me in getting the way from which I am able to jump from a particular code to label.


回答1:


workaround:

<<label>>
LOOP
   ...
   EXIT label WHEN i > 0;
   ...
   EXIT;
 END LOOP label;
 some;

But I didn't use it ten years - so usually you do some wrong




回答2:


PL/PgSQL does not have GOTO operator.

But, why do you need goto? In your case you can simply remove ELSE and get behavior your are looking for.




回答3:


You don't need GOTO.

DECLARE a boolean variable. Set its value based on whether you want to execute the next block or not. Wrap that block in an IF that tests the variable. Magic, it's skipped!

I'm assuming your code is cut-down and simplified, because otherwise it'd make no sense. Here's one way to do it, assuming you can't just delete the "ELSE ... GOTO" and let control flow on.

CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
DECLARE
    run_condition boolean = 't';
BEGIN
  IF i<0 THEN
    RETURN i + 1;
  ELSE
    run_condition = 'f';
  END IF;
  IF run_condition THEN
    -- Do the optional thing
  END;
  RETURN null;
END;
$$ LANGUAGE plpgsql;



回答4:


Another nested Begin block?

BEGIN
  <<label1>>
  BEGIN 
      IF i<0 THEN 
          RETURN i + 1;
      ELSE
          EXIT label1;
      END IF;
  END;
  RETURN null;
END;


来源:https://stackoverflow.com/questions/13508190/postgresql-goto-like-keyword-to-jump-to-a-block

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