我有一个简单的 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%。
除了评论中已有的建议之外,请尝试使用此修改后的脚本来演示如何使用 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;
如何使用 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
声明@Counter INT
设置@计数器=1
同时(@Counter <= 100)
开始
raiseerror('计数器值为 %d', 0, 1, @Counter) with nowait;
等待延迟'00:00:01';
设置@Counter = @Counter + 1
结束