在SQL中解析非标准XML

时间:2014-01-22 02:28:57

标签: sql-server xml tsql

我需要帮助在TSQL中解析这个XML:

<Settings>
    <Setting ERName="CAPTURE_MODE_ID" Value="9" />
    <Setting ERName="VEHICLE_TYPE" Value="7" />
</Settings>

我想这样返回值:

Capture_Mode_Id        Vehicle_Type
9                      7

2 个答案:

答案 0 :(得分:1)

SQL Fiddle

declare @XML xml

set @XML = '
<Settings>
 <Setting ERName="CAPTURE_MODE_ID" Value="9" />
 <Setting ERName="VEHICLE_TYPE" Value="7" />
</Settings>'

select @XML.value('(/Settings/Setting[@ERName = "CAPTURE_MODE_ID"]/@Value)[1]', 'int') as CAPTURE_MODE_ID,
       @XML.value('(/Settings/Setting[@ERName = "VEHICLE_TYPE"]/@Value)[1]', 'int') as VEHICLE_TYPE

<强> Results

| CAPTURE_MODE_ID | VEHICLE_TYPE |
|-----------------|--------------|
|               9 |            7 |

答案 1 :(得分:0)

我需要尽可能地执行两个逻辑步骤:

  1. 解析XML - 即从中获取结果集。
  2. 旋转结果集。
  3. 要从XML获取结果集,请使用OPENXML function - 类似以下内容......

    DECLARE @idoc int, @doc varchar(1000);
    
    -- the XML document
    SET @doc ='
    <ROOT>
    <Settings>
        <Setting ERName="CAPTURE_MODE_ID" Value="9" />
        <Setting ERName="VEHICLE_TYPE" Value="7" />
    </Settings>
    </ROOT>';
    
    -- Create an internal representation of the XML document.
    EXEC sp_xml_preparedocument @idoc OUTPUT, @doc;
    
    -- Execute a SELECT statement that uses the OPENXML rowset provider.
    SELECT *
    FROM OPENXML (@idoc, '/ROOT/Settings/Setting', 1)
        WITH (ERName varchar(20), Value varchar(20));
    

    ...,产生以下结果:

    ERName                 Value
    ---------------        -----
    CAPTURE_MODE_ID        9
    VEHICLE_TYPE           7
    

    要在没有聚合的情况下旋转结果集,请考虑在CALSQL blog post中为此目的提出的想法。