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

SQL Server XML更新最后一个节点值,sql,sql-server,sql-server-2012,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" /> &l

是否有任何方法可以更新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
修改

declare@data-xml=”
'
声明@new_id int=150
set@data.modify('
替换(//create)[last()]/@userid的值
带sql:variable(“@new_id”)
')
选择@data
/*
*/

您需要使用XML
修改

declare@data-xml=”
'
声明@new_id int=150
set@data.modify('
替换(//create)[last()]/@userid的值
带sql:variable(“@new_id”)
')
选择@data
/*
*/
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>
*/