Here's my problem's background: I have a couple of merge queries to UPSERT in my SQL Server tables (1 merge query per table). I converted them into stored procedures and loaded their names in a table which I am then executing via my SSIS package.
The problem is I want to embed error handling/status update in each of my stored procedures. I want it to email me the output if the merge query is successful, otherwise, send me the error in the email (as an attachment or printed in the email body).
I researched and found a catch block but how do I switch between success and failure?
I have tried, using sp_send_dbmail
twice, once in try block to send me output and once in the catch block to send me error, I tried printing the error like SELECT ERROR_MESSAGE()
and it printed this text - I know it would print the text. I thought I am in the right direction so declared a variable @errmsg
to contain the error message but where do I set the value for this variable? I tried setting it in the catch block but it gives me error. Please advise.
SET @Output = @@ROWCOUNT
END
ELSE
BEGIN
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Notifyme',
@recipients = 'johnkovich@abc.me',
@body = '@output',
@subject = 'Testmsg';
END
END TRY
BEGIN CATCH
SET @ERRMSG = ERROR_MESSAGE()
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Notifyme',
@recipients = 'johnkovich@abc.me',
@body = @ERRMSG,
@subject = 'Testmsg2'
END CATCH