CREATE TABLE [dbo].[Project](
[ProjectId] [int] NOT NULL,
[ProjectName] [nvarchar](255) ,
[ParentProjectId] [int] null,
[ReleaseId] [int]
)
insert into Project values (1, 'Project 1', null, 1)
insert into Project values (2, 'Project 2', null, 1)
insert into Project values (3, 'project 3', 1, 1)
insert into Project values (4, 'project 4', 2, 1)
CREATE TABLE [dbo].[Release](
[ReleaseId] [int] ,
[Name] [nvarchar](255) ,
[ReportingPriority] [int]
)
insert into Release values (1, 'march release', 1)
insert into Release values (2, 'may release', 2)
insert into Release values (3, 'june release', 3)
CREATE TABLE [dbo].[ReleaseSchedule](
[ReleaseScheduleID] [int] ,
[ReleaseID] [int],
[EndDate] [datetime]
)
insert into ReleaseSchedule values (1, 1, '3/1/2010' )
insert into ReleaseSchedule values (2, 2, '5/1/2010' )
insert into ReleaseSchedule values (3, 3, '6/1/2010' )
This is the SQL data I have. From this I need to get a hierarchical XML that resembles this:
<Release Heading="releaseName" id="releaseID" EndDate="date">
<Project Heading="projName" id="projectID">
<SubProject Heading="subprojName" id="projectID"/>
<SubProject Heading="subprojName" id="projectID"/>
</Project>
<Project Heading="releaseName" id="projectID">
<SubProject Heading="subprojName" id="projectID"/>
</Project>
</Release>
Basically the logic is that each release has some projects to it, and projects can be nested with sub-projects (from the project table’s self referencing data)
(note endDate comes from a join between the two release tables.)
Try this query here:
It gives me this output (based on your data provided):
The
FOR XML PATHapproach, introduced in SQL Server 2005, makes it quite easy to define the exact structure of your output XML with elements and attributes, and with theFOR XML PATH(..), TYPEexpression for sub selects, you can easily get nested result sets.Update: for the “duped” projects – maybe you need to add another WHERE clause to your first subquery that selects projects – select only those projects that have no parent (only top-level projects):
Update 2: since I start the selection on the
Releasetable, yes, obviously, projects that aren’t assigned to any release will be left out. However, releases that have no assigned projects ought to show up – can you verify??What doesn’t work right now is having a release that is not assigned to a release schedule – you can easily change that by changing the outer-most query to:
Use
LEFT OUTER JOINto list all releases – even those not assigned to any schedule.Basically, this is all pretty standard SQL query stuff – doesn’t really have anything to do with the XML specific aspects of your question, right??