如何在仅添加新记录时发送

时间:2017-09-26 03:22:07

标签: sql sql-server tsql ssis

我有这样的样本数据

empid   ename   sal
-----------------------
1       raj      1000
2       somu    20000

当我运行此查询时,它将使用SSIS或SQL Server加载到表中,我需要使用SEND MAIL TASK或sp_dbsendmail发送邮件,我会处理该邮件。

查询将每两小时通过Job运行一次。

当它被加载到表格中时,它将以表格格式发送邮件,表示它在2小时后再次有2条记录,它只有2条记录,不需要发送邮件,如果有任何额外的记录需要发送邮件

    empid   ename   sal
    ---------------------
    1       raj      1000
    2       somu    20000
    3       Mohan    2000

该作业将每2小时运行一次只发送邮件,如果它有新记录,否则无需发送...任何想法,请你建议

2 个答案:

答案 0 :(得分:0)

我建议你这样做。修改表并添加新列:

ALTER TABLE employee ADD processed DATETIME NULL

此列将包含上次运行的日期/时间

为了获取未处理记录的工作,请执行以下操作:

DECLARE @now DATETIME
SET @now = GetDate()

UPDATE employee SET processed = @now WHERE processed IS NULL

DECLARE @email VARCHAR(MAX)
SELECT @email = COALESCE(@email + '<br>', '') + 
                empid + ',' +  ename + ',' + CONVERT(VARCHAR(20), sal)
FROM employee
where processed = @now
order by empid

print email
--SEND mail

答案 1 :(得分:0)

正如cha建议在你的表中添加一个日期列,你就可以了。

此代码将在您的电子邮件正文中发送查询结果。

如果您希望作为附件发送,请从代码中取消注释“取消注释!!! ”行。

-- count how many new records you have in the table based on date column
DECLARE @count AS int
SELECT @count = COUNT(empid) FROM MyTbl WHERE processed IS NULL

-- if you have new records -> send email otherwise no
IF @count > 0
BEGIN
    DECLARE @subject varchar(50) = 'Your subject ... '
    DECLARE @Query varchar(max)
    DECLARE @recipients varchar(155)
    DECLARE @body varchar(155)
    --DECLARE @tab char(1) = CHAR(9) -- uncomment this!!!


    SET @recipients = 'email@co.uk'
    SET @body = 'bla bla ... ' + cast(@count as varchar) + ' new records have been added bla bla ... ' + CHAR(13)

    -- send email with all records available in table ... if you want only new ones add WHERE processed is NULL condition!
    SET @Query = CHAR(13) + 'SELECT empid, ename, sal, processed FROM MyTbl'


    EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'YOUR PROFILE MAIL'
    ,@recipients = @recipients
    ,@subject = @subject
    ,@query = @Query
    ,@body = @body
    ,@execute_query_database = 'Your DB name'
    --,@attach_query_result_as_file = 1, -- uncomment this!!!
    --,@query_attachment_filename = 'filename.csv', -- uncomment this!!!
    --,@query_result_separator= @tab, -- uncomment this!!!
    --,@query_result_no_padding=1, -- uncomment this!!!
    --,@query_result_width=32767 -- uncomment this!!!
END

UPDATE MyTbl SET processed = GETDATE() WHERE processed IS NULL