使用批处理文件执行一组 SQL 查询?

2021-12-13 00:00:00 database batch-file cmd sql-server

我使用的是 SQL Server 数据库.我有这些 SQL 查询:

I am using a SQL Server database. I have these SQL queries:

Delete from TableA;
Delete from TableB;
Delete from TableC;
Delete from TableD;
Delete from TableE;

是否可以使用批处理文件运行这些脚本?数据库是远程数据库.

Is it possible to run these scripts using a batch file? The database is a remote database.

谢谢!

推荐答案

将命令保存在 .SQL 文件中,例如:ClearTables.sql,在您的 .SQL 文件中说代码>C: emp 文件夹.

Save the commands in a .SQL file, ex: ClearTables.sql, say in your C: emp folder.

内容 C:TempClearTables.sql

Delete from TableA;
Delete from TableB;
Delete from TableC;
Delete from TableD;
Delete from TableE;

然后使用sqlcmd执行如下.既然您说数据库是远程的,请使用以下语法(更新服务器和数据库实例名称后).

Then use sqlcmd to execute it as follows. Since you said the database is remote, use the following syntax (after updating for your server and database instance name).

sqlcmd -S <ComputerName><InstanceName> -i C:TempClearTables.sql

例如,如果您的远程计算机名称是 SQLSVRBOSTON1 并且数据库实例名称是 MyDB1,那么命令应该是.

For example, if your remote computer name is SQLSVRBOSTON1 and Database instance name is MyDB1, then the command would be.

sqlcmd -E -S SQLSVRBOSTON1MyDB1 -i C:TempClearTables.sql

另请注意,-E 指定默认身份验证.如果您有要连接的用户名和密码,请使用 -U-P 开关.

Also note that -E specifies default authentication. If you have a user name and password to connect, use -U and -P switches.

您将通过打开 CMD 命令窗口来执行所有这些操作.

You will execute all this by opening a CMD command window.

使用批处理文件.

如果要保存成批处理文件,双击运行,如下操作.

If you want to save it in a batch file and double-click to run it, do it as follows.

像这样创建并保存ClearTables.bat.

echo off
sqlcmd -E -S SQLSVRBOSTON1MyDB1 -i C:TempClearTables.sql
set /p delExit=Press the ENTER key to exit...:

然后双击它运行它.它将执行命令并等待您按某个键退出,以便您可以看到命令输出.

Then double-click it to run it. It will execute the commands and wait until you press a key to exit, so you can see the command output.

相关文章