Run the script in SQLCMD mode in SSMS and use :on error exit . If you run a script form application, use a library compatible with sqlcmd mode, such as dbutilsqlcmd .
Edit
The fact that many answers recommending various forms of IF and RETURN and sp_executesql is missing is that they solve the problem of not executing a batch (sequence limited by GO ). This doesn't help much when talking about the script . A package that checks for the existence of the database will skip the instructions, but very soon, but the next batch in the script will continue and do everything it does (for example, create tables) in the current database, and not in the desired database. Adding verification when begging for each batch is tedious and error prone, so placing an entire script in one batch is often impossible. The best solution is to simply make USE <inexisting name> and rely on :on error exit to abort the script on the first error.
source share