如何在t-sql中循环变量

时间:2014-03-06 06:58:50

标签: sql sql-server tsql sql-server-2005

我有一个t-sql我必须循环变量。

DECLARE @empno  nVARCHAR(MAX),@tableHTML  NVARCHAR(MAX) ;
set @empno  =   (select Employee_No from emptemp where active = 'Yes');
SET @tableHTML =
N'<H2>Additions</H2>' +
N'<table border="1">' +
N'<th>Ename</th>' +
N'<th>Sal</th>' +
'<tr>' +
CAST ( ( select td=ename,'',td=sal,'' from emp Where empno = @empno)
FOR XML PATH('tr'), TYPE  ) AS NVARCHAR(MAX) ) + N'</table>' ;

EXEC msdb.dbo.sp_send_dbmail
@recipients=someone@gmail.com,
@subject = emp ,
@body = @tableHTML , @body_format = 'HTML', 
@profile_name = 'Sql Profile'

Emptemp表格看起来像

id  empno   active
1   245     yes
2   124     yes
3   255     yes
4   224     No

我必须根据emp表中的数据发送单个邮件

1 个答案:

答案 0 :(得分:1)

这就是光标的样子:

DECLARE @empno  nVARCHAR(MAX)
DECLARE @tableHTML  NVARCHAR(MAX) ;
DECLARE @ID INT;
DECLARE Curs CURSOR FAST_FORWARD
FOR
    SELECT DISTINCT  ID
    FROM    dEmptemp 
    WHERE active = 'Yes'
    ORDER BY ID

OPEN Curs

FETCH NEXT FROM Curs INTO @ID

WHILE @@FETCH_STATUS = 0

BEGIN 

set @empno  =   (SELECT empno FROM emptemp WHERE ID = @ID);
SET @tableHTML =
N'<H2>Additions</H2>' +
N'<table border="1">' +
N'<th>Ename</th>' +
N'<th>Sal</th>' +
'<tr>' +
CAST ( ( select td=ename,'',td=sal,'' from emp Where empno = @empno)
FOR XML PATH('tr'), TYPE  ) AS NVARCHAR(MAX) ) + N'</table>' ;

EXEC msdb.dbo.sp_send_dbmail
@recipients=someone@gmail.com,
@subject = emp ,
@body = @tableHTML , @body_format = 'HTML', 
@profile_name = 'Sql Profile'

FETCH NEXT FROM Curs INTO @ID

END

CLOSE Curs 
DEALLOCATE Curs;