【问题标题】:How to update an xml attribute value in an xml variable using t-sql?如何使用 t-sql 更新 xml 变量中的 xml 属性值?
【发布时间】:2011-07-17 08:12:55
【问题描述】:

让我们有一个示例 sn-p:

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 的值。

【问题讨论】:

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


    【解决方案1】:
    set @xml.modify('replace value of (/a/@abb)[1] with 344')
    

    在此处阅读有关它的更多信息。 XML Data Modification Language (XML DML)

    【讨论】:

    • 只是想提前询问。我们如何更新所有属性abb 而不仅仅是一个节点?
    • 我已经在stackoverflow.com/questions/5347890/…这里发布了这个问题@
    • 旁注:这仅在以前的值存在时才有效
    【解决方案2】:

    对于那些想要从 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
    

    【讨论】:

      猜你喜欢
      • 2011-07-17
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      相关资源
      最近更新 更多