SQL Server Express is a free version of SQL Server that you can use to create desktop and Web-based database applications. Developers manage SQL Server Express by using SQL Server Management Studio. They also use a small command-line utility called "Sqlcmd". Sqlcmd enables you to execute Transactional SQL commands, run stored procedures and execute SQL scripts. If you simply want to run a SQL script, sometimes it's easier to do that by using Sqlcmd. You get to Sqlcmd by opening up a new command prompt window.
Type CMD in the windows "Start Menu" and press "Enter". The command prompt window will open.
Type one of the following commands to connect to the database:
Sqlcmd -u username -p password
Sqlcmd -S computerName\instanceName
Use the first command if you setup a username and password when you installed SQL Server Express. Replace "username" and "password" with the actual username and password that you setup. Use the second command if you created a "named instance" during installation. Replace "computerName" with the name of your computer and "instanceName" with the name of the SQL instance that you created during installation.
Type the following command and press "ENTER":
Sqlcmd -i C:\mySqlScript.sql.
SQL Server Express will execute the script named "mySqlScript.sql". Replace that "mySqlScript.sql" with the name of the script that you want to run. Include the full path designation. If the SQL script returns data from the database, SQL Server Express will display the results in the command prompt window. .
Type Sqlcmd -i C:\nameOfScript -o C:\outputFile.txt and press ENTER to rerun the script. This will route the results to a text file named "C:\outputFile.txt". You can name this file anything. Saving to a text file comes in handy when you need to capture and save query results.
Type Sqlcmd exit. SQL Server Express will terminate the session.
If you run SQL scripts frequently, you can create batch (.bat) files that can speed up the process (see Resources). For example, you could place the commands shown above in a batch file and save it on your desktop. You could later run it by double-clicking the file.