EXIT

EXIT is a command in SQL that is used to terminate a loop or a subroutine within procedural languages in SQL like PL/SQL or T-SQL. It signals an immediate stop to a program or a block of code and transfers the control to the next sequence. It's often used in loops in conjunction with an IF statement to test for certain conditions, leading to an early end.

Example

DECLARE
x NUMBER := 0;
BEGIN
WHILE x < 10 LOOP
x := x + 1;
IF x = 5 THEN
EXIT;
END IF;
DBMS_OUTPUT.PUT_LINE('x = ' || x);
END LOOP;
END;
/

Output

x = 1
x = 2
x = 3
x = 4

Explanation

The EXIT statement terminates the LOOP when x equals 5. So, it prints the values of x from 1 to 4. When x becomes 5, it stops execution and exits the loop. Therefore, the output shows values only from 1 to 4.

Example

BEGIN
PRINT 'This is before EXIT';
RETURN; -- similar to EXIT
PRINT 'This is after EXIT';
END;

Output

This is before EXIT

Explanation

In the provided SQL Server script, the RETURN statement (which functions similarly to EXIT in some other programming languages) is used to stop execution of the script. The text ‘This is before EXIT’ is printed to the screen, but ‘This is after EXIT’ is not, because the RETURN statement has halted the script before it can be executed.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.