This should be the first line of your script:
Code:
whenever sqlerror exit sql.sqlcode
It will exit immediately with a non-zero number whenever it encounters an error.