Syntax of for-loop in SQL Server

前端 未结 9 1146
慢半拍i
慢半拍i 2020-11-28 02:36

What is the syntax of a for loop in TSQL?

9条回答
  •  死守一世寂寞
    2020-11-28 03:18

    For loop is not officially supported yet by SQL server. Already there is answer on achieving FOR Loop's different ways. I am detailing answer on ways to achieve different types of loops in SQL server.

    FOR Loop

    DECLARE @cnt INT = 0;
    
    WHILE @cnt < 10
    BEGIN
       PRINT 'Inside FOR LOOP';
       SET @cnt = @cnt + 1;
    END;
    
    PRINT 'Done FOR LOOP';
    

    If you know, you need to complete first iteration of loop anyway, then you can try DO..WHILE or REPEAT..UNTIL version of SQL server.

    DO..WHILE Loop

    DECLARE @X INT=1;
    
    WAY:  --> Here the  DO statement
    
      PRINT @X;
    
      SET @X += 1;
    
    IF @X<=10 GOTO WAY;
    

    REPEAT..UNTIL Loop

    DECLARE @X INT = 1;
    
    WAY:  -- Here the REPEAT statement
    
      PRINT @X;
    
      SET @X += 1;
    
    IFNOT(@X > 10) GOTO WAY;
    

    Reference

提交回复
热议问题