[英]SQL Server XML update last node value
Is there any way to update the userid
value in the last node in SQL Server? 有什么方法可以更新SQL Server中最后一个节点中的
userid
值? I have found a solution, but it requires an index value. 我找到了一个解决方案,但是它需要一个索引值。 The node count will not be the same 2 always, it might 3 for some case.
节点数始终不会是2,在某些情况下可能是3。
<audit>
<home>
<create timestamp="2017-10-16 12:19:28" userid="20" />
<create timestamp="2018-09-25 11:21:21" userid="130" />
</home>
</audit>
You need to use the XML modify
function . 您需要使用XML
modify
功能 。
declare @data xml = '
<audit>
<home>
<create timestamp="2017-10-16 12:19:28" userid="20" />
<create timestamp="2018-09-25 11:21:21" userid="130" />
</home>
</audit>
'
declare @new_id int = 150
set @data.modify('
replace value of (//create)[last()]/@userid
with sql:variable("@new_id")
')
SELECT @data
/*
<audit>
<home>
<create timestamp="2017-10-16 12:19:28" userid="20" />
<create timestamp="2018-09-25 11:21:21" userid="150" />
</home>
</audit>
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.