Syntax of for-loop in SQL Server

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

What is the syntax of a for loop in TSQL?

相关标签:
9条回答
  • 2020-11-28 02:58

    Extra Info

    Just to add as no-one has posted an answer that includes how to actually iterate though a dataset inside a loop, you can use the keywords OFFSET FETCH.

    Usage

    DECLARE @i INT = 0;
    SELECT @count=  Count(*) FROM {TABLE}
    
    WHILE @i <= @count
    BEGIN
    
        SELECT * FROM {TABLE}
        ORDER BY {COLUMN}
        OFFSET @i ROWS   
        FETCH NEXT 1 ROWS ONLY  
    
        SET @i = @i + 1;
    
    END
    
    0 讨论(0)
  • 2020-11-28 03:05

    T-SQL doesn't have a FOR loop, it has a WHILE loop
    WHILE (Transact-SQL)

    WHILE Boolean_expression
    BEGIN
    
    END
    
    0 讨论(0)
  • 2020-11-28 03:05

    While Loop example in T-SQL which list current month's beginning to end date.

    DECLARE @Today DATE= GETDATE() ,
    @StartOfMonth DATE ,
    @EndOfMonth DATE;
    
    DECLARE @DateList TABLE ( DateLabel VARCHAR(10) );
    SET @EndOfMonth = EOMONTH(GETDATE());
    SET @StartOfMonth = DATEFROMPARTS(YEAR(@Today), MONTH(@Today), 1);
    
    WHILE @StartOfMonth <= @EndOfMonth
    BEGIN
        INSERT  INTO @DateList
        VALUES  ( @StartOfMonth );
        SET @StartOfMonth = DATEADD(DAY, 1, @StartOfMonth);
    END;
    
    SELECT  DateLabel
    FROM    @DateList;  
    
    0 讨论(0)
  • 2020-11-28 03:08

    There is no for-loop, only the while-loop:

    DECLARE @i int = 0
    
    WHILE @i < 20
    BEGIN
        SET @i = @i + 1
        /* do some work */
    END
    
    0 讨论(0)
  • 2020-11-28 03:08

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5) 
    BEGIN
        PRINT @intFlag
        SET @intFlag = @intFlag + 1
    END
    GO
    
    0 讨论(0)
  • 2020-11-28 03:13

    Simple answer is NO !!.

    There is no FOR in SQL, But you can use WHILE or GOTO to achieve the way how the FOR will work.

    WHILE :

    DECLARE @a INT = 10
    
    WHILE @a <= 20
    BEGIN
        PRINT @a
        SET @a = @a + 1
    END
    

    GOTO :

    DECLARE @a INT = 10
    a:
    PRINT @a
    SET @a = @a + 1
    IF @a < = 20
    BEGIN
        GOTO a
    END
    

    I always prefer WHILE over GOTO statement.

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