从命令行执行 SQL 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6737064/
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 11:21:56  来源:igfitidea点击:

Execute SQL script from command line

sqlsql-serverbatch-filecommand-linescripting

提问by blur

I need to alter a database using a batch file, for a simple example, drop a table. I′m using local SQL Express (SQL Server 2008 R2) with user saand its password.

我需要使用批处理文件更改数据库,举个简单的例子,删除一个表。我正在使用带有用户sa及其密码的本地 SQL Express (SQL Server 2008 R2) 。

How would the bat file be?

bat文件会怎样?

How can I specify in the script the password and that I use in SQL Express?

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

回答by rsbarro

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

看看sqlcmd实用程序。它允许您从命令行执行 SQL。

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

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"

回答by Rahul

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 sqlcmdutility

从您的命令提示符运行sqlcmd /?以获取您可以与sqlcmd实用程序一起使用的所有选项

回答by Maxime

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

如果您使用Integrated Security,您可能想知道您只需要-E像这样使用:

sqlcmd -S Serverinstance -E -i import_file.sql

回答by Naelson Gon?alves Saraiva

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

反馈伙计们,首先创建数据库示例直播;在执行下面的sql文件之前。

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