Credit portal




If and While Statement in SQL Server 2012

SQL Server

In this article, we will see how to use If and While statements in SQL Server. If you have programmed in languages like C# or other languages then you are probably familiar with If and While statements. Transact-SQL also gives you this option to repeat the expression using a While loop and check the condition with an If loop. So let's take a look at a practical example of If and While statements with break and continue into SQL Server 2012. The example is developed in SQL Server 2012 using the SQL Server Management Studio. There are some simple steps to do that are described here.

While Statement

If the expression is true, the statement is executed, and then the expression is evaluated again to determine if the statement should be executed again. This process repeats until the expression evaluates to false.

print 'While statement'

DECLARE @countnumber varchar ( 50 )

SET @countnumber = 1

WHILE ( @countnumber <= 30 )


PRINT 'Number=' + @countnumber

SET @countnumber = @countnumber + 3


The execution of statements in the WHILE loop can be controlled from inside the loop with the break and continue keywords.

Break forces a loop to exit immediately. Suppose we repeat a number from 1 to 20. The loop will go through all the numbers. We want to exit when we get to the number 11 in the loop. That can be done simply by using the break keyword with a while loop.

-- While Statement with Beak

print 'While Statement with break'

DECLARE @countnumber varchar ( 50 )

WHILE ( @countnumber <= 30 )

This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code. The continue statement skips the value and jumps to the while loop without terminating the loop.

Category: Forex

Similar articles: