有没有办法运行sqlcmd得到查询输出,而不显示受影响的行数?

我在SQL Server 2005中运行一个简单的查询,并希望它通过sqlcmd导出到一个文件。 我希望得到没有标题和查询元数据(有多less行受到影响)的CSV格式的结果。 对于标题,你实际上可以指定-h -1但是你怎样才能摆脱结束文本?

现在我有

sqlcmd -S klingon -d stardb -i C:\testscript.sql -o C:\testresults.csv -h -1 -s "," 

脚本是简单的调整

 select x, y, z from agent 

不幸的是,结果是这样的:

  24 aingles1 creablegs 25 tbails12 bull2dog12 26 jtaylor3 Leandon62606 27 forrestw1 nuke19211 (4 rows affected) 

我似乎无法find帮助文件中的任何内容,告诉我如何删除最后一部分告诉我有多less行受到影响。

想法任何人?

我想你可能想要“SET NOCOUNT ON”选项。 你的SQL脚本如下所示:

  set nocount on select x, y, z from agent set nocount off 

结果集将是:

  24 aingles1 creablegs 25 tbails12 bull2dog12 26 jtaylor3 Leandon62606 27 forrestw1 nuke19211 

减去最后一行的行数。

sqlcmd -S svr -d db … | findstr / v“受影响的行”

findstr被内置到操作系统中,并且与grep类似。 见findstr /? 为更多的select。

删除列:

http://unxutils.sourceforge.net/使用cut.exe你可以运行:

sqlcmd -S svr -d db … | 切-c10-

这只会从字符10开始输出,从而删除行号。 相应地调整数字10。 你也可以尝试字段:

sqlcmd -S svr -d db … | 切-f2-

这只会输出字段2和以后(向右)。

我将以下代码块添加到查询本身的开头,以便在使用sqlcmd.exe将结果导出到CSV时删除所有消息。

 -- Suppress warnings and messages like (2 rows effected) SET ANSI_WARNINGS OFF; SET NOCOUNT ON; -- SQLCMD.exe batch command :setvar SQLCMDERRORLEVEL 1 -- To Reenable --:setvar SQLCMDERRORLEVEL 0 /********************************************************************************** ** DISABLING WARNINGS AND MESSAGES ** Disable "Changed database context to 'DatabaseName'." message in the CSV file when using ** SQLCMD.exe. You'll get a syntax error when executing this query in Management ** Studio if SQLCMD Mode is not enabled [Query] --> [SQLCMD Mode]. ** :setvar SQLCMDERRORLEVEL 1 is used to disable messages like (152 Rows affected). **********************************************************************************/