Question

It seems to me that SQL THROW is missing a crucial feature that RAISERROR has, and that is the abilty to use WITH LOG so that an Alert can be fired when the error number is logged in the Application log. Is there a simple way to do this that is escaping me or do I still have to rely on the more cumbersome RAISERROR and sp_addmessage SP? I would like to be able to notify an Operator through an Alert using THROW in a CATCH block.

Was it helpful?

Solution

No, THROW is missing some RAISERROR functionality, including WITH LOG. I blogged about this back when SQL Server 2012 was still in beta, and no changes have been made since:

However, you don't need to use sp_addmessage to send RAISERROR messages to the log, unless you need a custom message number outside of 50000:

DECLARE @s VARCHAR(32) = 'friend';
RAISERROR(N'What happened %s?', 19, 1, @s) WITH LOG;

Results:

enter image description here

Reading the guts of the question again, you probably do want to use sp_addmessage to achieve your ultimate goal. I shouldn't have tried to separate the logging on its own from that (50000 doesn't help much if you have other errors getting logged and want different alerts).

Example of putting the error number into the text for the message raised by RAISERROR:

BEGIN TRY
  SELECT 1/0;
END TRY
BEGIN CATCH
  DECLARE @err INT = ERROR_NUMBER();
  RAISERROR(N'What happened %d?', 19, 1, @err) WITH LOG;
END CATCH
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top