How to rename XML node name in a SQL Server

2019-02-25 10:46发布

问题:

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:

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>')