2

I have XML stored in my table. This table has columns id type int, and value type XML. I'm using SQL Server 2012.

XML looks like this:

 <?xml version="1.0" encoding="utf-16"?>
 <Weather>
 <Forecast>
 <Description>sky is clear</Description>
 <Date>6.9.2013 23:50:36</Date>
 <MinTemp>13</MinTemp>
 <MaxTemp>13</MaxTemp>
 <Pressure>995</Pressure>
 <Humidity>68</Humidity>
 </Forecast>
 </Weather>

This XML can have up to then Forecast parts. How can I with simple SELECT statement get for instance Humidity value?

I have been trying several thins I found here, but I keep getting NULL so that's the reason I'm asking this question. Please help...

2
  • Check this similar question Select values from XML field in SQL Server 2008. It might be helpful. Commented Sep 9, 2013 at 19:04
  • If you share some of the queries tried, someone might be able to identify a mistake, etc. that causes your issue. Commented Sep 9, 2013 at 19:04

2 Answers 2

2

If you have more than one Forecast in your xml, use nodes function:

select
    id, d.c.value('Humidity[1]', 'bigint') as Humidity
from test as t
    outer apply t.Data.nodes('Weather/Forecast') as d(c)

sql fiddle demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Wish I could accept two answers, but can't. So Vote up!
1

Try like this:-

select
  columnname
from
  MyTable
where
  columnname.value('(/Weather/Forecast)[1]', 'varchar(max)') like 'StringToSearchFor'

or as suggested in this link like this:-

SELECT 
[xmlField].value('(/Weather//Forecast/Description/node())[1]', 'nvarchar(max)') as columname
FROM [myTable]

3 Comments

Thanks, really helped a lot! I was so close but couldn't find mistake. THANKS!
Can you please tell me what to do if I have XML that has 10 Forecast parts? I started using SQL few days ago so everything is new for me...
You have to specify nodes for all the 10 forecast parts!!

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.