I am attempting to run a postgres query from within a batch file. However, I have thus far been unable to detect when the command fails. The following is what I have tried thus far:
@FOR /F %%A IN ('PSQL -U userName -d dbName -t -c "SELECT * FROM nonExistantTable" 2^>^&1') DO @(
ECHO !ERRORLEVEL!
)
I have also tried the following:
1) Adding "CALL" prior to the sql command (CALL PSQL -U ...
)
2) Adding "-v ON_ERROR_STOP=1" to the sql command, both with and without the "CALL" command (PSQL -U ... -v ON_ERROR_STOP=1
)
However, the value of ERRORLEVEL is always coming out as zero. Does anyone know how to detect an error in a call to PSQL using batch? Specifically, the error I am getting is that the table doesn't exist. Thanks.
The
for /f
executes the command in a separatecmd
instance and theerrorlevel
from this instance is not exported to the code inside todo
clause.The better way to handle it in pure batch is:
Something like