Can I use XML.modify in combination with SELECT statement

  • I need to add xml data stored in multiple rows in a table  to a XML document by using XML.modify

    When I use the following code it is throwing an error:

    DECLARE @PKS       NVARCHAR(MAX) = ''
    DECLARE @TABLENAME VARCHAR(100) = 'CATALOGS'
    DECLARE @CRLF VARCHAR(2) = CHAR(13) + CHAR(10)
    DECLARE @XML XML = '<CHANGES/>'
    DECLARE @XML_PKS XML

    SELECT @XML.modify('insert (sql:column("PRIMARYKEY")) as last into (/CHANGES)[1]')
    FROM CONFIGURATION_LOG
    WHERE TABLENAME = @TABLENAME
    ORDER BY ID DESC

    SELECT @XML

    This is giving the following error:

    Msg 8137, Level 16, State 1, Line 16

    Incorrect use of the XML data type method 'modify'. A non-mutator method is expected in this context.

    My work around is:

    DECLARE @PKS       NVARCHAR(MAX) = ''
    DECLARE @TABLENAME VARCHAR(100) = 'CATALOGS'
    DECLARE @CRLF VARCHAR(2) = CHAR(13) + CHAR(10)
    DECLARE @XML XML = '<CHANGES/>'
    DECLARE @XML_PKS XML

    SELECT @PKS = @PKS + PRIMARYKEY + @CRLF
    FROM CONFIGURATION_LOG
    WHERE TABLENAME = @TABLENAME
    ORDER BY ID DESC

    SET @XML_PKS = CONVERT(XML, @PKS)

    SET @XML.modify('insert sql:variable("@XML_PKS") as last into (/CHANGES)[1]')

    SELECT @XML

    This works and gives the following output:

    <CHANGES>
    <PRIMARYKEY>
    <CATALOGID>101</CATALOGID>
    </PRIMARYKEY>
    <PRIMARYKEY>
    <CATALOGID>103</CATALOGID>
    </PRIMARYKEY>
    <PRIMARYKEY>
    <CATALOGID>102</CATALOGID>
    </PRIMARYKEY>
    <PRIMARYKEY>
    <CATALOGID>101</CATALOGID>
    </PRIMARYKEY>
    </CHANGES>

    I would like to find an optimized solution. Anyone an idea if the modify statement in a select is allowed?

     

  • The documentation seems clear on this:

    Modifies the contents of an XML document. Use this method to modify the content of an xml type variable or column. This method takes an XML DML statement to insert, update, or delete nodes from XML data. The modify() method of the xml data type can only be used in the SET clause of an UPDATE statement.

    If you haven't even tried to resolve your issue, please don't expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.

  • Thanks!

    I missed that you. I will keep to my origional way.

    Have a good day.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply