问题
Can someone provide a link or an example of an Oracle DB trigger that sends an email if a specific column in the table gets updated AND updates a different column in the same table?
Example: A table has multiple issues and there are two columns 'Issue Added' and 'Email Sent' that default to '0'
Issue Added Email Sent
0 0
When the 'Issue Added' column gets updated to '1'
Issue Added Email Sent
1 0
Trigger sends email and updates column 'Email Sent'
Issue Added Email Sent
1 1
回答1:
It would generally be a bad idea to try to send an email in a trigger.
- If the system is unable to send the email (for example, because the SMTP server is temporarily down), the trigger will fail and the triggering statement will fail and be rolled back. It is very rare that you would really want to stop the underlying transaction simply because you weren't able to send an email.
- Sending an email is non-transactional. That means that you'll send emails for changes that never get committed. And you'll send emails multiple times because Oracle chooses to rollback and re-execute all or part of an
INSERTstatement in order to maintain write consistency.
You'll generally be much better served with a database job that periodically looks for rows that need to have an email sent, sends the emails, and then updates the table. You can use either the older DBMS_JOB package or the newer and more sophisticated DBMS_SCHEDULER package. Something along the lines of
CREATE OR REPLACE PROCEDURE process_issues
AS
BEGIN
FOR i IN (SELECT *
FROM your_table_name
WHERE issue_added = 1
AND email_sent = 0)
LOOP
send_email( i.issue_id );
UPDATE your_table_name
SET email_sent = 1
WHERE issue_id = i.issue_id;
END LOOP;
END;
which is then scheduled to run, say, every 5 minutes (you could also use the DBMS_SCHEDULER package)
DECLARE
l_jobno PLS_INTEGER:
BEGIN
dbms_job.submit( l_jobno,
'BEGIN process_issues; END;',
sysdate + interval '5' minute,
'sysdate + interval ''5'' minute' );
commit;
END;
You can use the UTL_MAIL package to implement the send_email procedure. You probably just need to call UTL_MAIL.SEND with appropriate parameters (assuming you've configured your SMTP_OUT_SERVER parameter and your user has been granted appropriate access to the UTL_MAIL package and to an ACL that allows you to communicate with that SMTP server).
来源:https://stackoverflow.com/questions/10281861/oracle-db-suggestion-for-email-trigger