Question

I have a batch file that runs multiple SQLCMD commands which run queries supplied by external SQL script files. The scripts themselves are fairly trivial, but I'm bugged by all the file dependencies required to run the batch. I've been googling for ways to link all these files together without luck.

Are there any techniques I can apply to encapsulate the batch script and SQL scripts within a single file, such that I could move the resulting file to other machines without dragging the individual sql files along? For the sake of organization/readability/information hiding, I would really prefer to avoid embedding the sql directly in the batch file.

Was it helpful?

Solution

Consider using 7-Zip. It is free and here

You could encapsulate all your BAT files and SQL commands into a zip like this:

C:\> 7za a -t7z archive.7z *.BAT *.SQL

Then you can extract like this:

C:\> 7z e archive.7z

Alternatively you could make a self-extracting executable with it - which has the benefit you don't need any tools to extract it when you arrive at another server, but you may not be able to Email that. By the way, if you change the command to the following, Windows can read the archive itself natively so you don't need to install extraction software wherever you go with the file:

C:\> 7za a -tzip archive.zip *.BAT *.SQL

Or you could use the Microsoft CAB tool that will be present everywhere documentation.

That would look something like this if you wanted to gather *.BAT and *.CMD into a "cabinet" called BATplusSQL.cab:

dir /b *.BAT *.CMD >files.txt
makecab /d "CabinetName1=BATplusSQL.cab" /f files.txt
del /q /f files.txt

OTHER TIPS

Here is an example of what I mean.

Create a text file with one SQL query per line similar to this:

My Queries
Select * from table1 where something = somethingelse
Select * from table2
delete from table3
update table1 set something=nothing

Make sure the first line is not a query. It can be anything else. Tweak the settings in %sql% as necessary.

Run the following batch file:

@echo off
setlocal

set "sql=sqlcmd -S MySERVER -E -q "

set cnt=1
for /f "tokens=* skip=%cnt%" %%a in (sqlQueries.txt) do (
  echo %sql% "%%a"
  set /a cnt+=1
)

Remove the echo to run the queries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top