Just Code‎ > ‎

SQLCMD - TSQL script to run all .sql scripts in a folder

posted Jan 9, 2014, 1:03 AM by Peter Henell   [ updated Jan 9, 2014, 1:09 AM ]
SQLCMD is a command line tool to run sql scripts. See SQLCMD @ Technet Microsoft

In the documentation of Sqlcmd it mentions: 
  • To increase performance, do as much in one sqlcmd session as you can, instead of in a series of sessions.

This script will run all scripts within a folder in a single sqlcmd session.
Copy the following code into a new file called main.sql.


:!! if exist files.sql del files.sql
:!! for %f in (*.sql) do @(if not %f==main.sql echo :r %f &echo.GO)>> files.sql
:r files.sql

:!! del files.sql

Then execute the script using sqlcmd: (This will connect to your local machine, using AdvetureWorks as the initial database, using integrated security)
sqlcmd -E -d AdventureWorks -i main.sql

To execute against a remote server:
sqlcmd -E -S REMOTESERVERNAME -d AdventureWorks -i main.sql