Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select: Take value from XML field

I'm struggling to pull a value out of an XML field using SQL Select Statement.

The XML field is Info, the table is results.

<Screens>
  <Results>
    <Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse="" 
          DataAction="" DataValue="2" DataScore="0" />
  </Results>
</Screens>

I need to pull the attribute DataValue. For the record above, I'd be looking for 2.

Any help would be greatly appreciated.

like image 777
Colin Edgar Avatar asked Dec 06 '25 21:12

Colin Edgar


1 Answers

With SQL Server it was this:

DECLARE @xml XML=
'<Screens>
  <Results>
    <Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse="" 
          DataAction="" DataValue="2" DataScore="0" />
  </Results>
</Screens>';

SELECT @xml.value('(/Screens/Results/Result/@DataValue)[1]','int') AS DataValue

EDIT: Data comes from a table

Just replace my @tbl with your actual table

--test scenario with two data rows, one has DataValue=2 the other =99
DECLARE @tbl TABLE(ID INT IDENTITY,info XML);
INSERT INTO @tbl(info) VALUES
 (
    '<Screens>
      <Results>
        <Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse="" 
              DataAction="" DataValue="2" DataScore="0" />
      </Results>
    </Screens>'
 )
,(
    '<Screens>
      <Results>
        <Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse="" 
              DataAction="" DataValue="99" DataScore="0" />
      </Results>
    </Screens>'
 );

--this is the query
SELECT info.value('(/Screens/Results/Result/@DataValue)[1]','int') AS DataValue
FROM @tbl

The result is 2 and 99

like image 153
Shnugo Avatar answered Dec 09 '25 15:12

Shnugo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!