'Execute SQL script from command line
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?
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[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
Solution 4:[4]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rahul |
| Solution 2 | |
| Solution 3 | Pradeep |
| Solution 4 | Mateen |
