user2173894
user2173894

Reputation: 35

Replace an attribute name in an Xml column with a SQL query

I need to replace the attribute's name "TimeStamp" by "Timestamp" in the following XML example :

<CMD CommandID="6000">
   <DATA>
      <ReportData Key="10000">
         <Event TimeStamp="2013-03-07 15:42:49.000" Name="ABC" />
         <Event TimeStamp="2013-03-07 15:42:50.000" Name="DEF" />
         <Event TimeStamp="2013-03-07 16:22:03.000" Name="GHI" />
      <ReportData>
   <DATA>
<CMD>

It is stored in a SQL Server 2008 database within a column of XML type.

I tried something like this but it's incorrect:

DECLARE @variable NVARCHAR(20) = 'Timestamp'

UPDATE MyDatabase.dbo.MyTable
SET MyXmlColumn.modify('replace value of (/CMD/DATA/ReportData/Event/@TimeStamp) with sql:variable("@variable") ')

Thank you for your help.

Upvotes: 2

Views: 1222

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

You can use replace.

update MyDatabase.dbo.MyTable
set MyXMLColumn = replace(cast(MyXMLColumn as nvarchar(max)), '<Event TimeStamp="', '<Event Timestamp="')

Upvotes: 5

Related Questions