0

I need help parsing this XML in TSQL:

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

I would like to return the values as such:

Capture_Mode_Id        Vehicle_Type
9                      7
1
  • 5
    What is non-standard about the XML in your question? Commented Jan 22, 2014 at 3:29

2 Answers 2

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 |
Sign up to request clarification or add additional context in comments.

Comments

0

You need to perform two logical steps as best I can tell:

  1. Parse the XML - i.e. get a result set from it.
  2. Pivot the result set.

To get a result set from the XML, use the OPENXML function - something like the following...

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));

..., which yields the following results:

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

To pivot the result set without aggregation, consider the ideas presented to this end in a CALSQL blog post.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.