windows 如何使用 BAT 文件运行脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3258975/
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
How do I run a script using a BAT file?
提问by l--''''''---------''''''''''''
I would like to have a BAT file open a sql server script. Currently I have this code in the sql file:
我想让一个 BAT 文件打开一个 sql server 脚本。目前我在 sql 文件中有这个代码:
declare @path varchar(255), @mydb varchar(50)
SELECT @mydb = 'timeclockplus'
select @path = 'C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Backup\'
+ @mydb + '-' + convert(varchar(8),getdate(),112) + '.bak'
BACKUP DATABASE @mydb TO DISK = @path
How do I open this SQL file from a BAT file?
如何从 BAT 文件打开此 SQL 文件?
I am currently trying to run it like this:
我目前正在尝试像这样运行它:
C:\Program Files\Microsoft SQL Server\Tools\Binn\osql -E
-S Sql server-hl7\timeclockplus timeclockplus.sql -oresults.txt
but OSQL does not exist in the BINN directory,
但是BINN目录下不存在OSQL,
回答by driis
You should invoke the sqlcmdcommand-line tool from your batch file. Assuming your sql file is "backup.sql", the command line would be something like:
您应该从批处理文件中调用sqlcmd命令行工具。假设您的 sql 文件是“backup.sql”,命令行将类似于:
sqlcmd -E -S yoursqlinstance -i backup.sql
-E
uses trusted connection, replace with -U
and -P
if you need to specify a SQL username and password. See also this article with examples.
-E
使用可信连接,如果需要指定 SQL 用户名和密码,请替换为-U
和-P
。另请参阅本文的示例。
回答by DaveShaw
sqlcmd -S 127.0.0.1 /E -i MySqlScript.sql
Replace /E with /U and /P if you don't have trusted connection
如果您没有受信任的连接,请将 /E 替换为 /U 和 /P
回答by djangofan
If you want a much better answer, here it is:
如果你想要一个更好的答案,这里是:
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
:: batch file for sql query
SET FIELDVAL=Empty
SET DBNAME=MYDB
SET SQLSTRING=SELECT column_name(s)^
FROM table_name1^
INNER JOIN table_name2^
ON table_name1.column_name=table_name2.column_name^
AND table_name2.field=%FIELDVAL%
ECHO !SQLSTRING!
ECHO.
sqlcmd.exe -b -S localhost -E -d !DBNAME! -Q "!SQLSTRING!" -W
ECHO Query is done. Hit any key to close this window....
pause>nul
回答by ajdams
Start > Run > Type Cmd.
开始 > 运行 > 键入 Cmd。
MyDrive:\Mypath\Mybat.bat
MyDrive:\Mypath\Mybat.bat
=)
=)