|
Execute the following Microsoft SQL Server T-SQL training example script in Management Studio Query Editor to demonstrate the design of a WHILE loop.
-- T-SQL WHILE loop
SET nocount ON
USE Northwind;
-- T-SQL local variables
DECLARE @Customer NCHAR(5),
@Limit INT,
@RowNum INT
SET @Limit = 7
-- T-SQL TOP function
SELECT TOP 1 @Customer = CustomerID
FROM Northwind.dbo.Customers
SET @RowNum = 0
WHILE @RowNum < @Limit
BEGIN
------------------------------------------------------------------
-- ADD PROCESSING HERE
------------------------------------------------------------------
SET @RowNum = @RowNum + 1
PRINT Convert(VARCHAR,@RowNum) + ' ' + @Customer -- in messages
SELECT TOP 1 @Customer = CustomerID
FROM Northwind.dbo.Customers
WHERE CustomerId > @Customer
END -- while
GO
/* Messages
1 ALFKI
2 ANATR
3 ANTON
4 AROUT
5 BERGS
6 BLAUS
7 BLONP
*/
------------
Related link:
http://www.sqlusa.com/bestpractices/whilelooptablevariable/
|