sql server - MIN of XML descendats of date type -


how can query min date of descendants in xml field. this:

declare @xml xml =' <plan>     <effectivedate>2006-01-01</effectivedate>     <effectivedate>2016-09-14</effectivedate>     <effectivedate>2016-09-14</effectivedate>     <effectivedate>2016-09-14</effectivedate> </plan>'  select @xml.value('min(descendant::effectivedate)','varchar(max)') mindate     ,@xml.value('count(descendant::effectivedate)','varchar(max)') countdate 

unfortunately above returns null min

the default datatype untyped xml node values xdt:untypedatomic. min function (xquery) try convert xdt:untypedatomic values xs:double , return min value. values can not converted xs:double min() return min value of 4 null values.

since min() works fine on xs:date can first convert values xs:date , min() on date values.

declare @xml xml = ' <plan>     <effectivedate>2006-01-01</effectivedate>     <effectivedate>2016-09-14</effectivedate>     <effectivedate>2016-09-14</effectivedate>     <effectivedate>2016-09-14</effectivedate> </plan>';  select @xml.value('min(for $n in descendant::effectivedate/text()                         return $n cast xs:date?)', 'date'),        @xml.value('count(descendant::effectivedate)', 'int'); 

Comments