In the realm of database management, particularly within the Microsoft SQL Server ecosystem, loops are indispensable tools for processing a large set of records or iterating over a series of actions. A loop in T-SQL, Microsoft's version of SQL, allows you to repeat a block of code until a specified condition is met. Let's delve into MS SQL for loop examples, exploring its functionalities and use-cases.

MS SQL provides two types of loops: WHILE and Cursor. The WHILE loop repeats a block of code while a specified condition is true, while a Cursor allows you to traverse a set of records row by row. Let's explore these in detail.

WHILE Loop in MS SQL
The WHILE loop in MS SQL is useful when you need to perform an operation until a certain condition is met. It's perfect for iterative processes like updating records or manipulating data until a specific condition is fulfilled.

Here's a simple example, where we increment a counter and display its value until it reaches a specified limit:
```sql DECLARE @counter INT; SET @counter = 0; WHILE (@counter < 5) BEGIN SELECT @counter AS 'Counter Value'; SET @counter = @counter + 1; END; ```
Example of WHILE Loop with DB Records

Let's upgrade our previous example by fetching data from a table and operating on it until a condition is met. Suppose we want to increase each record's 'Price' column by 10% until the price exceeds 100.
```sql DECLARE @currentPrice MONEY; UPDATE Products SET @currentPrice = Price FROM Products WHERE Price < 100; WHILE @currentPrice < 100 BEGIN UPDATE Products SET Price = @currentPrice * 1.1 WHERE Price = @currentPrice; SELECT @currentPrice = (SELECT TOP 1 Price FROM Products WHERE Price < 100); END; ```
In this script, we gradually increase the prices of products in the 'Products' table until all of them are above 100.
Using WHILE Loop with Error Handling

In complex scenarios, it's crucial to handle potential errors within your loop. Here's an example where we attempt to divide two variables and handle the ensuing error:
```sql DECLARE @dividend INT; SET @dividend = 10; DECLARE @divisor INT; SET @divisor = 0; WHILE @divisor = 0 BEGIN TRY SELECT @dividend / @divisor; CATCH SELECT 'Error: Division by zero' AS ErrorMessage; END TRY; SET @divisor = @divisor + 1; END; ```
Cursor Loop in MS SQL
A Cursor in MS SQL is a database object that enables you to iterate through a set of rows. It's like a pointer that moves from one record to another within a query result set.

Here's an example where we retrieve and display all records from a table:
```sql DECLARE @id INT; DECLARE @name VARCHAR(50); DECLARE cursor_products CURSOR FOR SELECT Id, Name FROM Products; OPEN cursor_products; FETCH NEXT FROM cursor_products INTO @id, @name; WHILE @@FETCH_STATUS = 0 BEGIN SELECT @id AS 'Product ID', @name AS 'Product Name'; FETCH NEXT FROM cursor_products INTO @id, @name; END; CLOSE cursor_products; DEALLOCATE cursor_products; ```
Example of Cursor Loop with Row-by-Row Processing



















Here's a scenario where we calculate and store the total weight of all 'Products' in our 'Orders' table using a cursor:
```sql DECLARE @order_id INT; DECLARE @order_total_weight FLOAT; DECLARE cursor_orders CURSOR FOR SELECT OrderId, SUM(Quantity * Weight) AS TotalWeight FROM OrderItems GROUP BY OrderId; OPEN cursor_orders; FETCH NEXT FROM cursor_orders INTO @order_id, @order_total_weight; WHILE @@FETCH_STATUS = 0 BEGIN UPDATE Orders SET TotalWeight = @order_total_weight WHERE OrderId = @order_id; FETCH NEXT FROM cursor_orders INTO @order_id, @order_total_weight; END; CLOSE cursor_orders; DEALLOCATE cursor_orders; ```
In conclusion, MS SQL for loops, particularly the WHILE and Cursor loops, are invaluable tools for performing iterative processes and traversing datasets. They open up a plethora of possibilities for data manipulation and analysis, making them essential to any MS SQL developer's toolkit. As you've seen, with the right looping strategy, you can handle complex operations and extract meaningful insights from your data seamlessly. Happy coding!