简体   繁体   中英

XML to NVarchar(MAX) failing

I have a stored procedure which returns 2 resultset each containing exact one cell. In first one I am returning an xml and in second a datetime value.

I tried accessing this SP (SP_XML) from a linked server which failed saying XML not allowed on linked server. So I wrote a wrapper (SP_NChar) like below. The thing is I need only the XML resultset across linked server and not the datetime resultset(it does not matter if I receive it or not)

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

It works as expected on my dev environment, but fails on prod environment, any idea what might go wrong.

Just for testing purpose here SP_XML

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

Try modify your SP like this:

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

And you'll get the error:

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

In SP_XML you try to return datetime, but you can't convert it to XML. I advice you to modify code like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM