Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve all values from xml in SQL

I am pretty new in SQL and stuck in a very common scenario. I have a xml with nested child as input parameter in my Stored Procedure

    <XML>
    <Id>1</Id>
    <Age>1</Age>
    <Address>Test</Address>
    .
    .
    <Days>
      <long>1</long>
      <long>2</long>
      <long>3</long>
      <long>7</long>
    </Days>
  </XML>

I am able to pick data inside XML tag through

Id = t.Xml.value('(./Id)[last()]','int')

but I have no idea how to pick all long values inside XML/Days. I tried

 long = t.UserXml.value('.','int')

and it returns all the values as 1237 but this doesn't solve my problem. I needed values in different rows and long values need to be inserted into another table.

Please let me know the possible solutions for the same. Thanks

like image 963
Haseeb Akhtar Avatar asked May 21 '26 08:05

Haseeb Akhtar


1 Answers

Solution for Days on Sqlserver could be

DECLARE @XML XML
SET @XML='<XML>
    <Id>1</Id>
    <Age>1</Age>
    <Address>Test</Address>
    <Days>
      <long>1</long>
      <long>2</long>
      <long>3</long>
      <long>7</long>
    </Days>
  </XML>'

SELECT 
    x.y.value('text()[1]', 'int') as xx
FROM @xml.nodes('XML/Days/long') x(y)
like image 104
bummi Avatar answered May 23 '26 00:05

bummi



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!