开发者

How to update an xml attribute value in an xml variable using t-sql?

Let's have a sample snippet:

DECLARE @x开发者_运维问答ml XML = N'
<a abb="122">
    <b>
    </b>
</a>
';
SELECT @xml;

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

SELECT @xml;

I don't know how to update that attribute abb's value.


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

Read more about it here. XML Data Modification Language (XML DML)


For those wanting to update from a VARIABLE, here is an example...

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜