XML到NVarchar(MAX)失败

时间:2014-05-19 16:03:25

标签: sql xml procedure nvarchar

我有一个存储过程,它返回2个结果集,每个结果集包含完全一个单元格。在第一个中,我返回一个xml,第二个返回一个日期时间值。

我尝试从链接服务器访问此SP(SP_XML),该服务器未能在链接服务器上说XML。所以我写了一个包装器(SP_NChar),如下所示。问题是我只需要跨链接服务器的XML结果集而不是日期时间结果集(如果我收到它就没关系)

CREATE PROCEDURE SP_NChar
AS  
BEGIN  
 -- TO STORE PROC RESULT
 DECLARE @XML_RESULT TABLE(result XML)  
 BEGIN TRY  

  INSERT INTO @XML_RESULT(result) EXEC SP_XML
  SELECT CAST(result AS NVARCHAR(MAX)) FROM @XML_RESULT   

 END TRY  
 BEGIN CATCH

  -- This block will get executed because one is XML and another is Datetime and it will fail in try part
  PRINT 'Do Nothing'  
  select * from @XML_RESULT  

 END CATCH  
END

它在我的开发环境中按预期工作,但在prod环境中失败,任何想法可能出错。

仅用于测试目的SP_XML

CREATE procedure SP_XML
as
BEGIN
    select CAST('<ROOT>2</ROOT>' AS XML)
    select getdate()
END

1 个答案:

答案 0 :(得分:0)

尝试修改您的SP:

CREATE PROCEDURE [dbo].[SP_NChar]
AS  
BEGIN  
 -- TO STORE PROC RESULT
    DECLARE @XML_RESULT TABLE(result XML)  
    BEGIN TRY  
        INSERT INTO @XML_RESULT(result) EXEC SP_XML
        SELECT CAST(result AS NVARCHAR(MAX)) FROM @XML_RESULT   
    END TRY  
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        DECLARE @ErrorSeverity INT;
        DECLARE @ErrorState INT;
        SELECT 
            @ErrorMessage = ERROR_MESSAGE() + '. В строке: ' + CAST(ERROR_LINE() AS NVARCHAR),
            @ErrorSeverity = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE();

        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
        RETURN;
    END CATCH  
END

您将收到错误:

Msg 50000, Level 16, State 2, Procedure SP_NChar, Line 28
Operand type clash: datetime is incompatible with xml

在SP_XML中,您尝试返回datetime,但无法将其转换为XML。我建议你修改这样的代码:

CREATE PROCEDURE [dbo].[SP_XML]
AS
BEGIN
    SELECT CAST('<ROOT>2</ROOT>' AS XML)
    SELECT CAST('<date>' + CONVERT(nvarchar(MAX),getdate()) + '</date>' AS XML)
END