tsql while循环和时间问题

时间:2017-02-02 16:16:18

标签: sql sql-server tsql

我不知道我的查询有什么问题,但它没有突破while循环。我认为这是我计算时间但不确定的方式。

DECLARE @start DATETIME = GETDATE(), @currenttime INT = 0

while @currenttime <= 1 --- represent min
begin

    [execute Query]

    ' this will always return 0 and keep executing query even though the 1 min has been reached
    set @currenttime = CONVERT(INT, DATEDIFF(s, @start, GETDATE())%3600/60) 
end

3 个答案:

答案 0 :(得分:5)

另一种方法是改变while循环的条件:

public override void Init()
{
    base.Init();
    //EventHandlerTaskAsyncHelper Wraps the task call in an APM-style BeginEventHandler, EndEventHandler
    var wrapper = new EventHandlerTaskAsyncHelper(AsyncSessionStart);
    this.AddOnAcquireRequestStateAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler);
}

private async Task AsyncSessionStart(Object sender, EventArgs evtArgs)
{       
    //The only caveat is we have to check IsNewSession to see if it was created in this call
    //This doesn't need to be applied for other AddOn*Async wire-ups
    if (!Session.IsNewSession)
        return;

    await doSomethingAsync();
}

//I recall seeing something that for session state to be active, this callback has to be declared, even if empty
protected void Session_Start(object sender, EventArgs e)
{
    //Synchronous session
}

答案 1 :(得分:3)

而是尝试计算结束时间并循环直到达到

DECLARE @EndTime DATETIME
SET @EndTime = DATEADD(SECOND, 5, GETDATE())

WHILE GETDATE() < @EndTime
BEGIN

    PRINT CAST(DATEDIFF(SECOND, GETDATE(), @EndTime) AS VARCHAR(5)) + ' Seconds Remaining' 

END

答案 2 :(得分:0)

根据this answer对类似的问题,如果你想每秒运行一次脚本60秒,例如:

DECLARE @i INT = 1;

WHILE (@i <= 60)
 BEGIN
  WAITFOR DELAY '00:00:01'

       /*Your Script*/

 SET  @i = @i + 1;
END