我在SQL Server 2008中有一个表,其中有一些列。这些列之一是Xml格式,我想更新一些属性。
例如,我的Xml列的名称为XmlText,它在前5行中的值如下:
XmlText
<Identification Name="John" Family="Brown" Age="30" /> <Identification Name="Smith" Family="Johnson" Age="35" /> <Identification Name="Jessy" Family="Albert" Age="60" /> <Identification Name="Mike" Family="Brown" Age="23" /> <Identification Name="Sarah" Family="Johnson" Age="30" />
我想将所有Age属性设置为30到40,如下所示:
Age
<Identification Name="John" Family="Brown" Age="40" /> <Identification Name="Smith" Family="Johnson" Age="35" /> <Identification Name="Jessy" Family="Albert" Age="60" /> <Identification Name="Mike" Family="Brown" Age="23" /> <Identification Name="Sarah" Family="Johnson" Age="40" />
从问题的早期版本看来,您的XML实际上位于表的不同行上。在这种情况下,您可以使用此功能。
update YourTable set XMLText.modify('replace value of (/Identification/@Age)[1] with "40"') where XMLText.value('(/Identification/@Age)[1]', 'int') = 30
使用表变量的工作样本。
declare @T table(XMLText xml) insert into @T values('<Identification Name="John" Family="Brown" Age="30" />') insert into @T values('<Identification Name="Smith" Family="Johnson" Age="35" />') insert into @T values('<Identification Name="Jessy" Family="Albert" Age="60" />') insert into @T values('<Identification Name="Mike" Family="Brown" Age="23" />') insert into @T values('<Identification Name="Sarah" Family="Johnson" Age="30" />') update @T set XMLText.modify('replace value of (/Identification/@Age)[1] with "40"') where XMLText.value('(/Identification/@Age)[1]', 'int') = 30 select * from @T