Page 1 of 1

IF Statement not working

Posted: 24 Mar 2009 05:45
by bex
I have the following code (reduced for example purposes):

Code: Select all

@ECHO OFF
SET count = 1

FOR /l %%G in (1, 1,2) DO (

ECHO
CALL :parameter_count "%%G"

IF count == 2 (sqlcmd -S WS23 -E -d sainsburys -Q "DROP TABLE dbo.NewStoreMapping;")

)
:parameter_count
 ECHO RUNNING Iteration: %1
 SET /a count+=1
PAUSE


But it will not execute IF count == 2 (sqlcmd -S WS23 -E -d sainsburys -Q "DROP TABLE dbo.NewStoreMapping;")

What am I doing wrong?

Thanks

Posted: 24 Mar 2009 08:41
by avery_larry
It needs to be %count% when you want to use the value of the variable:

Code: Select all

@ECHO OFF 
SET count = 1

FOR /l %%G in (1, 1,2) DO (

ECHO
CALL :parameter_count "%%G"

IF %count% == 2 (sqlcmd -S WS23 -E -d sainsburys -Q "DROP TABLE dbo.NewStoreMapping;")

)
:parameter_count
 ECHO RUNNING Iteration: %1
 SET /a count+=1
PAUSE

Posted: 24 Mar 2009 08:51
by bex
Hi there

Thanks for the reply.

When I add the '%', the bat doesn't run (or rather, it does run, but doesn't execute any of the commands).

However, when I do not include the '%', the file runs as per norm, but does not execute the command after the IF statement.

Any other ideas?

Posted: 24 Mar 2009 09:07
by avery_larry
Oops -- can't have a space when you're defining the variable:

set count = 1 <- wrong -- it's setting "count " to be " 1"

set count=1 <- correct

Also, you must use delayedexpansion to access the current value of count instead of the value that count was when the for loop was called (or you can call a subroutine instead of keeping it inside the for loop).

Code: Select all

@ECHO OFF 
setlocal enabledelayedexpansion
SET count=1

FOR /l %%G in (1,1,2) DO (

ECHO.
CALL :parameter_count "%%G"

IF !count!==2 (sqlcmd -S WS23 -E -d sainsburys -Q "DROP TABLE dbo.NewStoreMapping;")

)
goto :eof

:parameter_count
 ECHO RUNNING Iteration: %1
 SET /a count+=1
PAUSE
goto :eof


Note that the sqlcmd will run on iteration #1 because you increment the count variable after you echo the iteration count but before you compare the count variable to 2. But since this is just a partial bit of your code you may have other reasons for the way it is.

Posted: 25 Mar 2009 03:39
by bex
Thanks for your help. I shall try that today. :D