I saw on a website, a guy had returned his database table information as an html table. It was pretty neat. His code is as follows:
select 2 [@cellpadding]
,2 [@cellspacing]
,1 [@border]
--This returns the header
,(select th
from (select 'Database Table' th
union all
select 'Entity Count'
union all
select 'Total Rows') d --name of this alias is irrelevant but you have to have one
for xml path(''),type) tr --tr here defines that the header row will be a tr element
--This returns the rows in the table
,(select (select dbtable [*] for xml path('td'),type),
(select entities [*] for xml path('td'),type),
(select rows [*] for xml path('td'),type)
from (--We have to use a derived table because we are grouping
select dbtable = object_name( object_id ),
entities = count( distinct name ),
rows = count( * )
from sys.columns
group by object_name( object_id )) data
--name of this alias is irrelevant but you have to have one
for xml path ('tr'),type) --path('tr') turns each row into a tr element
for xml path('table'), type
I would like to see if it is possible to return an html table from one arbitrary SQL Server table. I know that people have differing opinions on whether or not there is a best way to do this, that is not however the point of this question. I am new to SQL and I am just trying to learn my way around it. My code is as follows.
select dataid as [@id], *
from table_1
for xml path('tr'), root('table')
It returns something like:
<table>
<tr id="1">
<column_1>data</column_1>
<column_2>data</column_2>
</tr>
<tr id="2">
<column_1>data</column_1>
<column_2>data</column_2>
</tr>
</table>
I would prefer output like:
<table>
<tr id="1">
<td>data</td>
<td>data</td>
</tr>
<tr id="2">
<td>data</td>
<td>data</td>
</tr>
</table>
Is this doable in an SQL Server Transaction? If so, how would it be done?