I need to export data from a table in the following XML format:
<studentid="000011111">
<academic_goal type="official">
<program_group>
<program type="catalog">2014-16</program>
<program type="degree">BS</program>
<program type="major">PS</program>
<program type="concentration">PCC</program>
</program_group>
<program_group>
<program type="catalog">2014-16</program>
<program type="degree">BS</program>
<program type="minor">HI</program>
</program_group>
</academic_goal>
</studentid>
So far what I have is:
<studentid="000011111">
<academic_goal type="official">
<program_group>
<program type="catalog">2014-16</program>
<program type="degree">BS</program>
<program type="major">PS</program>
<program type="minor">HI</program>
<program type="concentration">PCC</program>
</program_group>
</academic_goal>
</studentid>
How can I loop through this information so that the minor is within its own program_group
tag (along with catalog and degree)?
Here's the table structure:
CREATE TABLE [dbo].[StudentProgramData](
[StudentID] [nvarchar](10) NULL,
[Catalog] [nvarchar](10) NULL,
[Degree] [nvarchar](10) NULL,
[Major] [nvarchar](50) NULL,
[Minor] [nvarchar](50) NULL,
[Concentration] [nvarchar](50) NULL)
Sample data:
insert into StudentProgramData
values
('000011111', '2014-16', 'BS', 'PS', 'HI', 'PCC'),
('000022222', '2012-14', 'BA', 'MK', 'BI', 'ESO'),
('000033333', '2012-14', 'BS', 'MB', NULL, 'AUE'),
('000044444', '2014-16', 'ME', 'PS', 'HI', NULL),
('000055555', '2010-12', 'MD', 'PS', NULL, 'PCC')
I included 5 sample records, but my output above only shows the first student.
My code so far for the loop is:
(select
ltrim(rtrim(StudentProgramData.catalog)) as [program/@catalog],
ltrim(rtrim(StudentProgramData.degree)) as [program/@degree],
ltrim(rtrim(StudentProgramData.major)) as [program/@major],
ltrim(rtrim(StudentProgramData.minor)) as [program/@minor],
ltrim(rtrim(StudentProgramData.concentration)) as [program/@concentration]
from StudentProgramData
for xml path('program'), type).query('
<academic_goal type="official">
{
for $program in /program
return
<program_group>
{$program/Name}
<program type="catalog">{data($program/program/@year)}</program>
<program type="degree">{data($program/program/@degree)}</program>
<program type="major">{data($program/program/@major)}</program>
<program type="minor">{data($program/program/@minor)}</program>
<program type="concentration">{data($program/program/@concentration)}</program>
</program_group>
}
</academic_goal>')
Any help you could provide is very much appreciated.