从SQL Server中的xml列中提取数据

时间:2015-03-25 16:49:34

标签: sql-server xml

我在SQL Server中有一个填充了以下内容的XML列:

<concession>
  <schema>
    <data schemaItem="title">Re-label to all boards</data>
    <data schemaItem="problem">These boards have been tested</data>
    <data schemaItem="solution">Ask to print new label and add the word "B" on the old serial numbers. so all serial numbers will be modified to new on B .......</data>
    <data schemaItem="justification">Will help UK test resource</data>
    <data schemaItem="liability">Us</data>
    <data schemaItem="parts">
      <part>075</part>
      <part>076</part>
    </data>
    <data schemaItem="products">
      <product>Pdq </product>
    </data>
    <data schemaItem="faultCode">ILB</data>
    <data schemaItem="processCode">MAT</data>
    <data schemaItem="quantity">273</data>
    <data schemaItem="requestedExpiry">14/12/2011</data>
  </schema>
</concession>

如何提取数量值,即:273?

我试过但没有快乐:

SELECT 
    [guid],XMLData, 
    (select xmlData.value('(/concession/schema/data)[1]', 'varchar(100)' )), 
    (select xmlData.value('(/concession/schema/data[schemaItem="quantity"])[0]', 'varchar(100)' ))   
FROM 
    tc_Concession

我得到了标题,但没有数量。

2 个答案:

答案 0 :(得分:1)

尝试使用Outer Apply使用nodes()方法

SELECT
      m.c.value('@schemaItem', 'varchar(max)') as SchemaItem,
      m.c.value('(text())[1]', 'nvarchar(max)') as Value
FROM Yourtablename
    OUTER APPLY xml_data.nodes('concession/schema/data') as m(c)

这将输出为

SchemaItem         Value
title            Re-label to all boards
problem          These boards have been tested
solution         Ask to print new label and add the word "B" on the old serial numbers. so all serial numbers will be modified to new on B .......
justification    Will help UK test resource
liability        Us
parts            NULL
products         NULL
faultCode        ILB
processCode      MAT
quantity         273
requestedExpiry  14/12/2011

答案 1 :(得分:1)

你非常接近。属性名称必须以@开头,索引应该从1开始。您不需要子选择 - .value()方法可以在其上使用。

SELECT 
    [guid],
    XMLData, 
    xmlData.value('(/concession/schema/data)[1]', 'varchar(100)' ),
    xmlData.value('(/concession/schema/data[@schemaItem="quantity"])[1]', 'varchar(100)' )
FROM 
    tc_Concession

如果不保证订购XML,那么您也应该使用第二种方法作为标题。