R.G*_*dam 0 xml t-sql sql-server xpath xquery
我需要使用SQL替换xml中的值,我面临的挑战是我要替换的值不在特定的xpath上,相同的值在不同的节点上并且xpath也不同,所以基本上我想找到并替换一个值。
例子:
<data>
<policy>
<Effectivedate>2018-04-05</Effectivedate>
<TermStartDate>2018-04-05</TermStartDate>
<Line>
<Risk>
<Coverage>
<Type>1</Type>
<coverstartdate>2018-04-05</coverstartdate>
</Coverage>
<Coverage>
<Type>2</Type>
<coverstartdate>2018-04-05</coverstartdate>
</Coverage>
<Coverage>
<Type>3</Type>
<coverstartdate>2018-04-05</coverstartdate>
</Coverage>
</Risk>
</Line>
</policy>
</data>
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,我需要将日期 2018-04-05 替换为 2018-04-06
请有人在这里帮忙。
如果您必须替换不同路径中的元素,您可以将 转换xml为 a*char并使用replace:
declare @xml xml='<data> <policy> <Effectivedate>2018-04-05</Effectivedate> <TermStartDate>2018-04-05</TermStartDate> <Line> <Risk> <Coverage> <Type>1</Type> <coverstartdate>2018-04-05</coverstartdate> </Coverage> <Coverage> <Type>2</Type> <coverstartdate>2018-04-05</coverstartdate> </Coverage> <Coverage> <Type>3</Type> <coverstartdate>2018-04-05</coverstartdate> </Coverage> </Risk> </Line> </policy> </data>'
select cast (replace (cast(@xml as nvarchar(max)), '2018-04-05','2018-04-06') as xml)
Run Code Online (Sandbox Code Playgroud)
结果: