触发以插入记录为PDF文件时发送邮件

时间:2016-01-06 08:09:34

标签: sql-server triggers

尝试创建触发器基础,以便在我的表中创建/插入的每条记录上为每个用户发送电子邮件,因为我已经在数据库中有路径 在我的代码下方,如果有人可以帮我这个

CREATE TRIGGER DP_READY
   ON  dbo.TimesheetLog
   for insert
AS 
    declare @pdf nvarchar (max)
declare @email nvarchar (50)
declare @fcode nvarchar (50)
declare @date date 
    set @pdf=  (select distinct  'C:\Papyrus_Router\Output\PDF' +  '\' + a.cpdffilename AS pdf_f , b.Name,b.cforeman,  b.Email
  from timesheetlog as a left join EmailSubscription b on right(ltrim(rtrim(a.cheaderkey)) ,6)= b.cforeman
   where cstatus = 'DP-READY')

   set @email= (select distinct    b.Email
    from timesheetlog as a left join EmailSubscription b on right(ltrim(rtrim(a.cheaderkey)) ,6)= b.cforeman
    where cstatus = 'DP-READY')

    set @fcode =   (select distinct  b.cforeman +'-'+ b.Name+'-'+ convert(varchar(50),convert(date,a.dcreated))
  from timesheetlog as a left join EmailSubscription b on right(ltrim(rtrim(a.cheaderkey)) ,6)= b.cforeman
   where cstatus = 'DP-READY')  
    SET NOCOUNT ON;
set @date = (select distinct  convert(date,a.dcreated)
  from timesheetlog as a left join EmailSubscription b on right(ltrim(rtrim(a.cheaderkey)) ,6)= b.cforeman
   where cstatus = 'DP-READY')
   -- Insert statements for trigger here
    if CHARINDEX(@pdf, @email) > 0 and @date = getdate()
BEGIN
 EXEC msdb.dbo.sp_send_dbmail
    @recipients=@email,
    @file_attachments = @pdf,
    @subject = @fcode,
    @body = 'Your Sync data from the Pens '

END
GO

我收到此错误

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

2 个答案:

答案 0 :(得分:0)

您无法将多个值分配到变量中:

    select 
        member_location 
        , count(member_location) cnt
    from
        members
    where
        id > 2
        and member_location = 10
    group by
        member_location
    order by 
        2 desc

问题是姓名,cforeman和电子邮件。

此外,您的触发器根本不使用虚拟表set @pdf= ( select distinct 'C:\Papyrus_Router\Output\PDF' + '\' + a.cpdffilename AS pdf_f, b.Name, b.cforeman, b.Email ,因此它可能无法正常工作。

答案 1 :(得分:0)

使用以下代码更改您的触发器:

CREATE TRIGGER DP_READY
ON  dbo.TimesheetLog
for insert
AS 
   declare @pdf nvarchar (max)
   declare @email nvarchar (50)
   declare @fcode nvarchar (50)
   declare @date date 

  select @pdf='C:\Papyrus_Router\Output\PDF' +  '\' + a.cpdffilename,
  @fcode=b.cforeman +'-'+ b.Name+'-'+ convert(varchar(50),convert(date,a.dcreated)),
  @email=b.Email,
  @date=convert(date,a.dcreated)
  from timesheetlog as a left join EmailSubscription b 
  on right(ltrim(rtrim(a.cheaderkey)) ,6)= b.cforeman
  where cstatus = 'DP-READY'

BEGIN
EXEC msdb.dbo.sp_send_dbmail
@recipients=@email,
@file_attachments = @pdf,
@subject = @fcode,
@body = 'Your Sync data from the Pens '

END
GO