DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
 
 
SITE SEARCH SQLUSA.com VIDEOS
 
 
SQL E/BOOKS   WORLD, USA & SQL NEWS   FORMAT
SCRIPTS SQL 2005 SQL 2008 ARTICLES
How to architect WHILE loop using TOP?

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/

 

Exam Prep 70-461
SQL 2016 DESIGN & PROGRAMMING
 
 
 
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE