在SQL Server中使用XML命名空间提取XML列的datav值

时间:2014-01-09 21:59:40

标签: sql sql-server xml xml-namespaces xml-column

任何人都可以帮我用下面的xml。我需要提取所有的xml值,如下所示。

AwarYear   Comments                         FieldCode   FieldNumber  Key    Value
AY2013-14  AAI: Adjusted Available Income   AAI            306       Blank  None Calculated

以下是XML示例。

<SchemaType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/process">
  <AwardYear>AY2013_14</AwardYear>
  <Fields>
    <FieldSchema>
      <Comments>AAI: Adjusted Available Income</Comments>
      <DbLocation>IsirData</DbLocation>
      <FieldCode>AAI</FieldCode>
      <FieldNumber>306</FieldNumber>
      <ReportDisplay>Data</ReportDisplay>
      <ValidContent>
       <ValidValueContent xmlns:d5p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
          <d5p1:KeyValueOfstringstring>
            <d5p1:Key>Blank</d5p1:Key>
            <d5p1:Value>None calculated</d5p1:Value>
          </d5p1:KeyValueOfstringstring>
        </ValidValueContent>
      </ValidContent>
    </FieldSchema>
      </Fields>
</SchemaType>

请充分满足需求。提前致谢。

1 个答案:

答案 0 :(得分:4)

假设您在XML列的表格中包含XML,如下所示:

DECLARE @XmlTable TABLE (ID INT NOT NULL, XMLDATA XML)

INSERT INTO @XmlTable VALUES(1, '<SchemaType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/process">
  <AwardYear>AY2013_14</AwardYear>
  <Fields>
    <FieldSchema>
      <Comments>AAI: Adjusted Available Income</Comments>
      <DbLocation>IsirData</DbLocation>
      <FieldCode>AAI</FieldCode>
      <FieldNumber>306</FieldNumber>
      <ReportDisplay>Data</ReportDisplay>
      <ValidContent>
       <ValidValueContent xmlns:d5p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
          <d5p1:KeyValueOfstringstring>
            <d5p1:Key>Blank</d5p1:Key>
            <d5p1:Value>None calculated</d5p1:Value>
          </d5p1:KeyValueOfstringstring>
        </ValidValueContent>
      </ValidContent>
    </FieldSchema>
      </Fields>
</SchemaType>')

然后您可以使用此T-SQL语句来获取值:

;WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/process', 
                    'http://schemas.microsoft.com/2003/10/Serialization/Arrays' AS ns1)
SELECT
    AwardYear = XmlData.value('(SchemaType/AwardYear)[1]', 'varchar(25)'),
    Comments = XmlData.value('(SchemaType/Fields/FieldSchema/Comments)[1]', 'varchar(50)'),
    FieldCode = XmlData.value('(SchemaType/Fields/FieldSchema/FieldCode)[1]', 'varchar(10)'),
    FieldNumber = XmlData.value('(SchemaType/Fields/FieldSchema/FieldNumber)[1]', 'int'),
    [Key] = XmlData.value('(SchemaType/Fields/FieldSchema/ValidContent/ValidValueContent/ns1:KeyValueOfstringstring/ns1:Key)[1]', 'varchar(10)'),
    [Value] = XmlData.value('(SchemaType/Fields/FieldSchema/ValidContent/ValidValueContent/ns1:KeyValueOfstringstring/ns1:Value)[1]', 'varchar(10)')
FROM
    @XmlTable

我将顶级XML命名空间定义为“默认”命名空间(不需要在整个地方引用),并且结构内部的第二个命名空间使用单独的XML命名空间前缀显式定义。