在 SQL Server 2008 中执行 while 循环

Do while loop in SQL Server 2008(在 SQL Server 2008 中执行 while 循环)

本文介绍了在 SQL Server 2008 中执行 while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SQL server 2008有没有实现do while循环的方法?

解决方案

我不确定 MS SQL Server 2008 中的 DO-WHILE,但您可以更改 WHILE 循环逻辑,以便像 DO-WHILE 循环一样使用.

示例取自此处:http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/

<块引用>

  1. WHILE 循环示例

    DECLARE @intFlag INT设置@intFlag = 1同时 (@intFlag <=5)开始打印@intFlagSET @intFlag = @intFlag + 1结尾走

    结果集:

    12345

  2. 带有 BREAK 关键字的 WHILE 循环示例

    DECLARE @intFlag INT设置@intFlag = 1同时 (@intFlag <=5)开始打印@intFlagSET @intFlag = @intFlag + 1如果@intFlag = 4休息;结尾走

    结果集:

    123

  3. 带有 CONTINUE 和 BREAK 关键字的 WHILE 循环示例

    DECLARE @intFlag INT设置@intFlag = 1同时 (@intFlag <=5)开始打印@intFlagSET @intFlag = @intFlag + 1继续;IF @intFlag = 4 -- 这将永远不会执行休息;结尾走

    结果集:

    12345

但是尽量在数据库级别避免循环.参考.

Is there any method for implement do while loop in SQL server 2008?

解决方案

I am not sure about DO-WHILE IN MS SQL Server 2008 but you can change your WHILE loop logic, so as to USE like DO-WHILE loop.

Examples are taken from here: http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/

  1. Example of WHILE Loop

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
        PRINT @intFlag
        SET @intFlag = @intFlag + 1
    END
    GO
    

    ResultSet:

    1
    2
    3
    4
    5
    

  2. Example of WHILE Loop with BREAK keyword

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
        PRINT @intFlag
        SET @intFlag = @intFlag + 1
        IF @intFlag = 4
            BREAK;
    END
    GO
    

    ResultSet:

    1
    2
    3
    

  3. Example of WHILE Loop with CONTINUE and BREAK keywords

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
        PRINT @intFlag
        SET @intFlag = @intFlag + 1
        CONTINUE;
        IF @intFlag = 4 -- This will never executed
            BREAK;
    END
    GO
    

    ResultSet:

    1
    2
    3
    4
    5
    

But try to avoid loops at database level. Reference.

这篇关于在 SQL Server 2008 中执行 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 SQL Server 2008 中执行 while 循环

基础教程推荐