如何:从 Service Broker 错误消息检索信息(Transact SQL)

适用于SQL ServerAzure SQL 托管实例

类型为 https://schemas.microsoft.com/SQL/ServiceBroker/Error 的消息是 Service Broker 错误消息。 此类型的消息为包含代表错误的数值代码及错误说明的 XML 文档。

从 Service Broker 错误消息中检索信息

  1. 声明 int 类型的变量以保存错误代码。

  2. 声明 nvarchar(3000) 类型的变量以保存错误说明。

  3. 声明 xml 类型的变量以保存消息正文的 XML 表示形式。

  4. CASTvarbinary(max)xml 的消息正文,并将结果分配给 xml 类型的变量。

  5. 使用 xml 数据类型的值函数检索错误代码。

  6. 使用 xml 数据类型的值函数检索错误说明。

  7. 按照适合于您应用程序的方法处理该错误。 错误代码为负值的错误是由 Service Broker 生成的。 运行的服务程序 END CONVERSATION WITH ERROR生成具有正错误代码的错误。

例子

-- The variables to hold the error code and the description are
-- provided by the caller.
CREATE PROCEDURE [ExtractBrokerError] (
    @message_body VARBINARY (MAX),
    @code INT OUTPUT,
    @description NVARCHAR (3000) OUTPUT
)
AS
BEGIN
    -- Declare a variable to hold an XML version of the message body.
    DECLARE @xmlMessage AS XML;

    -- CAST the provided message body to XML.
    SET @xmlMessage = CAST (@message_body AS XML);
    SET @code = @@ERROR;
    IF @@ERROR <> 0
        RETURN @code;

    -- Retrieve the error code from the Code element.
    SET @code = (SELECT @xmlMessage.value(N'declare namespace
               brokerns="https://schemas.microsoft.com/SQL/ServiceBroker/Error";
                   (/brokerns:Error/brokerns:Code)[1]', 'int'));

    -- Retrieve the description of the error from the Description element.
    SET @description = (SELECT @xmlMessage.value('declare namespace
               brokerns="https://schemas.microsoft.com/SQL/ServiceBroker/Error";
               (/brokerns:Error/brokerns:Description)[1]', 'nvarchar(3000)'));
    RETURN 0;
END
GO