【问题标题】:How to check Xml Element's Attribute Value in SQL如何在 SQL 中检查 Xml 元素的属性值
【发布时间】:2021-01-04 03:29:20
【问题描述】:

我想选择除 InEx 值为“已排除”的元素以外的元素。

这是我的 XML 文档:

<MachineStatus>
<ShiftStop  MachineName="01" InEx="Excluded" />
<ShiftStop  MachineName="01" InEx="Included"  />
<ShiftStop  MachineName="01" InEx="Included"  />
  </MachineStatus>

我需要得到

<ShiftStop  MachineName="01" InEx="Included"  />
<ShiftStop  MachineName="01" InEx="Included"  />

我试过这个查询,但它不起作用。

SELECT [Entity].query('/MachineStatus/ShiftStop') FROM [FES].[SMD].[Machine] WHERE 
[Entity].value('(/MachineStatus/ShiftStop/@InEx)[1]','varchar(10)') != 'Excluded'

【问题讨论】:

    标签: sql-server xml xpath xpathquery


    【解决方案1】:

    当从 XML 中提取值时,它会“撕掉”整个标签,它会提取元素。如果要提取值,然后取回 XML 数据,则必须重新构建 XML:

    CREATE TABLE dbo.YourTable (ID int IDENTITY,
                                YourXML xml);
    INSERT INTO dbo.YourTable (YourXML)
    VALUES('<MachineStatus>
    <ShiftStop  MachineName="01" InEx="Excluded" />
    <ShiftStop  MachineName="01" InEx="Included"  />
    <ShiftStop  MachineName="01" InEx="Included"  />
    </MachineStatus>');
    
    SELECT YT.ID,
           (SELECT MS.SS.value('@MachineName','char(2)') AS [ShiftStop/@MachineName],
                   MS.SS.value('@InEx','varchar(8)') AS [ShiftStop/@InEx]
            FROM YT.YourXML.nodes('MachineStatus/ShiftStop')MS(SS)
            WHERE MS.SS.value('@InEx','varchar(8)') != 'Excluded'
            FOR XML PATH(''),TYPE)
    FROM dbo.YourTable YT;
    
    GO
    
    DROP TABLE.dbo.YourTable;
    

    【讨论】:

      猜你喜欢
      • 2012-10-06
      • 1970-01-01
      • 2017-12-23
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多