alp*_*pav 17 sql sql-server loops boolean sql-server-2005
我想WHILE
在SQL Server 2005中使用无限循环,并BREAK
在某些条件下使用关键字退出.
while true
不起作用,所以我必须使用while 1=1
.有没有更好的方法来组织无限循环?
我知道我可以使用goto
,但在while 1=1 begin ... end
结构上看起来更好.
Dan*_*llo 25
除了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
Run Code Online (Sandbox Code Playgroud)
我发现上述技术在从长轮询AJAX后端调用的存储过程中很有用.在数据库端进行循环可以使应用程序不必经常访问数据库以检查新数据.