如何使用t-sql更新xml变量中的xml属性值?

时间:2011-03-17 11:33:44

标签: sql sql-server xml sql-server-2008 tsql

我们有一个示例代码段:

DECLARE @xml XML = N'
<a abb="122">
    <b>
    </b>
</a>
';
SELECT @xml;

--need to update abb to be 344 in @xml here

SELECT @xml;

我不知道如何更新该属性abb的值。

2 个答案:

答案 0 :(得分:18)

set @xml.modify('replace value of (/a/@abb)[1] with 344')

在这里阅读更多相关信息。 XML Data Modification Language (XML DML)

答案 1 :(得分:0)

对于那些想要从VARIABLE更新的人,这是一个示例...

DECLARE @XML XML = '<Event auditId="00000000-0000-0000-0000-000000000000" createdOn="2018-12-29T19:54:01.140" retryCount="0" version="1.0.0">
  <DataSource machineName="LONELYMOUNTAIN">SqlBroker.ApplicationSender</DataSource>
  <Topic>
    <Filter>Meter.Created</Filter>
  </Topic>
  <Name>Meter.Created</Name>
  <Contexts>
    <Context>
      <Name>Meter</Name>
      <Key>
        <Id>1</Id>
        <MeterGlobalId>DC3995A1-790B-E911-AC2F-D4BED9FD41CB</MeterGlobalId>
      </Key>
    </Context>
  </Contexts>
  <Payload type="Entity">
    <Device>
      <Id>1</Id>
      <DeviceGlobalId>27C03D8C-790B-E911-AC2F-D4BED9FD41CB</DeviceGlobalId>
      <DeviceName>Station X</DeviceName>
    </Device>
    <Meter>
      <Id>1</Id>
      <MeterGlobalId>DC3995A1-790B-E911-AC2F-D4BED9FD41CB</MeterGlobalId>
      <DeviceId>1</DeviceId>
      <MeterName>Meter Awesome</MeterName>
      <MeterNumber>1111</MeterNumber>
    </Meter>
  </Payload>
</Event>'

DECLARE @Audit TABLE (Id UNIQUEIDENTIFIER);
DECLARE @AuditId UNIQUEIDENTIFIER;

-- GET Id
SELECT @AuditId = NEWID()

-- REPLACE Id
SET @XML.modify('replace value of (/Event/@auditId)[1] with sql:variable("@AuditId")')

SELECT @XML