Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax of for-loop in SQL Server

What is the syntax of a for loop in TSQL?

like image 215
Macho Avatar asked May 20 '11 07:05

Macho


People also ask

What is the syntax of for loop in SQL?

The counter is always incremented by 1 and once the counter reaches the value of end integer, the loop ends. Syntax of for loop: FOR counter IN initial_value .. final_value LOOP.

What is for loop in SQL Server?

In SQL Server, a loop is the technique where a set of SQL statements are executed repeatedly until a condition is met. SQL Server supports the WHILE loop. The execution of the statements can be controlled from within the WHLE block using BREAK and CONTINUE keywords.

Can we use for loop in SQL query?

There is no FOR in SQL, But you can use WHILE or GOTO to achieve the way how the FOR will work. I always prefer WHILE over GOTO statement. Show activity on this post. For loop is not officially supported yet by SQL server.

What are 3 types of loops in SQL?

PL/SQL provides four kinds of loop statements: basic loop, WHILE loop, FOR loop, and cursor FOR loop.


2 Answers

There is no for-loop, only the while-loop:

DECLARE @i int = 0  WHILE @i < 20 BEGIN     SET @i = @i + 1     /* do some work */ END 
like image 104
TcKs Avatar answered Sep 20 '22 06:09

TcKs


T-SQL doesn't have a FOR loop, it has a WHILE loop
WHILE (Transact-SQL)

WHILE Boolean_expression BEGIN  END 
like image 32
jams Avatar answered Sep 19 '22 06:09

jams