小编典典

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

sql

我在一个表中有一个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中的一个函数来做。

谢谢!


阅读 191

收藏
2021-04-07

共1个答案

小编典典

正如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
2021-04-07