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

时间:2018-09-25 14:13:12

标签: sql sql-server sql-server-2012

有什么方法可以更新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>

1 个答案:

答案 0 :(得分:2)

您需要使用XML modify function

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>
*/