Skip to content

GOTO

SQL Server doesn’t support the GOTO statement in the way that other programming languages do. SQL is set-based language, it means it operates on a set of rows and columns instead of single values. Therefore, it lacks flow control structures seen in other procedural languages. In some instances, T-SQL includes the GOTO statement, but it is recommended to avoid using it. Due to this, providing an example would go against best practices in SQL Server development.

Here’s an example of how to use labels and the GOTO statement in your stored procedures using T-SQL:

BEGIN
DECLARE @counter INT;
SET @counter = 0;
PRINT 'Counter initialized'
BEGIN
SET @counter = @counter + 1;
PRINT 'Counter Incremented: ' + CAST(@counter AS VARCHAR);
IF @counter < 10
GOTO BEGIN
END
END
Counter initialized
Counter Incremented: 1
Counter Incremented: 2
Counter Incremented: 3
Counter Incremented: 4
Counter Incremented: 5
Counter Incremented: 6
Counter Incremented: 7
Counter Incremented: 8
Counter Incremented: 9
Counter Incremented: 10

In the code above, a loop is implemented using the GOTO statement. The code begins by initializing a counter variable, then it prints a message indicating that the counter is initialized. Then a label named BEGIN is declared. Within this block, the counter is incremented by 1 and a message indicating the new value of the counter is printed. If the counter is less than 10, the code will jump back to the BEGIN label. This loop will continue until the counter reaches 10. This kind of looping can typically be accomplished more effectively with WHILE or FOR loops.