0

I have an XML column in SQL Server which stores some data like:

<Title>
    <Section name="General">
         <InputText>
              <Value> Comments for the XML </Value>
         </InputText>
    </Section>
    <Section name="Comments">
         <InputText>
              <Value> Copy here the value of comments from General Section.</Value>
         </InputText>
    </Section>
</Title>

In this XML only one section tag was present. I created one more section called Comments and I want to copy the text value from first section called General to the newly created section's InputText child node.

I have tried one query:

UPDATE tempTable
SET ColumnXML.modify('replace value of (/Title[1]/Section[2]/InputText[1]/Value[1]/text())[1] 
   with ColumnXML.value(/Title[1]/Section[1]/InputText[1]/Value[1]/text())[1], "varchar(max)"')
WHERE id < 100; 

It runs successfully but I don't see any changes happening. The expected output is in all 100 XMLs the value of input text from one section to get copied to another section's input text.

What would be the correct query for this?

2
  • Yes, it worked for my problem. But one thing I want to highlight, the Value node was empty so replace was not working. I inserted some dummy values in the Value node and then the replace worked as expected. Thanks for highlighting the mistakes I was doing. Commented Jun 29, 2020 at 5:01
  • Hi Richa. Depending on the cases you encounter there are probably other ways around that. Commented Jun 29, 2020 at 6:51

1 Answer 1

4

You're making several mistakes in using modify.

  • You cannot (and need not) reference ColumnXML in the modify function, it will not be visible in its scope.
  • I do not know where the varchar(max) comes from in your statement, I suspect you used it as an argument for the value function. You do not need the value function.
DECLARE @x XML=N'<Title>
    <Section name="General">
         <InputText>
              <Value> Comments for the XML </Value>
         </InputText>
    </Section>
    <Section name="Comments">
         <InputText>
              <Value> Copy here the value of comments from General Section.</Value>
         </InputText>
    </Section>
</Title>';

DECLARE @t TABLE(x XML);
INSERT INTO @t(x)VALUES(@x);

UPDATE @t
SET x.modify('replace value of (/Title[1]/Section[2]/InputText[1]/Value[1]/text())[1]
   with (/Title[1]/Section[1]/InputText[1]/Value[1]/text())[1]');

SELECT * FROM @t;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.