SQL将查询内容输出为html表格

时间:2020-12-21 20:11:44
 1 CREATE PROCEDURE [dbo].[QUERY_TABLE](@conn varchar(200),@title varchar(200),@desc varchar(max),@query nvarchar(max),@link_ref nvarchar(max),
 2         @html nvarchar(max) output)
 3 AS
 4 BEGIN
 5     -- SET NOCOUNT ON added to prevent extra result sets from
 6     -- interfering with SELECT statements.
 7     SET NOCOUNT ON;
 8 
 9     -- Insert statements for procedure here
10     -- @link_ref: default delimiter is colon.
11 
12     if object_id('tempdb..##t') is not null drop table ##t
13 
14     declare @exec_query nvarchar(max)
15     set @exec_query='select * into ##t from openrowset(''SQLOLEDB'','''+@conn+''',''SET FMTONLY OFF; SET NOCOUNT ON; '+replace(@query,'''','''''')+''') a'
16     exec sp_executesql @exec_query
17     --select * from ##t
18     if exists(select * from ##t)
19     begin
20     select name as nm,type_name(system_type_id) as tp into #fd from tempdb.sys.all_columns where object_id=object_id('tempdb..##t')
21     --select * from #fd
22     declare @ref table(OKey varchar(max),OValue varchar(max))
23     if len(@link_ref)>0 insert into @ref select distinct * from StringToDic(@link_ref,';',':')
24     --select distinct * into #ref from StringToDic(@link_ref,';',':')
25     declare @th varchar(max)
26     select @th=cast((select [*]=nm from #fd where nm not in (select OValue from @ref) for xml path('th'),type) as nvarchar(max)) 
27     declare @h nvarchar(max),@tr nvarchar(max),@chtml nvarchar(max)
28     select @h=isnull(@h+',','')+case when tp in ('numeric','datetime','int') then '[td_r]' else '[td]' end+'='+
29         case when b.OValue is not null then '''<a href=''''''+'+b.OValue+'+''''''>''+' else '' end+
30         case tp when 'numeric' then 'cast(cast(isnull(['+nm+'],0) as decimal(18,2)) as varchar(max))' 
31             when 'datetime' then 'isnull(convert(varchar(10),['+nm+'],120),'''')' else 'isnull(['+nm+'],'''')' end +
32         case when b.OValue is not null then '+''</a>''' else '' end +',''''' 
33     from #fd a left join @ref b on a.nm=b.OKey where a.nm not in (select OValue from @ref)
34     select @h='select @chtml=cast((select '+@h+' from ##t for xml path(''tr1'')) as nvarchar(max))'
35     --print @h
36     exec sp_executesql @h,N'@chtml nvarchar(max) output',@tr output
37     
38     select @tr=replace(@tr,'<td_r>','<td style="text-align:right">')
39     select @tr=replace(@tr,'</td_r>','</td>')
40     select @tr=replace(@tr,'<tr1>','<tr style="">')
41     select @tr=replace(@tr,'</tr1>','</tr>')
42     select @tr=replace(@tr,'&lt;','<')
43     select @tr=replace(@tr,'&gt;','>')
44 
45     select @html='<h2>'+@title+'</h2><p>'+isnull(@desc,'')+'</p><table rules="all" cellspacing="2" cellpadding="3" border="1"><tr>'+@th+'</tr>'+@tr+'</table>'
46     select @html='<div>'+@html+'</div>'
47     end
48     else
49     select @html='<h2>'+@title+'</h2><p>'+isnull(@desc,'')+'</p><p>No record.</p>'
50 
51 END