【问题标题】:Splitting column with XML data使用 XML 数据拆分列
【发布时间】:2015-01-08 11:55:48
【问题描述】:

我有一个名为“details”的 SQL 列,它包含以下数据:

<changes><RoundID><new>8394</new></RoundID><RoundLeg><new>JAYS CLOSE AL6 Odds(1 - 5)</new></RoundLeg><SortType><new>1</new></SortType><SortOrder><new>230</new></SortOrder><StartDate><new>01/01/2009</new></StartDate><EndDate><new>01/01/2021</new></EndDate><RoundLegTypeID><new>1</new></RoundLegTypeID></changes> 
<changes><RoundID><new>8404</new></RoundID><RoundLeg><new>HOLLY AREA AL6 (1 - 9)</new></RoundLeg><SortType><new>1</new></SortType><SortOrder><new>730</new></SortOrder><StartDate><new>01/01/2009</new></StartDate><EndDate><new>01/01/2021</new></EndDate><RoundLegTypeID><new>1</new></RoundLegTypeID></changes>
<changes><RoundID><new>8379</new></RoundID><RoundLeg><new>PRI PARK AL6 (1 - 42)</new></RoundLeg><SortType><new>1</new></SortType><SortOrder><new>300</new></SortOrder><StartDate><new>01/01/2009</new></StartDate><EndDate><new>01/01/2021</new></EndDate><RoundLegTypeID><new>1</new></RoundLegTypeID></changes>

将这些数据分成单独的列的最简单方法是什么? (就是一栏)

【问题讨论】:

  • SQL Server?甲骨文?我的 SQL?其他人?
  • 我使用的是 SQL Server

标签: sql-server xml tsql split


【解决方案1】:

试试这个:

SELECT DATA.query('/changes/RoundID/new/text()')  AS RoundID
      ,DATA.query('/changes/RoundLeg/new/text()') AS RoundLeg
      ,DATA.query('/changes/SortType/new/text()') AS SortType
      -- And so on and so forth
FROM (SELECT CONVERT(XML, Details) AS DATA
      FROM YourTable) AS T

【讨论】:

  • 嗨,这很好,但它仍然保持新的两边,例如: 892 用于圆形 id 和 NAYLORROAD S13 ,你知道吗我怎样才能删除新的
  • @WizTownley 看看this
【解决方案2】:

一旦您从 sql(mysql 或其他)获得结果集,您可能会得到一个字符串数组。据我了解您的问题,您想知道如何提取存储在相关列中的字符串中包含的每个 xml 节点。您可以遍历 sql 查询的结果并提取所需的数据。在 php 中它看起来像这样:

// Set a counter variable for the first dimension of the array, this will 
// number the result sets. So for each row in the table you will have a
// number identifier in the corresponding array.
$i = 0;
$output = array();
foreach($results as $result) {
    $xml = simplexml_load_string($result);
    // Here use simpleXML to extract the node data, just by using the names of the 
    // XML Nodes, and give it the same name in the array's second dimension.
    $output[$i]['RoundID'] =  $xml->RoundID->new;
    $output[$i]['RoudLeg'] = $xml->RoundLeg->new;
    // Simply create more array items here for each of the elements you want 
    $i++;
}

foreach ($output as $out) {
    // Step through the created array do what you like with it.
    echo $out['RoundID']."\n";
    var_dump($out);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2020-08-14
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多