我正在开发一个sql server数据库邮件发送任务,其中邮件正文应该是HTML。 数据必须从两个不同的表中提取。
实施例
表-1 [临时表 - 行继续添加]
ID Name C_Name
1 john Mumbai
2 Adam pune
3 Kevin Delhi
表-2 [静态表,配置类型]
FieldID FieldName FieldOrder
1 CustomerName 1
2 City 2
我期望的HTML邮件正文是:
<table >
<tr>
<td>
CustomerName</td>
<td>
john</td>
<td>
Adam</td>
<td>
Kevin</td>
</tr>
<tr>
<td>
City</td>
<td>
Mumbai</td>
<td>
pune</td>
<td>
Delhi</td>
</tr>
Table rows continues....
</table>
HTML表格设计:
CustomerName John Adam Kevin
City Mumbai Pune Delhi
为优化查询而苦苦挣扎,请建议。
答案 0 :(得分:0)
尝试此查询
create table #temp (
ID int, Name nvarchar(20), C_Name nvarchar(20))
insert into #temp select
1 , 'john' , 'Mumbai'
insert into #temp select
2 , 'Adam' , 'pune'
insert into #temp select
3 , 'Kevin' , 'Delhi'
DECLARE @Message as NVARCHAR(MAX)= '<table><tr><td>CustomerName</td>'
set @message = @Message +(
SELECT top(1) names = STUFF((
SELECT ' <td>' + name + '</td>'FROM #temp
FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 1, '')
FROM #temp AS x)
SET @Message = @Message + '</tr><tr><td>City</td>'
set @Message = @Message + (
SELECT top(1) Cities = STUFF((
SELECT ' <td>' + #temp .C_Name + '</td>'FROM #temp
FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 1, '')
FROM #temp AS x)
SET @Message = @Message + '</tr></table>'
select @Message
drop table #temp
答案 1 :(得分:0)
尝试使用这样的游标。
DECLARE @Name nvarchar(50)
DECLARE @City nvarchar(50)
DECLARE @Row1 nvarchar(4000)
DECLARE @Row2 nvarchar(4000)
SET @Row1 = '<tr><td>Customer Name</td>'
SET @Row2 = '<tr><td>City</td>'
DECLARE db_cursor CURSOR FOR
SELECT Name, C_Name
FROM Table1
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @Name, @City
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Row1 = @Row1 + '<td>' + @Name + '</td>'
SET @Row2 = @Row2 + '<td>' + @City + '</td>'
END
CLOSE db_cursor
DEALLOCATE db_cursor
SET @Row1 = @Row1 + '</tr>'
SET @Row2 = @Row2 + '</tr>'
SELECT '<table>' + @Row1 + @Row2 + '</table>'