How to Run SQL Script From a Microsoft SQL Server Express

By Kevin Lee

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.

Things You'll Need

  • SQL Server Express


Step 1

Type CMD in the windows \"Start Menu\" and press \"Enter\". The command prompt window will open.

Step 2

Type one of the following commands to connect to the database:Sqlcmd -u username -p passwordSqlcmd -S computerName\\instanceNameUse 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.

Step 3

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. .

Step 4

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.

Step 5

Type Sqlcmd exit. SQL Server Express will terminate the session.

Tips & Warnings

  • 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.