我可以为循环中的每次迭代立即打印吗? [英] Can I print immediately for each iteration in a loop?

查看:25
本文介绍了我可以为循环中的每次迭代立即打印吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的部署服务器为每个新的数据库构建运行一个部署脚本.

My deployment server runs a deployment script for every new database build.

部分脚本阻塞等待另一个异步操作完成.

Part of the script blocks to wait for another asynchronous operation to complete.

阻塞代码如下所示:

DECLARE @i INT = 0;
DECLARE @laststatus NVARCHAR(MAX) = N'';

WHILE @i < 5
BEGIN
  -- the real delay is longer
  WAITFOR DELAY '00:00:01';

  -- poll async operation status here
  SET @i = @i + 1;

  SET @laststatus = N'status is ' + CAST(@i AS NVARCHAR(MAX));
  RAISERROR(@laststatus, 0, 1) WITH NOWAIT;
END;

它使用 RAISERRORWITH NOWAIT 子句而不是 PRINT 因为它应该为每次迭代打印状态更新.

It uses the WITH NOWAIT clause of RAISERROR instead of PRINT because it's supposed to print a status update for every iteration.

部署服务器使用以下命令在 sqlcmd 中运行脚本:

The deployment server runs the script in sqlcmd with this command:

sqlcmd.exe -i print_test.sql

输出是这样的:

状态为1
状态为 2
状态为 3
状态为 4
状态为 5

status is 1
status is 2
status is 3
status is 4
status is 5

它应该在一秒钟后打印:

It should print this after one second:

状态为 1

再过一秒它应该打印这个

After another second it should print this

状态为 2

等等.

有没有办法在 sqlcmd 中做到这一点?

Is there a way to do this in sqlcmd?

推荐答案

您可以使用 osql 代替.它已被弃用,但它按您的预期工作.

You can use osql instead. It's deprecated, but it works as you expect.

等价的命令是:

osql -E -n -i print_test.sql

osql 默认需要用户名和密码.使用 -E 开关来使用 Windows 身份验证.这与 sqlcmd 默认行为相反.

osql by default expects a username and password. Use the -E switch to use Windows authentication. This is the opposite of sqlcmd default behavior.

osql 默认为输入文件脚本中的每一行打印一个数字.

osql by default prints a number for every line in the input file script.

1>2>3>4>5>6>7>8>9>10>11>12>13>14>15>

1> 2> 3> 4> 5> 6> 7> 8> 9> 10> 11> 12> 13> 14> 15>

使用 -n 开关抑制行号.

Use the -n switch to suppress the line numbers.

sqlcmd 没有 -n 开关.设置 -i 开关时,它只是不打印行号.

sqlcmd has no -n switch. It just doesn't print line numbers when the -i switch is set.

Martin Smith 通过引用 Microsoft Connect 项目 关于此问题.

Martin Smith led me to the workaround by quoting the Microsoft Connect item about this issue.

如果您的脚本使用 RAISERROR WITH NOWAIT,则输出仍会被缓冲.这适用于 OSQL 和来自 SQL 2008 的 SQLCMD.

If you a script which uses RAISERROR WITH NOWAIT, the output is nevertheless buffered. This works correctly with OSQL and SQLCMD from SQL 2008.

这篇关于我可以为循环中的每次迭代立即打印吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆