Syntax of for-loop in SQL Server

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

What is the syntax of a for loop in TSQL?

相关标签:
9条回答
  • 2020-11-28 03:15

    How about this:

    BEGIN
       Do Something
    END
    GO 10
    

    ... of course you could put an incremental counter inside it if you need to count.

    0 讨论(0)
  • 2020-11-28 03:15

    Try it, learn it:

    DECLARE @r INT = 5
    DECLARE @i INT = 0
    DECLARE @F varchar(max) = ''
    WHILE @i < @r
    BEGIN
    
        DECLARE @j INT = 0
        DECLARE @o varchar(max) = ''
        WHILE @j < @r - @i - 1
        BEGIN
            SET @o = @o + ' '
            SET @j += 1
        END
    
        DECLARE @k INT = 0
        WHILE @k < @i + 1
        BEGIN
            SET @o = @o + ' *'  -- '*'
            SET @k += 1
        END
        SET @i += 1
        SET @F = @F + @o + CHAR(13)
    END
    PRINT @F
    

    With date:

    DECLARE @d DATE = '2019-11-01'
    WHILE @d < GETDATE()
    BEGIN
        PRINT @d
        SET @d = DATEADD(DAY,1,@d)
    END
    PRINT 'n'
    PRINT @d
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题