等待延迟并打印声明

问题描述 投票:0回答:4

我有一个简单的 while 循环:

DECLARE @Counter INT 

SET @Counter = 1

WHILE (@Counter <= 10)

BEGIN

    PRINT 'The counter value is = ' + CONVERT(VARCHAR,@Counter) WAITFOR DELAY '00:00:01'
    SET @Counter  = @Counter  + 1
    
END

我期望 @counter 值会延迟 1 秒打印出来,但相反,代码在 10 秒后执行,并在执行结束时一次性打印结果。

The counter value is = 1
The counter value is = 2
The counter value is = 3
The counter value is = 4
The counter value is = 5
The counter value is = 6
The counter value is = 7
The counter value is = 8
The counter value is = 9
The counter value is = 10

如何确保每个下一个值都以 1 秒的延迟打印出来,以便我可以监控进度?

只是一些背景。我想使用类似的脚本来监控备份和恢复进度。 例如。将进度百分比的初始值分配给:

SELECT @Counter = percent_complete
FROM sys.dm_exec_requests r 
   CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a 
WHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE');

并每 5 秒监控一次 while 循环的进度,直到percent_complete 达到 100%。

sql-server while-loop sleep
4个回答
1
投票

除了评论中已有的建议之外,请尝试使用此修改后的脚本来演示如何使用 raiserror 来实现您在示例代码中期望的行为。

记住选择Messages表来查看输出。

declare @Counter Int = 1;

while (@Counter <= 10)
begin
  raiserror ('The counter value is %d', 0, 1, @Counter) with nowait;
  waitfor delay '00:00:01';
  set @Counter += 1;
end;

0
投票

你说

我想使用类似的脚本来监控备份和恢复进度

根本不要使用这个循环。只需使用

STATS
选项,您可以在其中指定百分比变化来显示更新。这是所有备份工具用来监控进度的方法。

BACKUP DATABASE
......
WITH STATS = 1;

0
投票

如何使用 sqlcmd 在批处理文件中显示进度?中提到了一个解决方案。其他解决方案是使用 Powershell。

GO
CREATE PROCEDURE [scutility].[SqlCmdTestOutput]
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @count INT = 50
    DECLARE @msg VARCHAR(8000)

    WHILE @count > 0
    BEGIN
        SET @msg = convert(VARCHAR(50), sysdatetime())

        RAISERROR (@msg,0,1) WITH NOWAIT

        WAITFOR DELAY '00:00:10'

        SET @count -= 1
    END
END

要调用此过程,请使用 Invoke-Sqlcmd。

powershell.exe  -command "Invoke-Sqlcmd -ServerInstance '.' -Query '[scutility].[SqlCmdTestOutput]' -Database SCUTILITY -Verbose -QueryTimeout 0"

更多详细信息请参见 - https://dba.stackexchange.com/questions/222054/how-to-report-stats-on-restore-via-sqlcmd


0
投票

声明@Counter INT

设置@计数器=1

同时(@Counter <= 100)

开始


-----在此插入流程

raiseerror('计数器值为 %d', 0, 1, @Counter) with nowait;

等待延迟'00:00:01';

设置@Counter = @Counter + 1

结束

© www.soinside.com 2019 - 2024. All rights reserved.