SQL 中的这个嵌套 WHILE 循环有什么问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2020602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:59:47  来源:igfitidea点击:

What is wrong with this nested WHILE loop in SQL

sqltsql

提问by edosoft

I ran into a weird situation today doing some one-time sql code. This nested loop doesn't seem to run the outer loop: it prints (0,0),(0,1),(0,2) and (0,3)

我今天在做一些一次性 sql 代码时遇到了一种奇怪的情况。这个嵌套循环似乎没有运行外循环:它打印 (0,0)、(0,1)、(0,2) 和 (0,3)

declare @i int, @j int
select @i = 0, @j = 0
while @i < 3 begin
    while @j < 3 begin
        select @i as i, @j as j
        set @j = @j + 1
    end
    set @i = @i + 1
end

Am I missing something blatantly obvious?

我是否遗漏了一些显而易见的东西?

回答by almog.ori

You are not resetting your j var for the next iteration

您不会为下一次迭代重置 j var

 set @i = @i + 1
 set @j = 0

回答by ozczecho

You are not resetting @j.

您没有重置@j。

回答by Chjquest

declare @i int, @j int
select @i = 0, @j = 0 --<- Wrong place set @j
while @i < 3 
begin
    select @i, @j --<-test print, then you will know what happened~
    --set @j = 0 --<- Right place to set @j
    while @j < 3 
    begin
        select @i as i, @j as j
        set @j = @j + 1
    end
    set @i = @i + 1
end

The original result is 0/0 0/0 0/1 0/2 1/3 2/3

原来的结果是 0/0 0/0 0/1 0/2 1/3 2/3

Well, the above answered, just add code for more detail, lol~

嗯,上面已经回答了,添加代码更详细,lol~