Execute SQL script from command line

blur picture blur · Jul 18, 2011 · Viewed 130.6k times · Source

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?

Answer

rsbarro picture rsbarro · Jul 18, 2011

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"