我想在 SQL Server 2005 中使用无限 WHILE
循环,并使用 BREAK
关键字在特定条件下退出。
while true
不起作用,所以我必须使用 while 1=1
。
有没有更好的方法来组织无限循环?
我知道我可以使用goto
,但是while 1=1 begin ... end
在结构上看起来更好。
最佳答案
除了其他答案所建议的 WHILE 1 = 1
之外,我还经常向 SQL“infintie”循环添加“超时”,如下例所示:
DECLARE @startTime datetime2(0) = GETDATE();
-- This will loop until BREAK is called, or until a timeout of 45 seconds.
WHILE (GETDATE() < DATEADD(SECOND, 45, @startTime))
BEGIN
-- Logic goes here: The loop can be broken with the BREAK command.
-- Throttle the loop for 2 seconds.
WAITFOR DELAY '00:00:02';
END
我发现上述技术在从 long polling AJAX 调用的存储过程中很有用。后端。在数据库端使用循环可以使应用程序不必不断访问数据库来检查新数据。
关于sql - 如何在 SQL Server 中组织无限 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2456330/