jasonabrown
asked on
SQL server trigger to send mail about updated or inserted records
I have written a small sql helpdesk database and I would like a trigger to execute when a user enters a new record or updates a record for that particular record and its values to be emailed to the original submitter. One of the field values already contains the email address of the user. I would like the email formatted with the To box being that email address, the from box being a no-reply email, the subject containing some of the field values, and all the field values in the message body...no attachments or special formatting.
Can onyone help??
This is what I have so far...
--Begin code
--After record updated or inserted-email will be sent to Employee field value
--this field contains email address in the someone@somewhere.com format
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = N'Record_Update'
AND type = 'TR')
DROP TRIGGER Record_Update
GO
CREATE TRIGGER Record_Update
ON dbo.HelpDeskCalls
FOR UPDATE
AS
DECLARE @sCallNumber varchar(10)
DECLARE @sCallStatus varchar(10)
DECLARE @sEmployee varchar(10)
DECLARE @sPhoneNumber varchar(10)
DECLARE @sLocation varchar(10)
DECLARE @sCategory varchar(10)
DECLARE @sProblem varchar(10)
DECLARE @sITNotes varchar(10)
DECLARE @sAssignedPersonnel varchar(10)
DECLARE @sDateTimeOpened varchar(10)
DECLARE @sDateTimeClosed varchar(10)
SELECT @sCallNumber = CallNumber,
@sCallStatus = CallStatus,
@sEmployee = Employee,
@sPhoneNumber = PhoneNumber,
@sLocation = Location,
@sCategory = Category,
@sProblem = Problem,
@sITNotes = ITNotes,
@sAssignedPersonnel = AssignedPersonnel,
@sDateTimeOpened = DateTimeOpened,
@sDateTimeClosed = DateTimeClosed
FROM INSERTED
EXEC master..xp_sendmail @recipients =@sEmployee,
@query = '',
@subject = 'Helpdesk Call# Updated',
@message = 'Helpdesk Call# Updated',
@attach_results = 'TRUE', @width = 250
GO
-- End Code
Thanks for any help
Right now I'm getting the error "Cannot use text, ntext, or image columns in the 'inserted' and 'deleted' tables." I am fairly sure its due to my variable declarations, but can't seem to find the fix for it.
Can onyone help??
This is what I have so far...
--Begin code
--After record updated or inserted-email will be sent to Employee field value
--this field contains email address in the someone@somewhere.com format
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = N'Record_Update'
AND type = 'TR')
DROP TRIGGER Record_Update
GO
CREATE TRIGGER Record_Update
ON dbo.HelpDeskCalls
FOR UPDATE
AS
DECLARE @sCallNumber varchar(10)
DECLARE @sCallStatus varchar(10)
DECLARE @sEmployee varchar(10)
DECLARE @sPhoneNumber varchar(10)
DECLARE @sLocation varchar(10)
DECLARE @sCategory varchar(10)
DECLARE @sProblem varchar(10)
DECLARE @sITNotes varchar(10)
DECLARE @sAssignedPersonnel varchar(10)
DECLARE @sDateTimeOpened varchar(10)
DECLARE @sDateTimeClosed varchar(10)
SELECT @sCallNumber = CallNumber,
@sCallStatus = CallStatus,
@sEmployee = Employee,
@sPhoneNumber = PhoneNumber,
@sLocation = Location,
@sCategory = Category,
@sProblem = Problem,
@sITNotes = ITNotes,
@sAssignedPersonnel = AssignedPersonnel,
@sDateTimeOpened = DateTimeOpened,
@sDateTimeClosed = DateTimeClosed
FROM INSERTED
EXEC master..xp_sendmail @recipients =@sEmployee,
@query = '',
@subject = 'Helpdesk Call# Updated',
@message = 'Helpdesk Call# Updated',
@attach_results = 'TRUE', @width = 250
GO
-- End Code
Thanks for any help
Right now I'm getting the error "Cannot use text, ntext, or image columns in the 'inserted' and 'deleted' tables." I am fairly sure its due to my variable declarations, but can't seem to find the fix for it.
From Books Online:
In a DELETE, INSERT, or UPDATE trigger, SQL Server does not allow text,
ntext, or image column references in the inserted and deleted tables if the
compatibility level is equal to 70. The text, ntext, and image values in the
inserted and deleted tables cannot be accessed. To retrieve the new value in
either an INSERT or UPDATE trigger, join the inserted table with the
original update table. When the compatibility level is 65 or lower, null
values are returned for inserted or deleted text, ntext, or image columns
that allow null values; zero-length strings are returned if the columns are
not nullable.
If the compatibility level is 80 or higher, SQL Server allows the update of
text, ntext, or image columns through the INSTEAD OF trigger on tables or
views.
In a DELETE, INSERT, or UPDATE trigger, SQL Server does not allow text,
ntext, or image column references in the inserted and deleted tables if the
compatibility level is equal to 70. The text, ntext, and image values in the
inserted and deleted tables cannot be accessed. To retrieve the new value in
either an INSERT or UPDATE trigger, join the inserted table with the
original update table. When the compatibility level is 65 or lower, null
values are returned for inserted or deleted text, ntext, or image columns
that allow null values; zero-length strings are returned if the columns are
not nullable.
If the compatibility level is 80 or higher, SQL Server allows the update of
text, ntext, or image columns through the INSTEAD OF trigger on tables or
views.
post
table structure of dbo.HelpDeskCalls pls
table structure of dbo.HelpDeskCalls pls
ASKER
Column Name Data Type Length AllowNulls
CallNumber int 4 no
Employee nvarchar 50 no
PhoneNumber nvarchar 50 no
Location nvarchar 50 no
Category nvarchar 50 no
Problem nvarchar 50 no
ITNotes nvarchar 50 yes
AssignedPersonnel ntext 16 yes
DateTimeOpened datetime 8 no
DateTimeClosed datetime 8 yes
TotalTimeOpen decimal 13 no
TotalTimeOpened is a formula: (round((convert(decimal,da tediff(min ute,[DateT imeOpened] ,[DateTime Closed])) / 60),2))
CallNumber int 4 no
Employee nvarchar 50 no
PhoneNumber nvarchar 50 no
Location nvarchar 50 no
Category nvarchar 50 no
Problem nvarchar 50 no
ITNotes nvarchar 50 yes
AssignedPersonnel ntext 16 yes
DateTimeOpened datetime 8 no
DateTimeClosed datetime 8 yes
TotalTimeOpen decimal 13 no
TotalTimeOpened is a formula: (round((convert(decimal,da
ASKER
Just in case this is important to. The database is accessed and updated entirely through .asp web pages. I have a script that upon call submission the values can be emailed out unfortunately I have not been able to find out where to put the script or access the variables in the update pages. This project started out using an access db and the frontpage database interface wizard. I converted the db to sql and altered much of the code on the web pages for it to work. I would rather do all notification from the server but If anyone know how to do this from the update.asp pages which are created automatically by the db wizard in frontpage that would work too.
'SENDMAIL SCRIPT
Dim objSendMail
'Create CDO object for sending mail via smtp
Set objSendMail = CreateObject("CDO.Message" )
objSendMail.From = "ITWEB"
objSendMail.To = arFormValues0(1)
objSendMail.Subject = "New Open Call Submitted to ITWEB"
objSendMail.TextBody = "Please do not reply to this email" & Chr(13) & "Call Status = " & arFormValues0(3) & ""&Chr(13)&"" & "Employee = " & arFormValues0(1) & ""&Chr(13)&"" & "Phone Number = " & arFormValues0(2) & ""&Chr(13)&"" & "Location = " & arFormValues0(4) & ""&Chr(13)&"" & "Category = " & arFormValues0(5) & ""&Chr(13)&"" & "Problem = " & arFormValues0(0) & ""&Chr(13)&"" & "Date/Time Opened = " & Now
objSendMail.Configuration. Fields.Ite m _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objSendMail.Configuration. Fields.Ite m _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mailserver.work.com"
objSendMail.Configuration. Fields.Ite m _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objSendMail.Configuration. Fields.Upd ate
objSendMail.Send
Set objSendMail = Nothing
'END SENDMAIL SCRIPT
The above script is in my submission page just before the records are submitted to the db. The update pages only have an SQL update query and 50 other lines of code.
update code below
<html>
<head>
<% ' FP_ASP -- ASP Automatically generated by a Frontpage Component. Do not Edit.
FP_CharSet = "windows-1252"
FP_CodePage = 1252 %>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>HelpDeskCalls -- Updated Record</title>
<meta name="GENERATOR" content="Microsoft FrontPage 6.0">
<meta name="ProgId" content="FrontPage.Editor. Document">
</head>
<body stylesrc="../../../itindex .html" link="#000080" vlink="#000080" alink="#000080">
<p>
<!--webbot bot="PurpleText" PREVIEW="-Important- If you modify this Database Results region using the Database Results Wizard, then your Database Editor will no longer work. If you accidentally open the Database Results Wizard, simply click Cancel to exit without regenerating the Database Results region." -->
</p>
<!--webbot bot="DatabaseRegionStart" s-columnnames s-columntypes s-dataconnection="HELPDESK " b-tableformat="FALSE" b-menuformat="FALSE" s-menuchoice s-menuvalue b-tableborder="TRUE" b-tableexpand="TRUE" b-tableheader="TRUE" b-listlabels="FALSE" b-listseparator="FALSE" i-ListFormat="0" b-makeform="FALSE" s-RecordSource s-displaycolumns s-criteria s-order s-sql="UPDATE HelpDeskCalls SET CallStatus = '::CallStatus::' , Employee = '::Employee::' , PhoneNumber = '::PhoneNumber::' , Location = '::Location::' , Category = '::Category::' , Problem = '::Problem::' , ITNotes = '::ITNotes::' , AssignedPersonnel = '::AssignedPersonnel::' , DateTimeOpened = '::DateTimeOpened::' WHERE (CallNumber = ::CallNumber::)" b-procedure="FALSE" clientside SuggestedExt="asp" s-DefaultFields="CallStatu s=&amp ;Employee= &amp;P honeNumber =&amp; Location=& amp;amp;Ca tegory=&am p;amp;Prob lem=&a mp;ITNotes =&amp; AssignedPe rsonnel=&a mp;amp;Dat eTimeOpene d=&amp ;CallNumbe r=" s-NoRecordsFound="Record updated in table." i-MaxRecords="1" i-GroupSize="0" u-dblib="../../../_fpclass /fpdblib.i nc" u-dbrgn1="../../../_fpclas s/fpdbrgn1 .inc" u-dbrgn2="../../../_fpclas s/fpdbrgn2 .inc" Tag="BODY" startspan BOTID="0" preview="<table border=0 width="100%"> <tr> <td bgcolor="#FFFF00" ;><f ont color="#000000"& gt;This is the start of a Database Results region.</font></t d></ tr>< /table> " b-WasTableFormat="FALSE" --><!--#include file="../../../_fpclass/fp dblib.inc" -->
<% if 0 then %>
<SCRIPT Language="JavaScript">
document.write("<div style='background: yellow; color: black;'>The Database Results component on this page is unable to display database content. The page must have a filename ending in '.asp', and the web must be hosted on a server that supports Active Server Pages.</div>");
</SCRIPT>
<% end if %>
<%
fp_sQry="UPDATE HelpDeskCalls SET CallStatus = '::CallStatus::' , Employee = '::Employee::' , PhoneNumber = '::PhoneNumber::' , Location = '::Location::' , Category = '::Category::' , Problem = '::Problem::' , ITNotes = '::ITNotes::' , AssignedPersonnel = '::AssignedPersonnel::' , DateTimeOpened = '::DateTimeOpened::' WHERE (CallNumber = ::CallNumber::)"
fp_sDefault="CallStatus=&E mployee=&P honeNumber =&Location =&Category =&Problem= &ITNotes=& AssignedPe rsonnel=&D ateTimeOpe ned=&CallN umber="
fp_sNoRecords="Record updated in table."
fp_sDataConn="HELPDESK"
fp_iMaxRecords=1
fp_iCommandType=1
fp_iPageSize=0
fp_fTableFormat=False
fp_fMenuFormat=False
fp_sMenuChoice=""
fp_sMenuValue=""
fp_sColTypes="&CallNumber= 3&CallStat us=202&Emp loyee=202& PhoneNumbe r=202&Loca tion=202&C ategory=20 2&Problem= 203&ITNote s=203&Assi gnedPerson nel=202&Da teTimeOpen ed=135&Dat eTimeClose d=135&"
fp_iDisplayCols=16
fp_fCustomQuery=True
BOTID=0
fp_iRegion=BOTID
%>
<!--#include file="../../../_fpclass/fp dbrgn1.inc "-->
<!--webbot bot="DatabaseRegionStart" endspan -->
<p><!--webbot bot="PurpleText" PREVIEW="This is the UPDATE query." --></p>
<!--webbot bot="DatabaseRegionEnd" b-tableformat="FALSE" b-menuformat="FALSE" u-dbrgn2="../../../_fpclas s/fpdbrgn2 .inc" i-groupsize="0" clientside Tag="BODY" startspan preview="<table border=0 width="100%"> <tr> <td bgcolor="#FFFF00" ;><f ont color="#000000"& gt;This is the end of a Database Results region.</font></t d></ tr>< /table> " --><!--#include file="../../../_fpclass/fp dbrgn2.inc "-->
<!--webbot bot="DatabaseRegionEnd" endspan -->
<p><a href="../../../itindex.htm l">ITWEB HOME</a></p>
</body>
</html>
'SENDMAIL SCRIPT
Dim objSendMail
'Create CDO object for sending mail via smtp
Set objSendMail = CreateObject("CDO.Message"
objSendMail.From = "ITWEB"
objSendMail.To = arFormValues0(1)
objSendMail.Subject = "New Open Call Submitted to ITWEB"
objSendMail.TextBody = "Please do not reply to this email" & Chr(13) & "Call Status = " & arFormValues0(3) & ""&Chr(13)&"" & "Employee = " & arFormValues0(1) & ""&Chr(13)&"" & "Phone Number = " & arFormValues0(2) & ""&Chr(13)&"" & "Location = " & arFormValues0(4) & ""&Chr(13)&"" & "Category = " & arFormValues0(5) & ""&Chr(13)&"" & "Problem = " & arFormValues0(0) & ""&Chr(13)&"" & "Date/Time Opened = " & Now
objSendMail.Configuration.
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objSendMail.Configuration.
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mailserver.work.com"
objSendMail.Configuration.
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objSendMail.Configuration.
objSendMail.Send
Set objSendMail = Nothing
'END SENDMAIL SCRIPT
The above script is in my submission page just before the records are submitted to the db. The update pages only have an SQL update query and 50 other lines of code.
update code below
<html>
<head>
<% ' FP_ASP -- ASP Automatically generated by a Frontpage Component. Do not Edit.
FP_CharSet = "windows-1252"
FP_CodePage = 1252 %>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>HelpDeskCalls -- Updated Record</title>
<meta name="GENERATOR" content="Microsoft FrontPage 6.0">
<meta name="ProgId" content="FrontPage.Editor.
</head>
<body stylesrc="../../../itindex
<p>
<!--webbot bot="PurpleText" PREVIEW="-Important- If you modify this Database Results region using the Database Results Wizard, then your Database Editor will no longer work. If you accidentally open the Database Results Wizard, simply click Cancel to exit without regenerating the Database Results region." -->
</p>
<!--webbot bot="DatabaseRegionStart" s-columnnames s-columntypes s-dataconnection="HELPDESK
<% if 0 then %>
<SCRIPT Language="JavaScript">
document.write("<div style='background: yellow; color: black;'>The Database Results component on this page is unable to display database content. The page must have a filename ending in '.asp', and the web must be hosted on a server that supports Active Server Pages.</div>");
</SCRIPT>
<% end if %>
<%
fp_sQry="UPDATE HelpDeskCalls SET CallStatus = '::CallStatus::' , Employee = '::Employee::' , PhoneNumber = '::PhoneNumber::' , Location = '::Location::' , Category = '::Category::' , Problem = '::Problem::' , ITNotes = '::ITNotes::' , AssignedPersonnel = '::AssignedPersonnel::' , DateTimeOpened = '::DateTimeOpened::' WHERE (CallNumber = ::CallNumber::)"
fp_sDefault="CallStatus=&E
fp_sNoRecords="Record updated in table."
fp_sDataConn="HELPDESK"
fp_iMaxRecords=1
fp_iCommandType=1
fp_iPageSize=0
fp_fTableFormat=False
fp_fMenuFormat=False
fp_sMenuChoice=""
fp_sMenuValue=""
fp_sColTypes="&CallNumber=
fp_iDisplayCols=16
fp_fCustomQuery=True
BOTID=0
fp_iRegion=BOTID
%>
<!--#include file="../../../_fpclass/fp
<!--webbot bot="DatabaseRegionStart" endspan -->
<p><!--webbot bot="PurpleText" PREVIEW="This is the UPDATE query." --></p>
<!--webbot bot="DatabaseRegionEnd" b-tableformat="FALSE" b-menuformat="FALSE" u-dbrgn2="../../../_fpclas
<!--webbot bot="DatabaseRegionEnd" endspan -->
<p><a href="../../../itindex.htm
</body>
</html>
So no comment on any of my posts??
ASKER
I have tried using INSTEAD OF and not changing any other code and get the same errors. I am fairly new to sql and don't know all the syntax and commands. I have read about the INSTEAD OF trigger, but it seems that it is used to see what would happen to the table or record but it would not actually alter the table. I need the table to be altered, and then an email sent tothe employee field so that the cutomers know when the helpdesk team has changed information on a helpdesk call.
ASKER
This has been resolved using an AFTER UPDATE trigger on the inserted tables and exec using xp_smtp_sendmail.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
"close this question."
You're responsible for doing that....
You're responsible for doing that....
https://www.experts-exchange.com/questions/20815377/Use-'text'-data-types-in-triggers.html
The from address is going to be the from address of the SQLAgent/SQLMail account (unless you use CDO or SMTPmail) and can't be changed.
Brett