Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create HTML Table with SQL FOR XML

I'm creating a HL7 Continuity of Care Document (CCD) using FOR XML statements in SQL Server 2008 R2.

I've done A LOT with this method, but this is the first time I have to represent part of the data in a HTML table, which is giving me trouble.

So, I have the following information in a table:

  Problem  |   Onset    | Status ---------------------------------   Ulcer    | 01/01/2008 | Active   Edema    | 02/02/2005 | Active 

and I'm trying to render the following

<tr>     <th>Problem</th>     <th>Onset</th>     <th>Status</th> </tr> <tr>     <td>Ulcer</td>     <td>01/01/2008</td>     <td>Active</td> </tr> <tr>     <td>Edema</td>     <td>02/02/2005</td>     <td>Active</td> </tr> 

I'm using this query:

SELECT    p.ProblemType AS "td"     , p.Onset AS "td"     , p.DiagnosisStatus AS "td" FROM tblProblemList p WHERE p.PatientUnitNumber = @PatientUnitNumber FOR XML PATH('tr') 

And I keep getting the following:

<tr>   <td>Ulcer2008-01-01Active</td> </tr> <tr>   <td>Edema2005-02-02Active</td> </tr> 

Anyone got any advice?

like image 494
David Walker Avatar asked Aug 16 '11 23:08

David Walker


1 Answers

select    (select p.ProblemType     as 'td' for xml path(''), type),   (select p.Onset           as 'td' for xml path(''), type),   (select p.DiagnosisStatus as 'td' for xml path(''), type) from tblProblemList p where p.PatientUnitNumber = @PatientUnitNumber for xml path('tr') 

To add the header as well you can use union all.

select    (select 'Problem' as th for xml path(''), type),   (select 'Onset'   as th for xml path(''), type),   (select 'Status'  as th for xml path(''), type) union all          select    (select p.ProblemType     as 'td' for xml path(''), type),   (select p.Onset           as 'td' for xml path(''), type),   (select p.DiagnosisStatus as 'td' for xml path(''), type) from tblProblemList p where p.PatientUnitNumber = @PatientUnitNumber for xml path('tr') 
like image 131
Mikael Eriksson Avatar answered Sep 20 '22 23:09

Mikael Eriksson