SQL and Batch File: (Microsoft SQL SERVER) by Souvik Ghosh (516964)
SQL and Batch File: (Microsoft SQL SERVER) by Souvik Ghosh (516964)
Problem Statement
As part of a development team, our daily work includes fixing bugs and adding new changes to SQL
scripts. We also need to check that code into our Version Control System (VCS). That means every time
another developer changes any script, we need to execute the same script on our database so that it is up-
to date.We need to do this at least every day, if not every couple of hours.
So once we have the latest script, we can use this cool trick to update multiple databases in one go. We
need two folders with scripts. For my illustration, I have two folders called:
1. Create Scripts
2. Change Scripts
@@echo off
del errors /f /s /q
rd Errors
md Errors
You would need to change the following as per your Database Name(s) and credentials in the above script:
Save this file with the Extension as .bat in one of your scripts folder.
Copy this batch file to the other script folder.
The Explanation
Here is an explanation of each section of the code.
del errors /f /s /q
When executing the scripts, we dump all errors to a folder called Errors. This needs to be cleaned up. This
will delete the contents of folder silently.
rd Errors
This will delete the folder Errors.
md Errors
This will create a new folder names Errors. I know it is redundant, but why not start with a clean slate.
FOR %%A IN (*.SQL) DO ( sqlcmd -S MANU -d DATABASE1 -U username -P password -i "%%A" -o
"Errors\%%AError_DB1.txt" -I )
Using a FOR loop we select each file name in sequential order as per the name of the file which ends
with .sql extension in the current folder and pass the file name to execute with Server Name, Username,
Password and the database name using SQLCMD.
%%A
here denotes the name of the current file name in the loop.
–o
outputs any errors/messages from the script to a file in the errors folder followed by the Database name.
Adding the database name can help you differentiate the error files when you add multiple FOR Loops for
multiple databases. You can have n number of loops to n number of databases as in the example.
Ready,Set and Run
Now all you have to do is double click the batch file in the respective folders to execute all the scripts.
On executing the batch file, a new folder called Errors will be created which generated output from each
script that was executed against the Server.
If you see there are 2 files for CreateScript – 1.sql. Each error file pertains to different database.
PROS:
It is really helpful when we need to run script to update multiple database tables. Especially
when the change is frequent.
CONS:
The only caveat with this method is if there are no errors, it will still create the Error File.