2

I am trying to append some nodes to an existing XML in the database. The XML looks like the following:

<Parameters>
  <Parameter>
    <Name>ColumnsToDisplay</Name>
    <Value>Priority</Value>
    <Value>Description</Value>
    <Value>Asset ID</Value>
  </Parameter>
</Parameters>

The number of values can vary for each parameter. I'm trying to update the XML by appending a few new values as with the query below. Its a little wonky but it is the only way I could get FOR XML AUTO to work.

set @NewXML =
(
select * from 
    (
    SELECT  
        Parameter.C.value('Name[1]', 'varchar(256)') as Name,
        Parameter.C.value('Value[1]', 'varchar(256)') AS Value
    FROM tblSavedReportParameters
    CROSS APPLY ParameterXML.nodes('//Parameter') Parameter(C)
    where savedreportid = @SavedReportID
    union 
    select  'FilterType' as Name, '#All' as Value
    union 
    select  'FilterText' as Name, '#All' as value
    ) as Parameter for xml Auto, elements, root('Parameters') 
)

Everything works great except the new XML only returns the first value for each parameter. I've tried a variety of CROSS APPLY and INNER JOINS on the value node and just can't get the syntax down. It currently looks like this:

<Parameters>
  <Parameter>
    <Name>ColumnsToDisplay</Name>
    <Value>Priority</Value>
  </Parameter>
  <Parameter>
    <Name>FilterText</Name>
    <Value>#All</Value>
  </Parameter>
  <Parameter>
    <Name>FilterType</Name>
    <Value>#All</Value>
  </Parameter>
</Parameters>

How can I update the query to return all the values for each parameter? Thanks!

1 Answer 1

1
set @NewXML = 
(
  select (
         select T.ParameterXML.query('Parameters/Parameter')
         from tblSavedReportParameters as T
         where T.savedreportid = @SavedReportID 
         ),
         (
         select P.Name, P.Value
         from (
              select 'FilterType' as Name, '#All' as Value
              union all
              select 'FilterText', '#All'
              ) as P
         for xml path('Parameter'), type
         )
  for xml path('Parameters')
)

This query builds two XML columns that is then combined using for xml path('Parameters'). The first column contains all Parameters from the XML and the second column contains all your new Parameters.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, much easier to do it that way. I'll keep that in mind for the future. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.