Error Handling with Batch File & Sqlcmd

前端 未结 4 1888
傲寒
傲寒 2021-02-07 07:19

I have a batch file that runs some SELECT queries using sqlcmd, puts the results into text files, and uploads those files onto an FTP server. That\'s all working just the way it

4条回答
  •  佛祖请我去吃肉
    2021-02-07 07:19

    I would maybe start with putting return values in your SQL, like so:

    DECLARE @IsBored bit = 1
    
    ... do work ...
    
    SELECT 0 -- Success!
    

    You could take it a bit further and use TRY/CATCH blocks to trap errors and return an error code. With SQLCMD, you can use the return code from your SQL as the exit code of the application, like so:

    sqlcmd -b -S ServerName -E -d DbName -q "EXIT(EXEC dbo.YourProc)" 
           -o "C:\Logs\output.log" -u
    

    If you were managing your SQLCMD calls with something like a scheduler, you could take action based on returns codes from SQLCMD. Since you're just using batch files, I think you can do something like this:

    @ECHO OFF
    sqlcmd -b -S ServerName -E -d DbName -q "EXIT(EXEC dbo.YourProc)" 
           -o "C:\Logs\output.log" -u
    IF %ERRORLEVEL% NEQ 0 ECHO "Error"
    

    Good luck!

提交回复
热议问题