Results 1 to 3 of 3

Thread: For loop in sql

  1. #1
    Join Date
    Aug 2009
    Posts
    37

    Unanswered: For loop in sql

    Hi

    can i write a for loop in sql 2005.

    just give me syntax and example

    thanks

  2. #2
    Join Date
    Oct 2009
    Posts
    19
    Yes you can, it's called a cursor (cursors can be slow)
    Example:
    DECLARE MyCursor CURSOR
    FOR SELECT * FROM MyTable
    OPEN MyCursor
    FETCH NEXT FROM MyCursor
    For more information
    -----------------------------------
    Free SQL server monitoring for DBA's
    SQL DBA manager by BlueThames.com

  3. #3
    Join Date
    Jan 2007
    Location
    UK
    Posts
    11,434
    Provided Answers: 10
    You can also use WHILE loops:
    Code:
    DECLARE @i int
        SET @i = 1
    
    PRINT '---Regular loop---'
    
    WHILE (@i <= 10)
      BEGIN
        PRINT @i
        SET @i = @i + 1
      END
    
    PRINT '---alternative style---'
    
    WHILE (1=1)
      BEGIN
        PRINT @i
        SET @i = @i + 1
        IF @i > 20 BREAK
      END
    
    PRINT '---Loop table---'
    
    WHILE (1=1)
      BEGIN
        PRINT @i
        SET @i = (SELECT Min(number) FROM master..spt_values WHERE number > @i)
        IF @i > 30 BREAK
      END
    George
    Home | Blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •