From the course: Querying Microsoft SQL Server 2019

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Create a counter for a looping statement

Create a counter for a looping statement - SQL Server Tutorial

From the course: Querying Microsoft SQL Server 2019

Start my 1-month free trial

Create a counter for a looping statement

- [Instructor] SQL variables can be used as counters in a looping statement to control how many times a batch of commands will execute. To see how this works, first I'll create a new variable called @Counter. It'll be an integer data type, and I'll set the initial value to one. Then we create the commands that I want to repeat inside of something called a WHILE loop. The following commands are repeat as long as the WHILE condition is true. To have the commands execute three times, for instance, I can say WHILE @Counter <= 3. Every time the commands are executed, it'll increment the value of the @Counter by one. When the @Counter is at four, the WHILE condition becomes false and the loop is complete. After the WHILE condition is set, we need a BEGIN line as well as an END line. Inside of this block are all the different commands that we want to execute multiple times. Let's keep it simple and simply SELECT the value of…

Contents