3

I have on my database a table with one column storing XML data. Due to changes in the source code we want to rename one specific XML node name and XML namespace. Lets say that I have the XML bellow:

<MediaClass xmlns="MediaClass/1">   
    <Media>
        <Title>Test</Title>
        <Type>Book</Type>
        <Price>1.00</Price>
    </Media>
</MediaClass>

How can I rename the Node MediaClass name to let's say Book and also change the namespace value?

So it can look like as:

<Book xmlns="Book/1">   
    <Media>
        <Title>Test</Title>
        <Type>Book</Type>
        <Price>1.00</Price>
    </Media>
</Book>

I need to do it entirely in T-SQL as this will be used as a migration script. The minimum SQL Server installed on ours customers is SQL Server 2005.

1 Answer 1

6

I don't know if this is possible with XML DML

It might work for you to use replace instead.

update YourTable set
  XMLCol = replace(replace(cast(XMLCol as nvarchar(max)), 
                           '<MediaClass xmlns="MediaClass/1">', 
                           '<Book xmlns="Book/1">'), 
                   '</MediaClass>', 
                   '</Book>')
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, that was my first approach indeed, but because my XML are bigger than 8000 characters, I have to use more complicated solution (sqlteam.com/article/search-and-replace-in-a-text-column) which I want to avoid.
@Andres - That is not a problem when you cast to nvarchar(max).
Yeah, after trying and guessing I think this is the most possible and feasible approach now. Thanks
Amazing... this helped a lot! :)

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.