解析xml时数据丢失

时间:2015-12-30 06:11:46

标签: sql sql-server xml tsql

我在表格中有xml数据,如下所示。

<App action="A" id="1">
<BaseVehicle id="822" />
<!-- 1986 Volvo 740 -->
<EngineBase id="2137" />
<!-- L6 2.4L -->
<Qty>6</Qty>
<PartType id="7152" />
<!-- Diesel Glow Plug -->
<MfrLabel>Diesel Glow Plug</MfrLabel>
<Part>0250201032</Part>

当我使用以下代码解析数据时,我遗漏了1986 Volvo 740L6 2.4L

我试图分别在名为BaseVehicle和PartType的列中提取这些数据。在数据类型VARCHAR下。

可以任何请帮我解决下面代码中的错误

SELECT  ROW_NUMBER() OVER ( ORDER BY one.App.value('@id', 'int') ) AS AppID ,
    1 AS FileID ,
    one.App.value('@action', 'varchar(10)') AS Action ,
    one.App.value('@id', 'int') AS ID ,
    one.App.value('BaseVehicle[1]/@id', 'int') AS BaseVehicleID ,
    **one.App.value('BaseVehicle[1]', 'VARCHAR (100)') AS BaseVehicle ,**
    one.App.value('BodyType[1]/@id', 'int') AS BodyTypeID ,
    one.App.value('BodyType[1]', 'varchar(100)') AS BodyType ,
    one.App.value('Qty[1]', 'int') AS Qty ,
    one.App.value('PartType[1]/@id', 'int') AS PartTypeID ,
    **one.App.value('PartType[1]', 'VARCHAR (100)') AS PartType ,**
    one.App.value(' SubModelID[1]/@id', 'int') AS SubModelID ,
    '<Quals>' + CAST(one.App.query('Qual') AS VARCHAR(MAX)) + '</Quals>' AS QualNodes ,
    '<Notes>' + CAST(one.App.query('Note') AS VARCHAR(MAX)) + '</Notes>' AS NoteNodes ,
    one.App.query('.') AS AppNode

FROM    NETCHANGESource.dbo.tblFile s
        CROSS APPLY s.xmldata.nodes('/ACES/App') AS one ( app );

1 个答案:

答案 0 :(得分:2)

您应该正确准备XML,而不是依赖于评论中的数据。

要阅读评论中的数据,您可以使用comments() XQuery:

DECLARE @xml XML = 
N'<ACES>
    <App action="A" id="1">
      <BaseVehicle id="822" />
      <!-- 1986 Volvo 740 -->
      <EngineBase id="2137" />
      <!-- L6 2.4L -->
      <Qty>6</Qty>
      <PartType id="7152" />
      <!-- Diesel Glow Plug -->
      <MfrLabel>Diesel Glow Plug</MfrLabel>
      <Part>0250201032</Part>
   </App>
 </ACES>';

SELECT  
   one.App.value('comment()[1]', 'nvarchar(1000)') AS comment_1,
   one.App.value('comment()[2]', 'nvarchar(1000)') AS comment_2,
   one.App.value('comment()[3]', 'nvarchar(1000)') AS comment_3
FROM ...

LiveDemo

输出:

╔════════════════╦═══════════╦═══════════════════╗
║   comment_1    ║ comment_2 ║     comment_3     ║
╠════════════════╬═══════════╬═══════════════════╣
║ 1986 Volvo 740 ║ L6 2.4L   ║ Diesel Glow Plug  ║
╚════════════════╩═══════════╩═══════════════════╝