Say, you are given a large number of scripts underneath the following directory tree:
N:\Apps\Release\PRS\PR12345\CMP1\procs
\views
\triggers
\CMP2\procs
\views
\scripts
You need to execute these scripts on a SQL Server instance. To simplify the matter a bit, let’s assume that these scripts can be executed in any order. How would you go about it?
Here’s how I would do it with the following trivial throw-away Perl script:
# script file name: release.pl
$path = 'N:\Apps\Release\PRS\PR12345';
$server = 'SQLNYC01';
@scripts = `dir /B /s $path`;
foreach $f (@scripts) {
if ($f =~ /^(.+\.sql)\s*$/i) {
$osql = "sqlcmd.exe -S$server -E -w250 -i" . $f;
print "$osql \n";
# $log = `$osql`;
}
}
I then run this little script and re-direct the result to a file:
cmd>perl release.pl > PR12345.bat
PR12345.bat is the batch file that you can run to execute all the SQL scripts. Note that this Perl script assumes that all the SQL script files have the .sql file extension. That is just an example to show that you can easily filter out or filter for specific types of files, and construct the batch as you wish.
You can also easily execute the SQL script files directly in the Perl script without using an intermediate batch file. The commented line in the script does precisely that (if uncommented).
The assumption that the SQL scripts can be executed without any particular order can be easily removed with just a little bit of more coding as long as a way to identify the order is provided. For instance, a list of the script file names may be included in some release notes, and they must be executed in that order. It is quite easy to take that list, and help sort the SQL script files along with their complete paths so that they are listed correctly in the batch file.