keeney
keeney

Reputation: 933

Selecting SQL XML element between Dates

I have some data in an SQL table with an XML datatype column where I need to return a list of elements that fall within a date range. The data looks like this:

folder Table - TBLfolder: id - GUID ClientId = GUID CreatedDate: DateTime contents: xml

the contents xml has a structure like:

<Contents>
  <Files>
   <File id="SOMEGUID">
   <StartDate>2001-11-07</StartDate>
   <EndDate>2062-11-14</EndDate>
   <Type code="jpeg">JPEG</Type>
   <Valid>true</Valid>
   </File>
   <File id="SOMEGUID">
   <StartDate>2012-09-01</StartDate>
   <EndDate>2065-11-14</EndDate>
   <Type code="jpeg">JPEG</Type>
   <Valid>true</Valid>
   </File>
   Files etc......
</Files>
</Contents>

I'm writing this in a stored proc where I pass in a client GUID and a start and end Date I'm after a an xml column containing all files that fall between the date range from the latest folder record:

Here is what I have so far:

Select top 1 folder.contents.query('Contents/File/File
from TBLFolder
where clientID = @clientId
order by CreatedDate desc
For XML PATH ('Files')

What is the best way of filtering the Files node in the xml to only show files that fall between the start and end parameters? I'm new to XML in SQL so unsure of the best way of tackling this.

I've tried a FLOWER statement and predicates on my query but having trouble with the datetime and conversions i've also been getting p1: p2: prefixes appearing on my elements.

the output I'm after is:

<Files>
       <File id="SOMEGUID">
       <StartDate>2001-11-07</StartDate>
       <EndDate>2062-11-14</EndDate>
       <Type code="jpeg">JPEG</Type>
       <Valid>true</Valid>
       </File>
       <File id="SOMEGUID">
       <StartDate>2012-09-01</StartDate>
       <EndDate>2065-11-14</EndDate>
       <Type code="jpeg">JPEG</Type>
       <Valid>true</Valid>
       </File>
       Files etc......
    </Files>

Upvotes: 1

Views: 845

Answers (1)

Royi Namir
Royi Namir

Reputation: 148524

DECLARE @x XML 
SET @x='<Files>
       <File id="SOMEGUID">
       <StartDate>2001-11-07</StartDate>
       <EndDate>2062-11-14</EndDate>
       <Type code="jpeg">JPEG</Type>
       <Valid>true</Valid>
       </File>
       <File id="SOMEGUID">
       <StartDate>2001-11-08</StartDate>
       <EndDate>2065-11-14</EndDate>
       <Type code="jpeg">JPEG</Type>
       <Valid>true</Valid>
       </File>
        <File id="SOMEGUID">
       <StartDate>2001-11-19</StartDate>
       <EndDate>2065-11-14</EndDate>
       <Type code="jpeg">JPEG</Type>
       <Valid>true</Valid>
       </File>
    </Files>'

    edited...

    SELECT @x.query('
for $i in /Files/File
where $i/StartDate < ''2001-11-19''
return $i
') as Resu 

will produce :

enter image description here

Upvotes: 1

Related Questions