0

我正在处理一个 sql server DB 邮件发送任务,其中邮件正文应为 HTML。必须从两个不同的表中提取数据。

前任。

表-1[Staging table-Rows不断增加]

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

为优化查询而苦苦挣扎,请提出建议。

4

2 回答 2

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>'
于 2013-07-29T09:06:36.000 回答
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 
于 2013-07-28T07:29:12.927 回答