IF Statement not working

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
bex
Posts: 11
Joined: 24 Mar 2009 05:41

IF Statement not working

#1 Post by bex » 24 Mar 2009 05:45

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

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

#2 Post by avery_larry » 24 Mar 2009 08:41

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

bex
Posts: 11
Joined: 24 Mar 2009 05:41

#3 Post by bex » 24 Mar 2009 08:51

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?

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

#4 Post by avery_larry » 24 Mar 2009 09:07

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.

bex
Posts: 11
Joined: 24 Mar 2009 05:41

#5 Post by bex » 25 Mar 2009 03:39

Thanks for your help. I shall try that today. :D

Post Reply