SQL 带有输出文件和屏幕输出的 sqlcmd

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9319025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:26:12  来源:igfitidea点击:

sqlcmd with output file and screen output

sqlsql-server-2005command-linesqlcmd

提问by Leandro

I do some command line batch (.bat) with sqlcmd as this way:

我以这种方式使用 sqlcmd 执行一些命令行批处理 (.bat):

sqlcmd -i Scripts\STEP01.sql -o PROCESS.log -S MYSERVER -E -d MYDATABASE

and i need an output file (it's works currently) and also the output trought the screen to do something like:

我需要一个输出文件(它目前可以工作),并且输出通过屏幕执行以下操作:

@echo off
echo The result of the query was:
    sqlcmd -i Scripts\STEP01.sql -o PROCESS.log -S MYSERVER -E -d MYDATABASE
pause
CHOICE /C:YN /M "Is the result accord?"
IF ERRORLEVEL 2 GOTO ENDWITHERROR
IF ERRORLEVEL 1 GOTO STEP2

Note:

注意

  • Yes, the script works suscefull, it's not an issue question.
  • And yes, I've a "print "something" on my sql. The log file gets the output.
  • 是的,脚本可以正常工作,这不是问题。
  • 是的,我在我的 sql 上有一个“打印“东西”。日志文件获取输出。

Thanks a lot!

非常感谢!

Similar question without answer: How to run a sql script file using sqlcmd and output to both shell and file

没有答案的类似问题: How to run a sql script file using sqlcmd and output to both shell and file

采纳答案by Gerardo Lima

I also couldn't find a better way then @Sparky proposed. The following code adds his suggestion:

我也找不到比@Sparky 提出的更好的方法。以下代码添加了他的建议:

@echo off

:: this will execute the script into PROCESS.log
sqlcmd -i Scripts\STEP01.sql -o PROCESS.log -S MYSERVER -E -d MYDATABASE

:: this present the contents of PROCESS.log to the screen
echo The result of the query was:
type PROCESS.log

pause
CHOICE /C:YN /M "Is the result accord?"
IF ERRORLEVEL 2 GOTO ENDWITHERROR
IF ERRORLEVEL 1 GOTO STEP2

回答by jgerstle

If you want you can use powershell instead and use the following:

如果需要,您可以改用 powershell 并使用以下命令:

sqlcmd -i Scripts\STEP01.sql  -S SERVER -E -d MYDB | Tee-Object -file "PROCESS.log"

More info from Microsoft

来自微软的更多信息