如果存在和批处理(.bat)文件中的错误级别

时间:2015-06-16 13:11:15

标签: windows batch-file command-line

我尝试对SQL命令的结果运行删除命令,但仅当它返回错误代码为0.以下是我的代码:

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%

目前,我收到了语法错误,但我无法看到我出错的地方。任何帮助都是有用的,因为我是批处理新手,谢谢!

1 个答案:

答案 0 :(得分:3)

试试这个:

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%