I've got a very large xml data set that is structured like the following:
<root>
<person>
<personid>HH3269732</personid>
<firstname>John</firstname>
<lastname>Smith</lastname>
<entertime>01/02/2008 10:15</entertime>
<leavetime>01/02/2008 11:45</leavetime>
<entertime>03/01/2008 08:00</entertime>
<leavetime>03/01/2008 10:00</leavetime>
...
// number of enter times and leave times vary from person to person
// there may not be a final leave time (ie, they haven't left yet)
</person>
...
</root>
The structure of the data is not under my control. This data is currently residing in a single xml column in a single row in MS SQL Server 2005. I am trying to construct a query which results in the following output:
HH3269732 John Smith 01/02/2008 10:15 01/02/2008 11:45
HH3269732 John Smith 03/01/2008 08:00 01/02/2008 10:00
HH3269735 Mark Pines 02/01/2008 09:00 NULL
HH3263562 James Frank NULL NULL
HH3264237 Harold White 04/18/2008 03:00 04/18/2008 05:00
...
My query currently looks like the following:
DECLARE @xml xml
SELECT @xml = XmlCol FROM Data
SELECT
[PersonId] = Persons.PersonCollection.value('(personid)[1]', 'NVARCHAR(50)')
,[First Name] = Persons.PersonCollection.value('(firstname)[1]', 'NVARCHAR(50)')
,[Last Name] = Persons.PersonCollection.value('(lastname)[1]', 'NVARCHAR(50)')
??????
FROM @xml.nodes('root\person') Persons(PersonCollection)
That query may not be 100% right as I'm pulling it from memory, but the problem I'm having is that I don't know how to include the entertime leavetime sequence elements in such a way as to get the desired rowset that I indicated above.
Thanks.
UPDATE: I wanted to add that a given person record may have no entertime/leavetime sequence elements at all, but still needs to be returned in the rowset. I have updated the example of the desired output to reflect this.