如何在HTML上显示SQL Server的结果?

时间:2017-03-07 06:25:15

标签: html sql-server

ID      | Number    | UID                                   | Flag1 | Flag2 
12345   | 5733      | ed2006eb-2340-405e-afec-2b5b4a99ce8a  | NULL  | NULL  
78945   | 599       | f3a784b5-559c-415d-824e-2a55fe2175af  | NULL  | NULL  

1 个答案:

答案 0 :(得分:0)

通过了解表HTML格式的结构: -

<table >
  <tr>
    <th></th>
    <th></th> 
    <th></th>
    <!--... etc th /-->
  </tr>
  <tr>
    <td></td>
    <td></td> 
    <td></td>
    <!--... etc/-->
  </tr>
  <!--

  ...etc tr/

  -->
</table>

通过FOR XML Path模式将SQL查询的正式结果检索为XML,您可以实现所需。

<强>演示: -

CREATE TABLE #Temp 
( 
  EmployeeID   int,
  EmployeeName  varchar(128),
  Salary  int,
  City  varchar(128)
)


INSERT INTO #Temp
SELECT 1,'Ahmed Abdelqader',2000,'Egypt'
UNION ALL
SELECT 2,'Johen Mark',3000,'France'
UNION ALL
SELECT 3,'jito Delfi',4000,'England'


DECLARE @xml NVARCHAR(MAX)
DECLARE @body NVARCHAR(MAX)


SET @xml = CAST(( SELECT EmployeeID AS 'td','',EmployeeName AS 'td','',
       Salary AS 'td','', City AS 'td'
FROM  #Temp ORDER BY EmployeeID 
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))


SET @body ='<html><body>
<table border = 1> 
<tr>
<th> EmployeeID </th> <th> EmployeeName </th> <th> Salary </th> <th> City </th></tr>'    


SET @body = @body + @xml +'</table></body></html>'

select @body

Drop TABLE #Temp

<强>结果: -

<html><body>  <table border = 1>   <tr>  <th> EmployeeID </th> <th> EmployeeName </th> <th> Salary </th> <th> City </th></tr><tr><td>1</td><td>Ahmed Abdelqader</td><td>2000</td><td>Egypt</td></tr><tr><td>2</td><td>Johen Mark</td><td>3000</td><td>France</td></tr><tr><td>3</td><td>jito Delfi</td><td>4000</td><td>England</td></tr></table></body></html>