繁体   English   中英

SQL Server XML更新最后一个节点值

[英]SQL Server XML update last node value

有什么方法可以更新SQL Server中最后一个节点中的userid值? 我找到了一个解决方案,但是它需要一个索引值。 节点数始终不会是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>

您需要使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM