如何在SQL IF EXISTS中设置两个变量

时间:2015-03-12 08:59:10

标签: sql-server-2008

我需要在IF EXISTS语句中设置两个变量。首先更改电子邮件的主题,另一个是更改收件人列表。请帮忙.. Thanx

SET DATEFORMAT mdy;
GO
DECLARE @datevar date = getdate();
DECLARE @subjectCheck AS NVARCHAR(MAX);
DECLARE @email AS NVARCHAR(MAX);


IF EXISTS (SELECT CurrentDate from LOG_SHIP_CHECK WHERE CurrentDate = @datevar)
 SET @subjectCheck = 'Check LogShip: Success'
 SET @email = 'recipient1@server.com'
 ELSE
SET @subjectCheck = 'Check LogShip: Failure'; @email = 'recipient2@server.com'
DECLARE @tableHTML  NVARCHAR(MAX) ;

SET @tableHTML =
    N'<H1>Ezis Raadpleeg</H1>' + 
    N'<table border="1">' +
    N'<th>Datum</th></tr>' +
    CAST ( ( SELECT td = CurrentDate 
              FROM LOG_SHIP_CHECK 
             FOR XML PATH('tr'), TYPE 
    ) AS NVARCHAR(MAX) ) +
    N'</table>' ;

EXEC msdb.dbo.sp_send_dbmail @profile_name = 'ProfileName', @recipients=@email,
    @subject = @subjectCheck,
    @body = @tableHTML,
    @body_format = 'HTML' ;

2 个答案:

答案 0 :(得分:0)

BEGIN语句后尝试ENDIF语句,并使用SELECT代替SET。像这样的东西,

IF EXISTS (SELECT CurrentDate from LOG_SHIP_CHECK WHERE CurrentDate = @datevar)
BEGIN
 SELECT @subjectCheck = 'Check LogShip: Success', @email = 'recipient1@server.com'
END
 ELSE
BEGIN
  SELECT @subjectCheck = 'Check LogShip: Failure', @email = 'recipient2@server.com'

END

答案 1 :(得分:0)

IF EXISTS (SELECT CurrentDate from LOG_SHIP_CHECK WHERE CurrentDate = @datevar)
BEGIN
 SET @subjectCheck = 'Check LogShip: Success';
 SET @email = 'recipient1@server.com';
END
ELSE
BEGIN
 SET @subjectCheck = 'Check LogShip: Failure';
 SET @email = 'recipient2@server.com';
END