Search code examples
sqlsql-serverxmlsqlxml

SELECT XML FROM TABLE IN SQL SERVER


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...


Solution

  • 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]