From the course: Hands-On Advanced SQL Server: Strategies and Techniques
Unlock this course with a free trial
Join today to access over 25,300 courses taught by industry experts.
WHILE Loops - SQL Server Tutorial
From the course: Hands-On Advanced SQL Server: Strategies and Techniques
WHILE Loops
- [Instructor] In the last video, you wrote some sequel that made decisions using the IF statement. In this video, you're going to learn how to make SQL repeat logic using a WHILE loop. Now, this is useful when you need to perform an action multiple times until a certain condition is no longer true. So, a WHILE loop keeps running a block of code as long as the condition you define is true. It's one of the simplest and most powerful control flow tools in SQL Server. So let's take a look at an example here. With this code, we build a loop that returns three small results one row at a time. Let's start with the very first line. DECLARE Count equal one creates our loop counter. WHILE Count is less than or equal to three checks the condition. Keep looping while the count is less than three. Now, inside the loop between this BEGIN and END block here we have a SELECT statement. This returns a simple label like looping step one, looping step two, and so forth. Now this particular statement…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.