且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用sqlcmd运行sql脚本文件并将其输出到shell和文件

更新时间:2023-01-23 10:11:28

@Noam

在UNIX世界中,有一个标准程序可以从 stdin 读取并写入 stdout 到指定文件: tee 命令.下面的示例将当前目录列出到 stdout 和"myfile":

There's a standard program in UNIX world that reads from stdin and writes to stdout and to a specified file: the tee command. The following example lists the current directory to stdout and to "myfile":

$ ls | tee "myfile"

有一些用于Windows的开源端口,例如 wintee ,甚至轻松实现自己的实现(请参见此处),但PowerShell实际上已经内置了此实用程序: Tee -Object .下面的示例类似于上一个在PowerShell中的示例:

There are some open-source ports for windows, like wintee, and it's even trivial to make your own implementation (see here), but PowerShell actually has already this utility built-in: the Tee-Object.The following example is analogous the previous, in PowerShell:

PS [c:\tmp]
> dir | tee myDirContents.txt

因此,以下命令将使用当前的Windows凭据将 myscript.sql 执行到 myserver 中,并且其结果将输出到控制台改为"result.txt":

Hence, the following command will execute myscript.sql into myserver, using current windows credentials and its result will be output either to the console and to "result.txt":

PS [c:\tmp]
> sqlcmd -i mysrcipt.sql -S myserver -E | tee "result.txt"