I have four tables:
Activity:
ActivityID(PK) ActivityName CustomerID(FK) UserId(FK)
1 Lead Gen 1st 50 U1
2 Lead Gen 2nd 60 U2
Customer:
CustomerID(PK) CustomerNumber CustomerName
50 C0150 cust50 ltd
60 C0160 cust60 ltd
User:
UserID(PK) UserName Email
U1 Mr. X X@cat.com
U2 Mr. Y Y@cat.com
UserActivity:
UserActivityID(PK) UserID(FK) ActivityID(FK)
888 U1 1
889 U2 2
I want to send an email (i.e. Email:X@cat.com) to the users related to the activity (i.e. ActivityId:1) if any insert happens in Activity
Table (SQL Server 2008-R2).
The email body should contain the ActivityId
, ActivityName
, CustomerNumber
and CustomerName
.
The trigger has to do the above mentioned and the result should be like this in the email:
ActivityID:1, ActivityName:Lead Gen 1st created for CustomerNumber: C0150 & CustomerName: cust50 ltd
Here is my code:
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
The problem is in my code that I can't fetch the customer data and email from the respective tables properly.