从命令行执行 SQL 脚本

我需要使用批处理文件修改数据库,举个简单的例子,删除一个表。我使用本地 SQLExpress (SQLServer2008R2)和用户 sa及其密码。

蝙蝠档案怎么样?

如何在脚本中指定密码以及在 SQLExpress 中使用的密码?

174593 次浏览

Take a look at the sqlcmd utility. It allows you to execute SQL from the command line.

http://msdn.microsoft.com/en-us/library/ms162773.aspx

It's all in there in the documentation, but the syntax should look something like this:

sqlcmd -U myLogin -P myPassword -S MyServerName -d MyDatabaseName
-Q "DROP TABLE MyTable"

You can do like this

sqlcmd -S <server Name> -U sa -P sapassword -i inputquery_file_name -o outputfile_name

From your command prompt run sqlcmd /? to get all the options you can use with sqlcmd utility

If you use Integrated Security, you might want to know that you simply need to use -E like this:

sqlcmd -S Serverinstance -E -i import_file.sql

Feedback Guys, first create database example live; before execute sql file below.

sqlcmd -U SA -P yourPassword -S YourHost -d live -i live.sql

First set the path of MYSQL in Environment variable-> System variables-> Click on Path-> Add -> "C:\Program Files\MySQL\MySQL Server 8.0\bin"

Open cmd-> navigate to the folder which has the sql script-> type as below -> mysql --user=root -p < employees.sql -> Enter the password which was set during MYSQL setup-> hit enter

Done.

CMD Screenshot after it worked form me

Firstly create an empty database in SQL server, then run this command.

sqlcmd -s ServerName -d CreatedDatabaseName -i ScriptFileName.sql

ScriptFileName should be with a complete path like "D:\Folder Name\ScriptFileName.sql".

You can also use -u and -p if you have userName and password in your sql server.