Stop processing a batch which is separated with 'GO'


If you have batch scripts which is separated with 'GO' statement, it is not easy to stop processing the rest of the script in case of an error.

You know 'GO' is not a T-SQL statement, it separates scopes from each other. If any error occurs in one scope, the rest of scope is omitted and next scope is run. At this point, if you want to stop running, you can use  RAISERROR ... WITH LOG option. An example is shown below.

select top 5 * from sys.objects
GO
if exists(select 1 from sys.databases)
begin
raiserror('Something bad happened.',23,1) with log
end
GO
select * from sys.databases
GO
Select 'Something'
GO

The key is "WITH LOG" option. When used, the error is logged to SQL Server log and connection is dropped.

sysadmin or ALTER TRACE permission is required.

It is life saving in some cases.

No comments:

Post a Comment