I’m trying to build a custom error message string for a bit of dynamic SQL. It looks like this when not wrapped in dynamic SQL:
SET @message = 'EXCEPTION: Msg ' + COALESCE(CAST(ERROR_NUMBER() AS NVARCHAR(20)), '[NULL]') + ', ' +
'Level ' + COALESCE(CAST(ERROR_SEVERITY() AS NVARCHAR(20)), '[NULL]') + ', ' +
'State ' + COALESCE(CAST(ERROR_STATE() AS NVARCHAR(20)), '[NULL]') + ', ' +
'Procedure ' + COALESCE(@PROCEDURE_NAME, '[NULL]') + ', ' +
'Line ' + COALESCE(CAST(ERROR_LINE() AS NVARCHAR(20)), '[NULL]') + ', ' +
'Message: ' + COALESCE(ERROR_MESSAGE(), '[NULL]') ;
I’m having trouble getting the quotes down so that it looks like this when it’s executed in the dynamic SQL. How should the quotes be arranged in the following:
EXEC @sql = 'BEGIN TRY
...
END TRY
BEGIN CATCH
DECLARE @PROCEDURE_NAME NVARCHAR(128);
SET @PROCEDURE_NAME = OBJECT_NAME(@@PROCID);
END CATCH
';
Your message code looks fine.
However, if you want to embed your @message in dynamic SQL, then you have to double every single quote.
This is a pain to do by hand. So, I do the following:
') in the search box, and two single quotes ('') in the replace with box.