Using GOTO Statements

Posted: November 11, 2010 in SQL Server 2005

The GOTO statement will stop the execution of a T-SQL command and processing continues from the label where GOTO points.

-- Declare variables
DECLARE @li_counter INT;

-- Initialise variables
SET @li_counter = 1;

-- Loop until the counter reaches 3
WHILE @li_counter < 5
BEGIN
   -- Show the counter value
   Select @li_counter;
   
   -- Set the counter value
   SET @li_counter = @li_counter + 1
   
   -- If the counter hits 2, we want to leave the loop
   IF @li_counter = 3 
   BEGIN
      GOTO leave_while_loop;
   END;
END;

-- Code to execute when leaving while loop
leave_while_loop:
SELECT 'Left while loop.'
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s