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
   -- 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 
      GOTO leave_while_loop;

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

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s