0

我有一个数据以 xml 数据类型值存储在其中的字段:

<Inning xmlns="" ID="2866433" Company="Hamfekran">
    <Test ID="rs232lon">
        <Param Name="corel" Value="0.00000" />
        <Param Name="co2rel" Value="10.8000" />
        <Param Name="hcrel" Value="111.000" />
        <Param Name="o2rel" Value="0.95000" />
    </Test>   
    <Test ID="9" Name="CustomData">
        <param Name="TireFront" Value="3.00" />
        <param Name="TireBack" Value="2.00" />
    </Test>
</Inning>

我怎么能得到这样的 TSQL 的结果:

corel       co2rel        hcrel        o2rel     TireFront      TireBack
-----------------------------------------------------------------------------       
0.00000     10.8000       111.000     0.95000       3.00          2.00
4

1 回答 1

0
DECLARE @CocoJambo TABLE (
    ID INT IDENTITY PRIMARY KEY,
    XmlColumn XML NOT NULL
);

INSERT  @CocoJambo (XmlColumn)
VALUES  (N'<Inning xmlns="" ID="2866433" Company="Hamfekran">
    <Test ID="rs232lon">
        <Param Name="corel" Value="0.00000" />
        <Param Name="co2rel" Value="10.8000" />
        <Param Name="hcrel" Value="111.000" />
        <Param Name="o2rel" Value="0.95000" />
    </Test>   
    <Test ID="9" Name="CustomData">
        <param Name="TireFront" Value="3.00" />
        <param Name="TireBack" Value="2.00" />
    </Test>
</Inning>');

SELECT  a.*,
        b.c.value('(Test[@ID="rs232lon"]/Param[@Name="corel"]/@Value)[1]','NUMERIC(38,5)') AS corel,
        b.c.value('(Test[@ID="rs232lon"]/Param[@Name="co2rel"]/@Value)[1]','NUMERIC(38,5)') AS co2rel,
        b.c.value('(Test[@ID="rs232lon"]/Param[@Name="hcrel"]/@Value)[1]','NUMERIC(38,5)') AS hcrel,
        b.c.value('(Test[@ID="rs232lon"]/Param[@Name="o2rel"]/@Value)[1]','NUMERIC(38,5)') AS o2rel,

        b.c.value('(Test[@ID="9"]/param[@Name="TireFront"]/@Value)[1]','NUMERIC(38,5)') AS TireFront,
        b.c.value('(Test[@ID="9"]/param[@Name="TireBack"]/@Value)[1]','NUMERIC(38,5)') AS TireBack
FROM    @CocoJambo a
CROSS APPLY a.XmlColumn.nodes('/Inning') AS b(c)

参考:

SQL Server 中的 XML 方法

nodes() 方法(xml 数据类型)

value() 方法(xml 数据类型)

xml 数据类型方法

于 2013-01-21T22:52:01.263 回答