#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2005
    Posts
    144
    Rep Power
    17

    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
    ETACH
    GOTO END
    :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 ;"
    REM %CD:~0,4%
    GOTO END
    PAUSE
    :END
  2. #2
  3. No Profile Picture
    Self-banned
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2004
    Location
    http://middle.nowhere.com
    Posts
    2,288
    Rep Power
    3606
    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:
    Code:
    FOR %%Z IN ('dir *.mdf') DO ...
    This will cause your loop to loop through all the files in the directory with the .bat file.
  4. #3
  5. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Oct 2004
    Location
    Brussels
    Posts
    1,001
    Rep Power
    840

    Lightbulb


    In addition to that, I think you can read all about FOR syntax by issuing on the command prompt:
    cmd.exe Code:
    help for

    For example on my XP SP2 box I could read
    ....
    To use the FOR command in a batch program, specify %%variable instead of %variable. Variable names are case sensitive, so %i is different from %I.
    ....
    "Problem" is just a bleak word for challenge. -- Richard Fish
    Javalanche

IMN logo majestic logo threadwatch logo seochat tools logo