1

データを SQL Server テーブルに収集しながら、いくつかの XML ファイルをインポートしました。

この XML データ列にクエリを実行して、単一の XML 列をより構造化されたテーブルに変換する必要があります。

XML構造にはパターンがあるため、SQL XML.query形式で理解すると、必要なすべての要素に対して簡単に繰り返すことができます。

Select TOP 1
   [XMLFILE].value('(/Objs/Obj[0]/TN)[0]','VARCHAR(MAX)') as TEST,
   [XMLFILE].query('/Objs/Obj') as HEADERTEST,
   [XMLFILE].query('/Ref[@id="0"]')  as Property1
FROM 
   SQL_Table

上記は、試行するすべてのパターンに対して空の文字列を返すだけです。

各 obj [] 要素の名前と値を抽出する必要があります。

XML 構造の例。つまり、objs ヘッダーの後に 0 から 'x' ノードまでの obj ノードが続きます。

<?xml version="1.0"?>
<Objs xmlns="xxxx" Version="1.1.0.1">
  <Obj RefId="0">
    <TN RefId="0">
      <T>xxxx/T>
      <T>xxxxx</T>
      <T>xxxx</T>
    </TN>
    <MS>
      <S N="Name">xxxx</S>
      <S N="Value">xxxx</S>
    </MS>
  </Obj>
  <Obj RefId="1">
    <TNRef RefId="0"/>
    <MS>
      <S N="Name">xxxxxx</S>
      <S N="Value"/>
    </MS>
  </Obj>
  <Obj RefId="2">
    <TNRef RefId="0"/>
    <MS>
      <S N="Name">xxxxx</S>
      <S N="Value"/>
    </MS>
  </Obj>
  <Obj RefId="3">
    <TNRef RefId="0"/>
    <MS>
      <S N="Name">xxxx</S>
      <S N="Value"/>
    </MS>
  </Obj>
......
......
</Objs>
4

1 に答える 1

0

Couple of problems:

  1. you're not respecting the XML namespace defined on your XML top level node
  2. you're not getting the appropriate nodes from your XML

Try this:

-- replace the 'xxx' with whatever is really defined in your <Objs xmlns=....> 
;WITH XMLNAMESPACES(DEFAULT 'xxxx')  
SELECT
    RefId = xc.value('@RefId', 'int'),
    Name = xc.value('(MS/S[@N="Name"])[1]', 'varchar(20)'),
    Value = xc.value('(MS/S[@N="Value"])[1]', 'varchar(20)')
FROM 
   SQL_Table
CROSS APPLY
    XmlFile.nodes('/Objs/Obj') AS XT(XC)

The CROSS APPLY generates an on-the-fly virtual table of XML fragments for each XML node that matches the XPath expression - here, for each <Obj> node under <Objs>.

The XQuery method .value() then "reaches" into that XML fragment (for each of the fragements in that virtual table) and pulls out the necessary desired info - here the RefId attribute on the <Obj> node, as well as the textual value of the <MS>/<S N="Name"> and <MS>/<S N="Value"> subnodes.

于 2014-06-04T17:24:54.497 に答える