1

I am struggling with this one for some time now. Tried WITH and WITHOUT EnableDelayedExpansion, but no joy. Simply, the variable %MYFILENAME% is empty right after it's set in a loop:

::echo off
setlocal enabledelayedexpansion
echo -- BACKUP DATABASES --
set MYPATH=D:\SQL_BACKUP
set MYDBASES=db1 db2 db3 db4

For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set MYDATE=%%c%%a%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set MYTIME=%%a-%%b)
set MYDATE=%MYDATE:.=-%

for %%q in (%MYDBASES%) do (
    echo DB %%q processing 
    set MYFILENAME=%MYPATH%\%%q_%MYDATE%_%MYTIME%.bak
    set SERVERNAME=.
    echo %MYFILENAME%
    echo sqlcmd -B -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%%q] TO DISK = N'%MYFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%%q backup', NOSKIP , STATS = 10, NOFORMAT"
    if %ERRORLEVEL% == 0 (
        echo OK
    ) else if %ERRORLEVEL% == 1 (
        echo failed!
    )
)

echo.
set MYDATE=
set MYTIME=
set BACKUPFILENAME=
set MYPATH=
set MYDBASES=
set MYFILENAME=

What I get is lost %MYFILENAME% imediatelly:

echo DB db1 processing
 set MYFILENAME=db1_11-11-2016_0-54.bak
 set SERVERNAME=.
 echo <<<----------HERE MISSING MYFILENAME ----------<<<
 echo sqlcmd -B -E -S . -d master -Q "BACKUP DATABASE [zdvrhnika] TO DISK = N''
WITH INIT , NOUNLOAD , NAME = N'zdvrhnika backup', NOSKIP , STATS = 10, NOFORMAT
"

Any idea?

EDIT After changing MYFILENAME and SERVERNAME variables to some simple texts, I found out, that they do not change at all! MYFILENAME is always empty, and SERVERNAME is always ".", regardless of what I set them to?! And regardless of whether I use SETLOCAL EnableDelayedExpansion or not. It's not script fault, but some environment stuff.

2

1 Answer 1

1

Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion **and use !var! in place of %var% to access the changed value of var ** or 2) to call a subroutine to perform further processing using the changed values.

Sign up to request clarification or add additional context in comments.

2 Comments

A third way is to use a pseudo call and double the percent signs call echo %%var%% or call set Var=%%OtherVar%%
Magoo, excellent! Works like a charm (replacing %variable% with !variable! inside block statements)! Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.