如何更新sql中的xml字段表?

时间:2012-04-24 07:16:24

标签: sql sql-server

我在表格中有一个XML列,如下所示:

<word A="al"   B="h"   C="Ps" />
<word A="has"  B="es"  C="Pf" /> 
<word A="mom"  B="es"  C="Ph" />

我想像这样更新这个字段:

<word A="al"   B="B1"   C="C1" /> 
<word A="has"  B="B2"  C="C1" /> 
<word A="mom"  B="B2"  C="C2" />

我想通过SQL Server中的函数来完成。

谢谢!

2 个答案:

答案 0 :(得分:4)

正如Mikael所说,你需要描述更新背后的逻辑。但是对于上面的预期输出,以下应该有效:

DECLARE @Words xml
SELECT @Words = '
<word A="al"   B="h"   C="Ps" />
<word A="has"  B="es"  C="Pf" />
<word A="mom"  B="es"  C="Ph" />'

SET @Words.modify('replace value of(/word[@A = "al"]/@B)[1] with "B1"')
SET @Words.modify('replace value of(/word[@A = "al"]/@C)[1] with "C1"')
SET @Words.modify('replace value of(/word[@A = "has"]/@B)[1] with "B2"')
SET @Words.modify('replace value of(/word[@A = "has"]/@C)[1] with "C1"')
SET @Words.modify('replace value of(/word[@A = "mom"]/@B)[1] with "B2"')
SET @Words.modify('replace value of(/word[@A = "mom"]/@C)[1] with "C2"')

SELECT @Words

答案 1 :(得分:1)

请在XQuery中尝试“替换值”。
参考:http://msdn.microsoft.com/en-us/library/ms190675.aspx