Home > SQL Server > SQL SERVER – Jumping between statements using GOTO – TSQL Control Statement

SQL SERVER – Jumping between statements using GOTO – TSQL Control Statement


GOTO is a programing statement used to transfer program execution control from one statement another. It is called an one-way-transfer. Because, it will not return the execution control back to the transfer initiated statement.

The goto statement is often combined with the if statement to cause a conditional transfer of control.  But we can also use GOTO without if statement.

GOTO in Transact-SQL

GOTO statement requires a label to transfer the flow of execution. The label should be a valid identifier value followed by colon (:).  A sample label statement look like this LABEL1:

Syntax for using GOTO statement

labelname:
GOTO labename

Example

1. A simple example used to print a string

Section1:
PRINT ‘Section 1’
GOTO Section3
Section2:
PRINT ‘Section 2’
GOTO Section1
Section3:
 
Output:

pic12. Another sample for executing a infinite loop using GOTO

Declare @i int = 0
loop:
PRINT ‘Loop I= ‘ + cast(@i as varchar(10))
set @i = @i + 1
GOTO loop
 
Output:
pic2

GOTO statement is not recommended to use in the programming. Because, tracing program flow in a large line of code is difficult and it decreased the code readability.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: