Getting sp_tracegenerateevent to work in a stored procedure

后端 未结 2 881
时光取名叫无心
时光取名叫无心 2021-01-21 22:15

I\'m having a hard-time debugging a stored procedure called from BizTalk.

In a prior thread, someone suggested using sp_trace_generateevent. [Use SQL Debugger when sto

2条回答
  •  走了就别回头了
    2021-01-21 22:48

    Well, if you try this:

    SET XACT_ABORT ON;
    BEGIN TRY   
        SELECT 1 / 0;
    END TRY
    BEGIN CATCH
        DECLARE @message nvarchar(128);
        SET @message = LTRIM(STR(ERROR_MESSAGE()));
        exec sp_trace_generateevent @event_class=82, @userinfo = @message
    END CATCH
    

    You'll get immediate feedback on what's wrong:

    Msg 8114, Level 16, State 5, Line 8 Error converting data type nvarchar to float.

    And that's because that STR() call you've got is not the right thing to use -- STR formats floating-point values, and only those. (For flexible conversion, use FORMAT and/or CONCAT, the latter of which always implicitly converts things to strings without complaining.)

    Aside from that, the first parameter of the stored procedure is @eventid, not @event_class (this is normally an error, but extended stored procedures are more flexible that way -- you could call the parameter @banana and it will still work). Still, for clarity's sake we should use the documented name. So:

    SET XACT_ABORT ON;
    BEGIN TRY   
        SELECT 1 / 0;
    END TRY
    BEGIN CATCH
        DECLARE @message nvarchar(128) = ERROR_MESSAGE();
        EXEC sp_trace_generateevent @eventid=82, @userinfo = @message;
    END CATCH
    

    And in my profiler, this produces a UserConfigurable:0 event with

    Divide by zero error encountered.

    Note that if there is no TRY / CATCH, you should still be able to get errors even without generating your own trace event, through the Exception event.

提交回复
热议问题