1

我在 sql 表中有一个 XML 列需要更新。说结构如下:

<JPS>
 <P>
  <JP>
   <IsRequired>true</IsRequired>
   <Name>Folder</Name>
   <Value>C:\Test</Value>
  </JP>
  <JP>
   <IsRequired>false</IsRequired>
   <Name>Email Addresses</Name>
   <Value>a@a.com; b@b.com</Value>      
  </JP>
</P>

我想将表中所有行中所有 XML 值中的电子邮件地址更新为特定值。我怎样才能达到同样的效果?

4

2 回答 2

1

If you want to update the contents of the <Value> element of the <JP> tag that has a <Name>Email Addresses</Name> value, then you can use something like this:

;WITH XmlEmail AS
(
SELECT 
    SomeUniqueID,  // some unique/primary key ID from your table - adapt as needed!
    JPReq = XJP.value('(IsRequired)[1]', 'varchar(20)'),
    JPName = XJP.value('(Name)[1]', 'varchar(20)'),
    JPValue = XJP.value('(Value)[1]', 'varchar(20)')
FROM 
    dbo.YourTable
CROSS APPLY
    YourXmlColumn.nodes('/JPS/P/JP[Name="Email Addresses"]') AS XTbl(XJP)
)
UPDATE dbo.YourTable
SET YourXmlColumn.modify('replace value of (/JPS/P/JP[Name="Email Addresses"]/Value/text())[1] with "newmail@test.tst"')
FROM XmlEmail xe 
WHERE dbo.YourTable.SomeUniqueID = xe.SomeUniqueID

This will update all rows, and all <JP>/<Value> nodes to the same value - is that what you're looking for?

Update: added support for checking and updating only those rows where the XML column actually does contain a <JP> tag with Email Addresses as its name - it requires that there is a primary key on your table (not sure what it is, since you didn't say anything about it) .... I've used SomeUniqueID as column name - adapt to your table as needed!

于 2013-07-23T10:44:46.697 回答
0

您不能在标准 sql 中执行此操作。

使用标准 sql,您应该一次读取相关的 xml 行,更新 xml 并将其插入回去。

于 2013-07-23T10:28:41.660 回答