83

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 sa and its password.

How would the bat file be?

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

0

6 Answers 6

84

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"
Sign up to request clarification or add additional context in comments.

Comments

71

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

1 Comment

providing a file name containing all my SQL queries is much more handy than providing the SQL query as command-line arguments.
41

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

1 Comment

I ran, sqlcmd -i filename.sql and it connected local sql server with integrated login and ran script... so looks like it has default values
3

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

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

Comments

2

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. Flags are case sensitive.

Comments

-3

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

1 Comment

Question are about Microsoft SQL Server, not MySQL. Check question tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.