Skip to content

Instantly share code, notes, and snippets.

@mcnemesis
Created August 5, 2016 06:20
Show Gist options
  • Save mcnemesis/6326eec9c4b61bf007b5be46674e37be to your computer and use it in GitHub Desktop.
Save mcnemesis/6326eec9c4b61bf007b5be46674e37be to your computer and use it in GitHub Desktop.
Using Windows Batch Scripting, and the SQLCMD utility, this little script will run, recursively, all the MS SQL scripts under a given directory... with options for setting DB access parameters and more.
@ECHO OFF
ECHO ***********************
ECHO Remember Batch sCripts?
ECHO Good ol days... but, right now, we got work to do ;-)
ECHO ***********************
ECHO SCRIPT: run_all_sql_in_dir.bat
ECHO SYNTAX: run_all_sql_in_dir [DIR] [HOST] [SERVER] [DBNAME] [USER] [PASSWORD]
ECHO Purpose: should be obvious by now... checks the DIR, and using the connection params, executes all SQL scripts found in that dir, against the specified DB
ECHO Uses some convinient defaults... check the source-code of this script!
ECHO ++++++++++++++++++++++++++++++++++++++++++++++
ECHO Rock-N-Roll time... tnx to NX@2016...
ECHO **********************************************
REM by default, we use the current working directory as the path where the SQL scripts are searched for
SET ROOT_DIR=%CD%
SET HOST=localhost
SET SERVERNAME=MACHINE\INSTANCE_NAME
SET DBNAME=THE_GLORIOUS_DB
SET USER=DBA
SET PASSWORD=Kr@ZYPASS?
REM if params were passed, use those...
IF defined %1 SET ROOT_DIR=%1
IF defined %1 SET HOST=%2
IF defined %2 SET SERVERNAME=%3
IF defined %1 SET DBNAME=%4
IF defined %2 SET USER=%5
IF defined %2 SET PASSWORD=%6
ECHO Processing all SQL scripts under the path: %ROOT_DIR%
ECHO Using the SERVER/DB : %SERVERNAME%/%DBNAME%
REM okay, we obtain the entire list of sql scripts (*.sql) in current dir
REM and execute them against the specified server and db..
ECHO Running the scripts...
FOR /R "%ROOT_DIR%" %%F in (*.sql) do (
echo "Processing SCRIPT: %%F"
sqlcmd -S %SERVERNAME% -d %DBNAME% -U %USER% -P %PASSWORD% -H %HOST% -i "%%F"
)
ECHO JOB COMPLETED.
ECHO Perhaps, you can now go let laid... hehehe.
PAUSE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment