2015-06-16 59 views
0

我试图对SQL命令的结果运行删除命令,但前提是它返回的错误代码为0.下面是我的代码:如果批处理(.bat)文件中存在错误级别

SqlCmd command... 

REM if SqlCmd command is successful run the below if exist statement 
if errorlevel 0 (

REM if the file exists then delete and exit: 
    if exist D:\Temp\database.bak(
     del "D:\Temp\database.bak" 
     exit /B 
    ) 
REM if the file doesn't exist, exit with error code 1: 
    else(
      echo The file does not exist 
      exit /B 1 
    ) 

) 
REM if SqlCmd is not successful, exit: 
if errorlevel 1 exit /B %errorlevel% 

目前,我收到一个语法错误,但我看不到我要去哪里错了。任何帮助将是有用的,因为我是批量新手,谢谢!

+0

括号需要一个空间: “d:\ TEMP \ database.bak(” 及其他子句必须和括号在同一行:“)else(”。 –

+0

'如果errorlevel 0'意味着:“如果errorlevel大于或等于0”,即所有的值!用法:'if if not errorlevel 1 ',即:“如果错误级别小于1” – Aacini

回答

2

试试这个:

REM if SqlCmd command is successful run the below if exist statement 
if "%ERRORLEVEL%"=="0" (

REM if the file exists then delete and exit: 
    if exist "D:\Temp\database.bak" (
     del "D:\Temp\database.bak" 
     exit /B 
    ) else (
REM if the file doesn't exist, exit with error code 1:  
     echo The file does not exist 
     exit /B 1 
    ) 

) 
REM if SqlCmd is not successful, exit: 
if "%ERRORLEVEL%"=="1" exit /B %ERRORLEVEL% 

或者,也许你可以使用一些GOTO语句尝试:

REM if SqlCmd command is successful run the below if exist statement 
if NOT "%ERRORLEVEL%"=="0" GOTO next 

REM if the file exists then delete and exit: 
    if exist "D:\Temp\database.bak" (
     del "D:\Temp\database.bak" 
     exit /B 
    ) else (
REM if the file doesn't exist, exit with error code 1:  
     echo The file does not exist 
     exit /B 1 
    ) 


:next 
REM if SqlCmd is not successful, exit: 
if "%ERRORLEVEL%"=="1" exit /B %ERRORLEVEL%