Is it possible to capture error message from one step in another step of a SQL Server Agent job?
I have below scenario:
Step 1: Transact-SQL script (TSQL)
-- On Success action: Go to step 2
-- On Failure action: Go to step 3
Step 2: Transact-SQL script (Send success email)
Step 3: Transact-SQL script (Send failure email)
What I need is, if step 1
fails, I need to capture error message from step 1
in step 3
and send the same in an email notification.
I tried to use below token in Job step, but no success.
declare @err_msg as nvarchar(4000) = $(ESCAPE_SQUOTE(A-MSG))
Best Answer
I think your best bet is going to be querying the
msdb.dbo.sysjobhistory
table in the job step to get the information you're looking for.Here's an example query that will get you all runs for a given job (mashed together from these two MSSQLTips articles [ref1], [ref2]). Obviously, you'll want to adjust this to fit your means, but this should provide you with sufficient direction to get what you want.