GOTO Statements
A GOTO statement unconditionally transfers the control from the current statement to a labeled statement. The GOTO statement changes the execution logic. Therefore, use this statement only when necessary. Alternatively, you can use the EXCEPTION statement to handle issues in special scenarios. To execute a GOTO statement, the labeled statement must be unique.
Syntax
label declaration ::=
goto statement ::=
Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
gaussdb=# CREATE OR REPLACE PROCEDURE GOTO_test() AS DECLARE v1 int; BEGIN v1 := 0; LOOP EXIT WHEN v1 > 100; v1 := v1 + 2; if v1 > 25 THEN GOTO pos1; END IF; END LOOP; <<pos1>> v1 := v1 + 10; raise info 'v1 is %. ', v1; END; / CREATE PROCEDURE gaussdb=#call GOTO_test(); INFO: v1 is 36. goto_test ----------- (1 row) |
Constraints
Using GOTO statements has the following constraints:
- Does not allow multiple labeled statements even if the statements are in different blocks.
1 2 3 4 5 6 7
BEGIN GOTO pos1; <<pos1>> SELECT * FROM ... <<pos1>> UPDATE t1 SET ... END;
- Cannot transfer control to the IF, CASE, or LOOP statement.
1 2 3 4 5 6 7
BEGIN GOTO pos1; IF valid THEN <<pos1>> SELECT * FROM ... END IF; END;
- Cannot transfer control from one IF clause to another, or from one WHEN clause in the CASE statement to another.
1 2 3 4 5 6 7 8 9
BEGIN IF valid THEN GOTO pos1; SELECT * FROM ... ELSE <<pos1>> UPDATE t1 SET ... END IF; END;
- Cannot transfer control from an outer block to an inner BEGIN-END block.
1 2 3 4 5 6 7
BEGIN GOTO pos1; BEGIN <<pos1>> UPDATE t1 SET ... END; END;
- Cannot transfer control from an exception handler to the current BEGIN-END block, but can transfer control to the upper-layer BEGIN-END block.
1 2 3 4 5 6 7
BEGIN <<pos1>> UPDATE t1 SET ... EXCEPTION WHEN condition THEN GOTO pos1; END;
- To branch to a position that does not have an executable statement, you need to add the NULL statement.
1 2 3 4 5 6 7 8 9 10 11 12
DECLARE done BOOLEAN; BEGIN FOR i IN 1..50 LOOP IF done THEN GOTO end_loop; END IF; <<end_loop>> -- You cannot run the GOTO statement to go here unless there is an executable statement following it. NULL; -- The statement added here is used to avoid errors. END LOOP; -- If the previous sentence NULL does not exist, an error is reported. END; /
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot