我有简单的查询
WHILE ( @counter < 50 )
BEGIN
BEGIN TRANSACTION
PRINT 'Counter = ' + CONVERT(VARCHAR(4), @counter);
WITH CTE
AS (
SELECT TOP 50000 * FROM MyTable
)
DELETE FROM CTE OPTION ( MAXDOP 1 )
SET @counter += 1
COMMIT TRAN
END
当我查看消息时,该PRINT
命令不会在每个循环中都返回行,而是显示为多行。我已经添加了一行,现在它一次显示了 1 行,整个过程要快得多。
WHILE ( @counter < 50 )
BEGIN
WAITFOR DELAY '00:00:00.5' --< This line
BEGIN TRANSACTION
PRINT 'Counter = ' + CONVERT(VARCHAR(4), @counter);
WITH CTE
AS (
SELECT TOP 50000 * FROM MyTable
)
DELETE FROM CTE OPTION ( MAXDOP 1 )
SET @counter += 1
COMMIT TRAN
END
那么为什么当我为每个循环迭代添加 0.5 秒的等待时间时,它实际上运行得更快,并允许打印消息同时出现?
PRINT
输出被缓冲。如果您替换PRINT ...
为,RAISERROR ... WITH NOWAIT
您将看到结果。