我受到以下任务的挑战。
这是我的问题:我需要从SQL Server发送带有HTML表格格式的电子邮件,电子邮件正文将有几个表格。
查询将来自数据库,如
SELECT Field1, Field2, Field3
FROM Table
WHERE DateField >= Somedate
Field3
将是分隔表的因素,因此,结果将按Field3
值分组并放在单独的表中
电子邮件内容或多或少与以下内容相同(已附上屏幕截图)
Section: Field3 Value1
Field Field2 Field3
1 AA Value1
2 BB Value1
3 CC Value1
Section: Field3 Value2
Field Field2 Field3
1 OO Value2
2 XX Value2
3 VV Value2
Section: Field3 Value3
Field Field2 Field3
1 qwqw Value3
2 GGGG Value3
3 COCO Value3
我已经尝试了游标,但是,它只会返回其中一个表(基于第一个FETCH值)。任何帮助表示赞赏
答案 0 :(得分:1)
使用函数I provide here可以执行此操作:
DECLARE @tbl TABLE(Field1 INT, Field2 VARCHAR(10), Field3 VARCHAR(10));
INSERT INTO @tbl VALUES
(1,'AA','Value1')
,(2,'BB','Value1')
,(3,'CC','Value1')
,(1,'OO','Value2')
,(2,'XX','Value2')
,(3,'VV','Value2')
,(1,'qwqw','Value3')
,(2,'GGGG','Value3')
,(3,'COCO','Value3');
- 查询会将其构建为一个大的XHTML
SELECT (SELECT N'Section: Field3="Value1"' AS p FOR XML PATH(''),TYPE)
,dbo.CreateHTMLTable
(
(SELECT * FROM @tbl WHERE Field3='Value1' FOR XML PATH('row'), ELEMENTS XSINIL)
,NULL,NULL,NULL
)
,(SELECT N'Section: Field3="Value2"' AS p FOR XML PATH(''),TYPE)
,dbo.CreateHTMLTable
(
(SELECT * FROM @tbl WHERE Field3='Value2' FOR XML PATH('row'), ELEMENTS XSINIL)
,NULL,NULL,NULL
)
,(SELECT N'Section: Field3="Value3"' AS p FOR XML PATH(''),TYPE)
,dbo.CreateHTMLTable
(
(SELECT * FROM @tbl WHERE Field3='Value3' FOR XML PATH('row'), ELEMENTS XSINIL)
,NULL,NULL,NULL
)
FOR XML PATH('body'),ROOT('html');
这是结果(点击运行代码段查看格式化的结果)
<html>
<body>
<p>Section: Field3="Value1"</p>
<table>
<thead>
<tr>
<th>Field1</th>
<th>Field2</th>
<th>Field3</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>AA</td>
<td>Value1</td>
</tr>
<tr>
<td>2</td>
<td>BB</td>
<td>Value1</td>
</tr>
<tr>
<td>3</td>
<td>CC</td>
<td>Value1</td>
</tr>
</tbody>
</table>
<p>Section: Field3="Value2"</p>
<table>
<thead>
<tr>
<th>Field1</th>
<th>Field2</th>
<th>Field3</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>OO</td>
<td>Value2</td>
</tr>
<tr>
<td>2</td>
<td>XX</td>
<td>Value2</td>
</tr>
<tr>
<td>3</td>
<td>VV</td>
<td>Value2</td>
</tr>
</tbody>
</table>
<p>Section: Field3="Value3"</p>
<table>
<thead>
<tr>
<th>Field1</th>
<th>Field2</th>
<th>Field3</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>qwqw</td>
<td>Value3</td>
</tr>
<tr>
<td>2</td>
<td>GGGG</td>
<td>Value3</td>
</tr>
<tr>
<td>3</td>
<td>COCO</td>
<td>Value3</td>
</tr>
</tbody>
</table>
</body>
</html>
嵌入<style>
节点以添加CSS格式
在上面提供的链接中找到更多可能性和背景......