如何为以下内容编写SQL Server存储过程?

时间:2012-09-27 04:01:16

标签: html sql stored-procedures

我有一张如下表:

create table testjob
(
   jobid int,  
   jobname varchar(100),  
   time float,  
   name varchar(50)  
)

insert into testjob values ( 1001,'java work',4.5,'arjun')  
insert into testjob values ( 1005,'sql work',10,'arjun')  
insert into testjob values ( 1010,'.net work',7.5,'arjun')  
insert into testjob values ( 1040,'java work',5.5,'ravi')  
insert into testjob values ( 1023,'php work',2.5,'arjun')  
insert into testjob values ( 1027,'.net work',3.5,'ravi')

我想要一个程序,以便我的输出如下所示的html格式如下:

Name: Arjun (24.5 Hrs spent)

jobname Time

java work 4.5  
sql work 10  
.net work 7.5  
php work 2.5    

Name: Ravi(9 Hrs spent)

jobname time

java work 5.5  
.net work 3.5

1 个答案:

答案 0 :(得分:1)

受到thisthis以及this

的启发
--detail template
declare @strDTmp nvarchar(200) = '<td>[job]</td><td>[hrs]</td>' 
--sum template
declare @strSTmp nvarchar(200) = 'Name: [name] ([hrs] Hrs spent)' 
--Table head
declare @strThead nvarchar(200) = '<th>jobname</th><th>Time</th>'

  select 
    replace(replace(@strSTmp,'[name]',name),'[hrs]',stime) h1
    ,(
      select
        tr
      from
        (
        select
          0 pos
          ,name
          ,@strThead tr
        from
          testjob
        group by
          name
        union all
        select
          1 pos
          ,name
          ,replace(replace(@strDTmp,'[job]',jobname),'[hrs]',time) tr
        from
          testjob
        ) t
      where
        t.name = sumtable.name
      order by 
        pos
      FOR XML PATH(''), root('table'), type
      ) 
  from
    (
    select
      name
      ,sum(time) stime
    from
      testjob sumtable
    group by
      name
    ) sumtable
  FOR XML PATH ('')

Test on SQL Fiddle

结果:

<h1>Name: arjun (24.5 Hrs spent)</h1>
<table>
  <tr><th>jobname</th><th>Time</th></tr>
  <tr><td>java work</td><td>4.5</td></tr>
  <tr><td>sql work</td><td>10</td></tr>
  <tr><td>.net work</td><td>7.5</td></tr>
  <tr><td>php work</td><td>2.5</td></tr>
</table>
<h1>Name: ravi (9 Hrs spent)</h1>
<table>
  <tr><th>jobname</th><th>Time</th></tr>
  <tr><td>java work</td><td>5.5</td></tr>
  <tr><td>.net work</td><td>3.5</td></tr>
</table>