August 1st, 2007, 03:15 PM
Substring in a batch file with a for variable
Im new to writing batch files don't really understand the difference between %% variables and % ones i wrote this batch to be able to attach detach databases in the same folder has the batch but i don't seem able to find a way to make the substring in the loop work here is my code:
sqlcmd -S %1
If %2 == d GOTO DETACH
If %2 == a GOTO ATTACH
FOR %%Z IN (*.mdf) DO sqlcmd -d [master] -q "CREATE DATABASE [%%Z:~0,-4%] ON ( FILENAME = N'%CD%\%%Z' ), ( FILENAME = N'%CD%\%%Z_log.ldf') FOR ATTACH ;"
August 1st, 2007, 05:00 PM
I believe the double-percent is just to denote that it is a special variable in the FOR loop.
Here's a very good resource on DOS Batch commands and syntax.
One thing I noticed is that your FOR loop set is only *.mdf. You may want to change that to:
This will cause your loop to loop through all the files in the directory with the .bat file.
FOR %%Z IN ('dir *.mdf') DO ...
August 2nd, 2007, 02:51 AM
In addition to that, I think you can read all about FOR syntax by issuing on the command prompt:
For example on my XP SP2 box I could read
"Problem" is just a bleak word for challenge. -- Richard Fish