我有四张桌子:
活动:
ActivityID(PK) ActivityName CustomerID(FK) UserId(FK)
1 Lead Gen 1st 50 U1
2 Lead Gen 2nd 60 U2
顾客:
CustomerID(PK) CustomerNumber CustomerName
50 C0150 cust50 ltd
60 C0160 cust60 ltd
用户:
UserID(PK) UserName Email
U1 Mr. X X@cat.com
U2 Mr. Y Y@cat.com
用户活动:
UserActivityID(PK) UserID(FK) ActivityID(FK)
888 U1 1
889 U2 2
Activity
如果表(SQL Server 2008-R2)中发生任何插入,我想向与活动相关的用户(即 ActivityId:1)发送一封电子邮件(即 Email:X@cat.com )。
电子邮件正文应包含ActivityId
、ActivityName
和。CustomerNumber
CustomerName
触发器必须执行上述操作,结果在电子邮件中应该是这样的:
ActivityID:1, ActivityName:Lead Gen 1st created for CustomerNumber: C0150 & CustomerName: cust50 ltd
这是我的代码:
CREATE TRIGGER [dbo].[Activity_Insert_Mail_Notification]
ON [dbo].[Activity]
AFTER INSERT
AS
BEGIN
DECLARE @ActivityID varchar(2000)
DECLARE @ActivityName varchar (2000)
Select @ActivityID=inserted.ActivityID,@ActivityName=inserted.ActivityName
From inserted
DECLARE @CustomerNo varchar(2000)
DECLARE @CustomerName varchar(2000)
Select @CustomerNo = B.[CustomerNumber]
,@CustomerName= B.[CustomerName]
from [dbo].[Activity] A
inner join [dbo].[Customer] B
on A.[CustomerID]=B.[CustomerID]
DECLARE @email VARCHAR(2000)
SELECT @email = RTRIM(U.[Email]) + ';'
FROM [dbo].[Activity] A
left join [dbo].[UserActivity] UA
inner join [dbo].[User] U
on UA.[UserID]=U.[UserID]
on A.[ActivityID]=UA.[ActivityID]
WHERE U.[Email]<> ''
DECLARE @content varchar (2000)
= 'ActivityID:' + @ActivityId + ' '
+ ',ActivityName:' + @ActivityName + ' '
+ 'has been created for' + 'CustomerNumber: ' + @CustomerNo
+ ' ' + '&CustomerName: ' + @CustomerName
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'LEADNOTIFY'
,@recipients = @email
,@subject = 'New Lead Found'
,@body = @content
,@importance ='HIGH'
END
问题出在我的代码中,我无法正确地从各个表中获取客户数据和电子邮件。