Syntax of for-loop in SQL Server

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

What is the syntax of a for loop in TSQL?

9条回答
  •  醉话见心
    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.

提交回复
热议问题