SQL TO THML TABLE

经常用到存储过程,发邮件给用户,这样写,可以节省大量的SQL
拼接字符串

--写法1
SELECT '<table>' + CAST((SELECT TOP 100 
       td=lngEmployeeID ,''
      ,td=strEmployeeCode, '' 
      ,td=strEmployeeName,'' 
from Syn_Employee 
for XML PATH('tr'), TYPE) AS  nvarchar(MAX)) + '</table>'

--写法2
SELECT '<table>' + CAST((SELECT  TOP 10 * from Syn_Employee FOR XML PATH('tr'), TYPE).query('
   for $item in /tr
   return
     <tr>
      <td>{ $item/lngEmployeeID/text() }</td>
      <td>{ $item/strEmployeeCode/text() }</td>
      <td>{ $item/strEmployeeName/text() }</td>
     </tr>
') AS NVARCHAR(MAX)) + '</table>' as Result;


--demo 3
SELECT CONVERT(NVARCHAR(MAX), '<html><head><META content="text/html;"></head>
<body>
<style>
table,td { margin: 0; padding: 0; border: 1px solid #CCC; border-collapse: collapse; font: small/1.5 "Tahoma", "Bitstream Vera Sans", Verdana, Helvetica, sans-serif; }
table { white-space: nowrap; border: none; border: 1px solid #CCC; }
thead th, tbody th { background: #FFF; color: #000; padding: 2px 4px; border-left: 1px solid #CCC; }
tbody th { background: #fafafb; border-top: 1px solid #CCC; text-align: center; font-weight: normal; }
tbody tr td { padding: 0px 4px; color: #000; }</style>'+(SELECT

    (SELECT '表头' FOR XML PATH(''), TYPE) AS 'caption',
    (SELECT '列1' AS th, '列2' AS th FOR XML RAW('tr'), ELEMENTS, TYPE) AS 'thead',
    (
        SELECT TOP 10 lngEmployeeID AS td,strEmployeeName AS td from Syn_Employee 

    FOR XML RAW('tr'), ELEMENTS, TYPE
    ) AS 'tbody'
  FOR XML PATH(''), ROOT('table'))+'</body></html>');

参考1

参考2

更多高级写法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值