logo

SQL Server W PĘTLI PODCZAS

W tym artykule dowiesz się o pełnym omówieniu używania pętli WHILE w SQL Server. A Pętla WHILE to instrukcja przepływu sterowania używana do wielokrotnego wykonywania zestawu instrukcji, aż do spełnienia określonego warunku . Pętla zaczyna się od podanego warunku, należy go ocenić i jeśli jest PRAWDA, instrukcje zostaną umieszczone w pętli w celu dalszego wykonania. Jeśli warunek stanie się FALSE, program nie zostanie uruchomiony. Oznacza to, że pętla while w SQL Server może działać zero lub więcej razy.

Schemat blokowy pętli WHILE

Poniższy schemat blokowy wyjaśni pełny przebieg pętli WHILE w SQL Server:

unia kontra unia wszystkich
SQL Server W PĘTLI PODCZAS

Na tym wykresie widzimy, że dla każdej iteracji sprawdzany jest określony warunek i na podstawie wyniku oceny określany jest przepływ kodu. Jeśli wynik zostanie oceniony jako PRAWDA, przepływ sterowania przechodzi do pętli w celu dalszego wykonania. Jeśli oceniony wynik ma wartość FAŁSZ, przepływ sterowania opuści pętlę i zostaną wykonane wszelkie instrukcje lub zapytania poza pętlą.

Składnia

Poniższa składnia ilustruje pętlę WHILE w SQL Server:

 WHILE boolean_condition BEGIN BREAK END; 

W tej składni mamy następujące parametry lub argumenty:

    warunek_logiczny:Jest to wymagany warunek, który będzie testowany w każdej iteracji, aby zwrócić wynik PRAWDA lub FAŁSZ. Jeżeli jest to instrukcja SELECT, należy ją ująć w nawias.instrukcja_sql lub blok_instrukcji:Instrukcja SQL lub grupowanie jest zdefiniowane wewnątrz słów kluczowych BEGIN i END. Będzie wykonywany w każdej iteracji, aż pętla stanie się FALSE.Przerwa:Natychmiast kończy to najbardziej wewnętrzną pętlę, a przepływ sterowania zostaje wznowiony od następnej instrukcji po pętli.Kontynuować:Przechodzi do następnej iteracji bez pomijania pozostałych instrukcji wewnątrz pętli. Zwykle powoduje to ponowne uruchomienie pętli od początku.

Przykład pętli WHILE

Pozwól nam zrozumieć, jak pętla WHILE działa w SQL Server na przykładzie. W podanym przykładzie najpierw zadeklarowaliśmy wartość typ całkowity i ustaw jego wartość na 1. Następnie pętla WHILE sprawdza warunek i czy tak jest PRAWDA , wydrukowana zostanie instrukcja drukowania. Kiedy pętla stanie się FAŁSZ , zostanie wydrukowana następna instrukcja po pętli WHILE.

 DECLARE @stud_value INT; SET @stud_value = 1; WHILE @stud_value <= 5 begin print 'mark henry'; set @stud_value="@stud_value" + 1; end; 'rose bennet'; < pre> <p>Executing this statement will return the following output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-2.webp" alt="SQL Server WHILE LOOP"> <p>In the above WHILE loop code snippet, we must increment the variable&apos;s value after each iteration. See the below part of the above code line as <strong>SET @stud_value = @stud_value + 1</strong> . If we do not write this statement, the loop will execute infinitely because it cannot becomes FALSE.</p> <pre> BEGIN PRINT &apos;Mark Henry&apos;; SET @stud_value = @stud_value + 1; END; </pre> <h3>Infinite WHILE Loop</h3> <p>An infinite loop occurs when the evaluation of a condition will never be false. Therefore, the loop will never end and be executed forever. The loop in the following code snippet is infinite because the variable&apos;s value is not incremented.</p> <pre> DECLARE @stud_value INT; SET @stud_value = 1; WHILE @stud_value <= 5 begin print 'please stop execution!' end; < pre> <p>Executing the loop will display the below output. This loop will never end its execution until we do not cancel their execution of the query manually.</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-3.webp" alt="SQL Server WHILE LOOP"> <h3>Inserting Records with WHILE Loop</h3> <p>We can also use the WHILE loop to insert records into the defined table. Let us see how to inserts dummy records into the database. First, we will create a table named <strong>&apos;bikeshop&apos;</strong> containing three columns: <strong>Id, bike_name,</strong> and <strong>price</strong> . Execute the following statement to create this table:</p> <pre> CREATE TABLE bikeshop ( Id INT PRIMARY KEY IDENTITY, bike_name VARCHAR (50) NOT NULL, price FLOAT ) </pre> <p>Next, we will use the WHILE loop to insert ten records into this table by executing the following script:</p> <pre> DECLARE @count INT; SET @count = 1; WHILE @count <= 10 begin insert into bikeshop values('bike-' + cast(@count as varchar), @count*5000) set @count="@count" 1; end; < pre> <p>In this code, we have declared a variable @ <strong>count</strong> and then initialize its value with 1 using a SET clause. Next, we have to define the loop body that executes the INSERT statement to add one record in each execution. The <strong>bike_name column</strong> will append the value of a @count variable with the string <strong>Bike</strong> , and the <strong>price</strong> column determines by the value of a @count variable multiplied by <strong>5000</strong> . The loop will execute until the value of the @count variable becomes FALSE. It means the WHILE loop will execute ten times and <strong>inserts ten records</strong> into the table bikeshop.</p> <p>Now, we can verify all the records of the bikeshop table with the SELECT statement. It will display the following output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-4.webp" alt="SQL Server WHILE LOOP"> <h3>BREAK Statement</h3> <p>SQL Server also allows us to use the BREAK statement in the WHILE loop like programming languages. This statement is used to <strong>immediately stop the current iteration of the loop</strong> , and control flow resumes with the next statement after the loop. In general, we will use the <a href="/sql-server-if-else"> <strong>IF...ELSE statement</strong> </a> to check whether or not a condition has occurred.</p> <p>The following example will explain how to use the BREAK statement in the WHILE loop:</p> <pre> DECLARE @count INT; SET @count = 1; WHILE @count = 6 BEGIN BREAK END SET @Count = @Count + 1 END; </pre> <p>Executing the code will display the below output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-5.webp" alt="SQL Server WHILE LOOP"> <p>The value of the variable is first evaluated in this code. If it is TRUE, the control enters into the loop and prints the statement. When the variable value is greater than or equal to 6, control enters the IF...ELSE block and executes the BREAK statement to terminate the loop. If an IF...ELSE block fails to meet the condition; then, the loop will keep running until the condition is changed to FALSE.</p> <h3>CONTINUE Statement</h3> <p>SQL Server also allows us to use the CONTINUE statement in the WHILE loop like programming languages. This statement immediately <strong>terminates the current execution of the loop when the specified condition is met</strong> , and control flow returns to the beginning of the loop. In general, the IF...ELSE statement will be used to test whether or not a condition has been met.</p> <p>The CONTINUE statement in the WHILE loop is demonstrated in the following example. In this example, we&apos;ll assume that we wish to use a WHILE loop to <strong>print only odd values</strong> . The CONTINUE statement can be used to do this. This example will first <strong>test</strong> whether the variable value is <strong>odd or even</strong> . If it is even, the execution goes inside the IF&#x2026;ELSE statement blocks and decrement the variable value by one. Then, it will execute the CONTINUE statement and starts a new iteration from the beginning.</p> <pre> DECLARE @Count INT SET @Count = 1 WHILE (@Count <= 1 2="0" 44 20) begin if @count % set + continue end print 'the odd value is=" + CONVERT(VARCHAR, @Count) SET @Count = @Count + 1 END &lt;/pre&gt; &lt;p&gt;Executing the code snippet will display the below output:&lt;/p&gt; &lt;img src=" techcodeview.com img sql-server-tutorials sql-server-while-loop-6.webp' alt="SQL Server WHILE LOOP"> <h3>How to implementing paging with WHILE loop in SQL Server?</h3> <p>We can also use the WHILE loop for implementing the paging. Paging allows displaying the subset of records from a table at any particular time. The following example will explain this concept. The WHILE loop in the code will select two records from the bikeshop table at a time. The records that have been chosen are then displayed in the output.</p> <pre> DECLARE @count INT DECLARE @limit INT; SET @count = 0 SET @limit = 2; WHILE @count <10 begin select * from bikeshop order by id offset @count rows fetch next @limit only set + 2; end; < pre> <p>Executing the code snippet will return the below output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-7.webp" alt="SQL Server WHILE LOOP"> <h3>Nested WHILE Loop</h3> <p>The Nested WHILE Loop in SQL Server is simply a WHILE Loop written inside another WHILE Loop. When we work on multi-layered data, the Nested WHILE loops are essential. Because this concept is useful in extracting the layered data when we want to select them, it is recommended to be careful while using the nested loop.</p> <p> <strong>Syntax</strong> </p> <p>The following syntax illustrate the working of the nested WHILE Loop in SQL Server:</p> <pre> WHILE Expression BEGIN WHILE @Val2 <= 10 begin --second while loop statements sql end --this statement is outside the second --which first -- this < pre> <p>Let us explain this syntax step by step:</p> <p> <strong>Step 1:</strong> The loop starts by checking the first WHILE loop condition, and if it finds a false result, it will exit from While Loop. Otherwise, if the result is true, the control goes inside the BEGIN and END block for further execution. This block will start the execution of the second WHILE loop. See step 2.</p> <p> <strong>Step 2:</strong> This step will check the condition in the Nested WHILE Loop, and if it is false, the second loop will be exit and execute the statement outside this. Otherwise, if the result is true, the control goes inside the BEGIN and END block for further execution.</p> <p> <strong>Step 3:</strong> Once all the statements execute from the second WHILE loop, the control goes to the first WHILE and repeats the first step.</p> <p> <strong>Example</strong> </p> <p>The following example will print the multiplication table of 5 up to 10 using the nested WHILE loop.</p> <pre> DECLARE @val1 INT DECLARE @val2 INT SET @val1 = 5 SET @val2 = 1 WHILE @val1 <= 5 44 begin while @val2 <="10" print convert(varchar, @val1) + ' * @val2) techcodeview.com img sql-server-tutorials sql-server-while-loop-8.webp' alt="SQL Server WHILE LOOP"> <h2>Conclusion</h2> <p>The WHILE loop is a useful method when there is a need to execute a SQL script repeatedly. The article explained how to work with the WHILE loop in MS SQL Server to execute operations such as record insertion and pagination with a simple example. Here we have also learned the BREAK and CONTINUE statements to control the WHILE loop iteration.</p> <hr></=></pre></=></pre></10></pre></=></pre></=></pre></=></pre></=>

Nieskończona pętla WHILE

Nieskończona pętla ma miejsce, gdy ocena warunku nigdy nie będzie fałszywa. Dlatego pętla nigdy się nie zakończy i będzie wykonywana w nieskończoność. Pętla w poniższym fragmencie kodu jest nieskończona, ponieważ wartość zmiennej nie jest zwiększana.

 DECLARE @stud_value INT; SET @stud_value = 1; WHILE @stud_value <= 5 begin print \'please stop execution!\' end; < pre> <p>Executing the loop will display the below output. This loop will never end its execution until we do not cancel their execution of the query manually.</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-3.webp" alt="SQL Server WHILE LOOP"> <h3>Inserting Records with WHILE Loop</h3> <p>We can also use the WHILE loop to insert records into the defined table. Let us see how to inserts dummy records into the database. First, we will create a table named <strong>&apos;bikeshop&apos;</strong> containing three columns: <strong>Id, bike_name,</strong> and <strong>price</strong> . Execute the following statement to create this table:</p> <pre> CREATE TABLE bikeshop ( Id INT PRIMARY KEY IDENTITY, bike_name VARCHAR (50) NOT NULL, price FLOAT ) </pre> <p>Next, we will use the WHILE loop to insert ten records into this table by executing the following script:</p> <pre> DECLARE @count INT; SET @count = 1; WHILE @count <= 10 begin insert into bikeshop values(\'bike-\' + cast(@count as varchar), @count*5000) set @count="@count" 1; end; < pre> <p>In this code, we have declared a variable @ <strong>count</strong> and then initialize its value with 1 using a SET clause. Next, we have to define the loop body that executes the INSERT statement to add one record in each execution. The <strong>bike_name column</strong> will append the value of a @count variable with the string <strong>Bike</strong> , and the <strong>price</strong> column determines by the value of a @count variable multiplied by <strong>5000</strong> . The loop will execute until the value of the @count variable becomes FALSE. It means the WHILE loop will execute ten times and <strong>inserts ten records</strong> into the table bikeshop.</p> <p>Now, we can verify all the records of the bikeshop table with the SELECT statement. It will display the following output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-4.webp" alt="SQL Server WHILE LOOP"> <h3>BREAK Statement</h3> <p>SQL Server also allows us to use the BREAK statement in the WHILE loop like programming languages. This statement is used to <strong>immediately stop the current iteration of the loop</strong> , and control flow resumes with the next statement after the loop. In general, we will use the <a href="/sql-server-if-else"> <strong>IF...ELSE statement</strong> </a> to check whether or not a condition has occurred.</p> <p>The following example will explain how to use the BREAK statement in the WHILE loop:</p> <pre> DECLARE @count INT; SET @count = 1; WHILE @count = 6 BEGIN BREAK END SET @Count = @Count + 1 END; </pre> <p>Executing the code will display the below output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-5.webp" alt="SQL Server WHILE LOOP"> <p>The value of the variable is first evaluated in this code. If it is TRUE, the control enters into the loop and prints the statement. When the variable value is greater than or equal to 6, control enters the IF...ELSE block and executes the BREAK statement to terminate the loop. If an IF...ELSE block fails to meet the condition; then, the loop will keep running until the condition is changed to FALSE.</p> <h3>CONTINUE Statement</h3> <p>SQL Server also allows us to use the CONTINUE statement in the WHILE loop like programming languages. This statement immediately <strong>terminates the current execution of the loop when the specified condition is met</strong> , and control flow returns to the beginning of the loop. In general, the IF...ELSE statement will be used to test whether or not a condition has been met.</p> <p>The CONTINUE statement in the WHILE loop is demonstrated in the following example. In this example, we&apos;ll assume that we wish to use a WHILE loop to <strong>print only odd values</strong> . The CONTINUE statement can be used to do this. This example will first <strong>test</strong> whether the variable value is <strong>odd or even</strong> . If it is even, the execution goes inside the IF&#x2026;ELSE statement blocks and decrement the variable value by one. Then, it will execute the CONTINUE statement and starts a new iteration from the beginning.</p> <pre> DECLARE @Count INT SET @Count = 1 WHILE (@Count <= 1 2="0" 44 20) begin if @count % set + continue end print \'the odd value is=" + CONVERT(VARCHAR, @Count) SET @Count = @Count + 1 END &lt;/pre&gt; &lt;p&gt;Executing the code snippet will display the below output:&lt;/p&gt; &lt;img src=" techcodeview.com img sql-server-tutorials sql-server-while-loop-6.webp\' alt="SQL Server WHILE LOOP"> <h3>How to implementing paging with WHILE loop in SQL Server?</h3> <p>We can also use the WHILE loop for implementing the paging. Paging allows displaying the subset of records from a table at any particular time. The following example will explain this concept. The WHILE loop in the code will select two records from the bikeshop table at a time. The records that have been chosen are then displayed in the output.</p> <pre> DECLARE @count INT DECLARE @limit INT; SET @count = 0 SET @limit = 2; WHILE @count <10 begin select * from bikeshop order by id offset @count rows fetch next @limit only set + 2; end; < pre> <p>Executing the code snippet will return the below output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-7.webp" alt="SQL Server WHILE LOOP"> <h3>Nested WHILE Loop</h3> <p>The Nested WHILE Loop in SQL Server is simply a WHILE Loop written inside another WHILE Loop. When we work on multi-layered data, the Nested WHILE loops are essential. Because this concept is useful in extracting the layered data when we want to select them, it is recommended to be careful while using the nested loop.</p> <p> <strong>Syntax</strong> </p> <p>The following syntax illustrate the working of the nested WHILE Loop in SQL Server:</p> <pre> WHILE Expression BEGIN WHILE @Val2 <= 10 begin --second while loop statements sql end --this statement is outside the second --which first -- this < pre> <p>Let us explain this syntax step by step:</p> <p> <strong>Step 1:</strong> The loop starts by checking the first WHILE loop condition, and if it finds a false result, it will exit from While Loop. Otherwise, if the result is true, the control goes inside the BEGIN and END block for further execution. This block will start the execution of the second WHILE loop. See step 2.</p> <p> <strong>Step 2:</strong> This step will check the condition in the Nested WHILE Loop, and if it is false, the second loop will be exit and execute the statement outside this. Otherwise, if the result is true, the control goes inside the BEGIN and END block for further execution.</p> <p> <strong>Step 3:</strong> Once all the statements execute from the second WHILE loop, the control goes to the first WHILE and repeats the first step.</p> <p> <strong>Example</strong> </p> <p>The following example will print the multiplication table of 5 up to 10 using the nested WHILE loop.</p> <pre> DECLARE @val1 INT DECLARE @val2 INT SET @val1 = 5 SET @val2 = 1 WHILE @val1 <= 5 44 begin while @val2 <="10" print convert(varchar, @val1) + \' * @val2) techcodeview.com img sql-server-tutorials sql-server-while-loop-8.webp\' alt="SQL Server WHILE LOOP"> <h2>Conclusion</h2> <p>The WHILE loop is a useful method when there is a need to execute a SQL script repeatedly. The article explained how to work with the WHILE loop in MS SQL Server to execute operations such as record insertion and pagination with a simple example. Here we have also learned the BREAK and CONTINUE statements to control the WHILE loop iteration.</p> <hr></=></pre></=></pre></10></pre></=></pre></=></pre></=>

Następnie użyjemy pętli WHILE, aby wstawić dziesięć rekordów do tej tabeli, wykonując następujący skrypt:

co to jest ul
 DECLARE @count INT; SET @count = 1; WHILE @count <= 10 begin insert into bikeshop values(\'bike-\' + cast(@count as varchar), @count*5000) set @count="@count" 1; end; < pre> <p>In this code, we have declared a variable @ <strong>count</strong> and then initialize its value with 1 using a SET clause. Next, we have to define the loop body that executes the INSERT statement to add one record in each execution. The <strong>bike_name column</strong> will append the value of a @count variable with the string <strong>Bike</strong> , and the <strong>price</strong> column determines by the value of a @count variable multiplied by <strong>5000</strong> . The loop will execute until the value of the @count variable becomes FALSE. It means the WHILE loop will execute ten times and <strong>inserts ten records</strong> into the table bikeshop.</p> <p>Now, we can verify all the records of the bikeshop table with the SELECT statement. It will display the following output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-4.webp" alt="SQL Server WHILE LOOP"> <h3>BREAK Statement</h3> <p>SQL Server also allows us to use the BREAK statement in the WHILE loop like programming languages. This statement is used to <strong>immediately stop the current iteration of the loop</strong> , and control flow resumes with the next statement after the loop. In general, we will use the <a href="/sql-server-if-else"> <strong>IF...ELSE statement</strong> </a> to check whether or not a condition has occurred.</p> <p>The following example will explain how to use the BREAK statement in the WHILE loop:</p> <pre> DECLARE @count INT; SET @count = 1; WHILE @count = 6 BEGIN BREAK END SET @Count = @Count + 1 END; </pre> <p>Executing the code will display the below output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-5.webp" alt="SQL Server WHILE LOOP"> <p>The value of the variable is first evaluated in this code. If it is TRUE, the control enters into the loop and prints the statement. When the variable value is greater than or equal to 6, control enters the IF...ELSE block and executes the BREAK statement to terminate the loop. If an IF...ELSE block fails to meet the condition; then, the loop will keep running until the condition is changed to FALSE.</p> <h3>CONTINUE Statement</h3> <p>SQL Server also allows us to use the CONTINUE statement in the WHILE loop like programming languages. This statement immediately <strong>terminates the current execution of the loop when the specified condition is met</strong> , and control flow returns to the beginning of the loop. In general, the IF...ELSE statement will be used to test whether or not a condition has been met.</p> <p>The CONTINUE statement in the WHILE loop is demonstrated in the following example. In this example, we&apos;ll assume that we wish to use a WHILE loop to <strong>print only odd values</strong> . The CONTINUE statement can be used to do this. This example will first <strong>test</strong> whether the variable value is <strong>odd or even</strong> . If it is even, the execution goes inside the IF&#x2026;ELSE statement blocks and decrement the variable value by one. Then, it will execute the CONTINUE statement and starts a new iteration from the beginning.</p> <pre> DECLARE @Count INT SET @Count = 1 WHILE (@Count <= 1 2="0" 44 20) begin if @count % set + continue end print \'the odd value is=" + CONVERT(VARCHAR, @Count) SET @Count = @Count + 1 END &lt;/pre&gt; &lt;p&gt;Executing the code snippet will display the below output:&lt;/p&gt; &lt;img src=" techcodeview.com img sql-server-tutorials sql-server-while-loop-6.webp\' alt="SQL Server WHILE LOOP"> <h3>How to implementing paging with WHILE loop in SQL Server?</h3> <p>We can also use the WHILE loop for implementing the paging. Paging allows displaying the subset of records from a table at any particular time. The following example will explain this concept. The WHILE loop in the code will select two records from the bikeshop table at a time. The records that have been chosen are then displayed in the output.</p> <pre> DECLARE @count INT DECLARE @limit INT; SET @count = 0 SET @limit = 2; WHILE @count <10 begin select * from bikeshop order by id offset @count rows fetch next @limit only set + 2; end; < pre> <p>Executing the code snippet will return the below output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-7.webp" alt="SQL Server WHILE LOOP"> <h3>Nested WHILE Loop</h3> <p>The Nested WHILE Loop in SQL Server is simply a WHILE Loop written inside another WHILE Loop. When we work on multi-layered data, the Nested WHILE loops are essential. Because this concept is useful in extracting the layered data when we want to select them, it is recommended to be careful while using the nested loop.</p> <p> <strong>Syntax</strong> </p> <p>The following syntax illustrate the working of the nested WHILE Loop in SQL Server:</p> <pre> WHILE Expression BEGIN WHILE @Val2 <= 10 begin --second while loop statements sql end --this statement is outside the second --which first -- this < pre> <p>Let us explain this syntax step by step:</p> <p> <strong>Step 1:</strong> The loop starts by checking the first WHILE loop condition, and if it finds a false result, it will exit from While Loop. Otherwise, if the result is true, the control goes inside the BEGIN and END block for further execution. This block will start the execution of the second WHILE loop. See step 2.</p> <p> <strong>Step 2:</strong> This step will check the condition in the Nested WHILE Loop, and if it is false, the second loop will be exit and execute the statement outside this. Otherwise, if the result is true, the control goes inside the BEGIN and END block for further execution.</p> <p> <strong>Step 3:</strong> Once all the statements execute from the second WHILE loop, the control goes to the first WHILE and repeats the first step.</p> <p> <strong>Example</strong> </p> <p>The following example will print the multiplication table of 5 up to 10 using the nested WHILE loop.</p> <pre> DECLARE @val1 INT DECLARE @val2 INT SET @val1 = 5 SET @val2 = 1 WHILE @val1 <= 5 44 begin while @val2 <="10" print convert(varchar, @val1) + \' * @val2) techcodeview.com img sql-server-tutorials sql-server-while-loop-8.webp\' alt="SQL Server WHILE LOOP"> <h2>Conclusion</h2> <p>The WHILE loop is a useful method when there is a need to execute a SQL script repeatedly. The article explained how to work with the WHILE loop in MS SQL Server to execute operations such as record insertion and pagination with a simple example. Here we have also learned the BREAK and CONTINUE statements to control the WHILE loop iteration.</p> <hr></=></pre></=></pre></10></pre></=></pre></=>

Wykonanie kodu wyświetli poniższe dane wyjściowe:

SQL Server W PĘTLI PODCZAS

Wartość zmiennej jest najpierw oceniana w tym kodzie. Jeśli ma wartość TRUE, sterowanie wchodzi do pętli i drukuje instrukcję. Gdy wartość zmiennej jest większa lub równa 6, sterowanie wchodzi do bloku IF...ELSE i wykonuje instrukcję break, aby zakończyć pętlę. Jeśli blok IF...ELSE nie spełnia warunku; następnie pętla będzie działać, dopóki warunek nie zostanie zmieniony na FAŁSZ.

KONTYNUUJ oświadczenie

SQL Server pozwala nam również używać instrukcji CONTINUE w pętli WHILE, podobnie jak w przypadku języków programowania. To stwierdzenie natychmiast kończy bieżące wykonanie pętli, gdy spełniony jest określony warunek , a przepływ sterowania powraca na początek pętli. Ogólnie rzecz biorąc, instrukcja IF...ELSE będzie używana do sprawdzania, czy warunek został spełniony.

Instrukcja CONTINUE w pętli WHILE została zademonstrowana w poniższym przykładzie. W tym przykładzie założymy, że chcemy użyć pętli WHILE drukuj tylko wartości nieparzyste . W tym celu można użyć instrukcji CONTINUE. Ten przykład będzie pierwszy test czy wartość zmiennej wynosi nieparzysty czy parzysty . Jeśli jest parzysta, wykonanie przechodzi do bloków instrukcji IF…ELSE i zmniejsza wartość zmiennej o jeden. Następnie wykona instrukcję CONTINUE i rozpocznie nową iterację od początku.

javascript najbliżej
 DECLARE @Count INT SET @Count = 1 WHILE (@Count <= 1 2="0" 44 20) begin if @count % set + continue end print \'the odd value is=" + CONVERT(VARCHAR, @Count) SET @Count = @Count + 1 END &lt;/pre&gt; &lt;p&gt;Executing the code snippet will display the below output:&lt;/p&gt; &lt;img src=" techcodeview.com img sql-server-tutorials sql-server-while-loop-6.webp\' alt="SQL Server WHILE LOOP"> <h3>How to implementing paging with WHILE loop in SQL Server?</h3> <p>We can also use the WHILE loop for implementing the paging. Paging allows displaying the subset of records from a table at any particular time. The following example will explain this concept. The WHILE loop in the code will select two records from the bikeshop table at a time. The records that have been chosen are then displayed in the output.</p> <pre> DECLARE @count INT DECLARE @limit INT; SET @count = 0 SET @limit = 2; WHILE @count <10 begin select * from bikeshop order by id offset @count rows fetch next @limit only set + 2; end; < pre> <p>Executing the code snippet will return the below output:</p> <img src="//techcodeview.com/img/sql-server-tutorials/44/sql-server-while-loop-7.webp" alt="SQL Server WHILE LOOP"> <h3>Nested WHILE Loop</h3> <p>The Nested WHILE Loop in SQL Server is simply a WHILE Loop written inside another WHILE Loop. When we work on multi-layered data, the Nested WHILE loops are essential. Because this concept is useful in extracting the layered data when we want to select them, it is recommended to be careful while using the nested loop.</p> <p> <strong>Syntax</strong> </p> <p>The following syntax illustrate the working of the nested WHILE Loop in SQL Server:</p> <pre> WHILE Expression BEGIN WHILE @Val2 <= 10 begin --second while loop statements sql end --this statement is outside the second --which first -- this < pre> <p>Let us explain this syntax step by step:</p> <p> <strong>Step 1:</strong> The loop starts by checking the first WHILE loop condition, and if it finds a false result, it will exit from While Loop. Otherwise, if the result is true, the control goes inside the BEGIN and END block for further execution. This block will start the execution of the second WHILE loop. See step 2.</p> <p> <strong>Step 2:</strong> This step will check the condition in the Nested WHILE Loop, and if it is false, the second loop will be exit and execute the statement outside this. Otherwise, if the result is true, the control goes inside the BEGIN and END block for further execution.</p> <p> <strong>Step 3:</strong> Once all the statements execute from the second WHILE loop, the control goes to the first WHILE and repeats the first step.</p> <p> <strong>Example</strong> </p> <p>The following example will print the multiplication table of 5 up to 10 using the nested WHILE loop.</p> <pre> DECLARE @val1 INT DECLARE @val2 INT SET @val1 = 5 SET @val2 = 1 WHILE @val1 <= 5 44 begin while @val2 <="10" print convert(varchar, @val1) + \' * @val2) techcodeview.com img sql-server-tutorials sql-server-while-loop-8.webp\' alt="SQL Server WHILE LOOP"> <h2>Conclusion</h2> <p>The WHILE loop is a useful method when there is a need to execute a SQL script repeatedly. The article explained how to work with the WHILE loop in MS SQL Server to execute operations such as record insertion and pagination with a simple example. Here we have also learned the BREAK and CONTINUE statements to control the WHILE loop iteration.</p> <hr></=></pre></=></pre></10></pre></=>