2015-06-16 90 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%