CHAPTER 15 Database Mail Setting Up Database Mail Unlike with SQL Mail, setting up profiles and accounts for use with Database Mail is easy to accomplish, thanks mainly to the Database M
Trang 1CHAPTER 14 Database Backup and Restore
The frequency of changes to the data and method by which it is changed
The acceptable amount of data loss in the event of a failure
The acceptable recovery time in the event of a failure
First, you must establish what your backup window will be Because SQL Server allows
dynamic backups, users can still access the database during backups; however, this affects
performance This means you should still schedule backups for low-activity periods and
have them complete in the shortest possible time
After you establish your backup window, you can determine your backup method and
schedule For example, if it takes 4 hours for a full backup to complete, and the database is
quiescent between midnight and 6:00 a.m., you have time to perform a full backup each
night On the other hand, if a full backup takes 10 hours, and you have a 2-hour window,
you should consider monthly or weekly backups, perhaps in conjunction with filegroup,
differential, and transaction log backups In many decision-support databases populated
with periodic data loads, it might suffice to back up once after each data load
Backup frequency is also directly tied to acceptable data loss In the event of catastrophic
failure, such as a fire in the server room, you can recover data only up to the point of the
last backup moved offsite If it is acceptable to lose a day’s worth of data entry, nightly
backups might suffice If your acceptable loss is an hour’s worth of data, hourly
transac-tion log backups would have to be added to the schedule
Your backup frequency affects your recovery time In some environments, a weekly full
backup plus transaction log backups taken every 10 minutes provide an acceptable data
loss factor A failure a few days after backup would require a full database restore and the
application of hundreds of transaction logs Adding a daily differential backup in this case
would vastly improve restore time The full and differential backups would be restored,
and then six logs would be applied for each hour between the differential backup and the
time of failure
Using a Standby Server
If the ability to quickly recover from failure is crucial to your operation, you might
consider implementing a standby server Implementing a standby server involves backing
up the production server and then restoring it to the standby server, leaving it in recovery
mode As transaction logs are backed up on the production server, they are applied to the
standby server If a failure occurs on the production server, the standby server can be
recovered and used in place of the production server If the production server is still
running, you should not forget to back up the current log with the NO_TRUNCATE option
and restore it to the standby server as well before bringing it online
NOTE
Another advantage of restoring backups to a standby server is that it immediately
vali-dates your backups so you can be assured of whether they are valid There is nothing
worse than finding out during a recovery process that one of the backup files is
dam-aged or missing
Trang 2Additional Backup Considerations
The STANDBY =undo_file_name option plays a key role in the application of transaction
logs to the standby server When the database and subsequent log backups are restored
to the standby server with this option, the database is left in recovery mode but is
avail-able as a read-only database Now that the standby database is availavail-able for queries, it
can actually reduce load on the production database by acting as a decision support
system (DSS) Database Consistency Checks (DBCC) can be run on it as well, further
reducing the load on the production system
For the database to be available for reads, the data must be in a consistent state This
means that all uncommitted transactions must be rolled back This rollback is usually
handled by the RECOVERY option during a restore In the case of a standby server, this
would cause a problem because you would intend to apply more logs, which could, in
fact, commit those transactions This situation is handled by the undo_file_name clause of
the STANDBY option The file specified here holds a copy of all uncommitted transactions
rolled back to bring the standby server to a consistent, read-only state If those
transac-tions subsequently commit a log restore, this undo information can be used to complete
the transaction
The application of hundreds or thousands of transaction logs to the standby server can be
challenging Fortunately, SQL Server 2008 includes log shipping, which automates the
transfer of logs to the standby server Log shipping, which can be configured in SSMS, uses
SQL Server Agent jobs on the primary server to back up the transaction log and copy it to
a folder on the standby server SQL Server Agent on the standby server then executes a
load job to restore the log Automating your standby server with log shipping reduces
administration and helps to ensure that the standby database is up-to-date For further
details on log shipping, see Chapter 19, “Replication.” Log shipping isn’t a form of
replica-tion but is covered in Chapter 19 as an alternative to replicareplica-tion
Snapshot Backups
Snapshot backups are developed in conjunction with independent hardware and software
vendors These backups are not related to SQL Server database snapshots and are not
accessible from any of the SQL Server tools They utilize backup and restore technology
and can provide relatively fast backup and restore operations Snapshot backups are
typi-cally utilized on very large databases that are unable to perform database backups and
restores in a timely fashion using SQL Server’s conventional backup and restore resources
Considerations for Very Large Databases
When it comes to backup and recovery, special consideration must be given to very large
databases, which are known as VLDBs A VLDB has the following special requirements:
Storage—Size might dictate the use of tape backups over the network or a disk.
Time—As your time to backup increases, the frequency of backups might have to be
adjusted
Trang 3CHAPTER 14 Database Backup and Restore
Recovery—Partial database recovery, such as restoring a file or filegroup, might be
required due to the prohibitive time required to restore the entire database
When designing a VLDB, you must integrate your backup plan with storage, performance,
and availability requirements Larger databases take longer to back up because the backup
sizes are larger, and restores on this type of database can take much longer to complete
than with a smaller database
Maintenance Plans
SQL Server includes maintenance plans that provide database maintenance tasks,
includ-ing optimization, integrity checks, and backups The backup options available in the
maintenance plans are comprehensive and include the capability to regularly schedule
full, differential, and transaction log backups This type of automation is essential to
ensure that your backups are taken with a reliable tool at regular intervals
You can create maintenance plans from within SSMS If you open the Management node in
the Object Explorer, you see a node named Maintenance Plans If you right-click this
node, you can select New Maintenance Plan to create a plan from scratch, or you can
select Maintenance Plan Wizard to have a wizard guide you through the creation of a new
maintenance plan The following options that relate to backups are available as part of a
maintenance plan:
Back Up Database (Full)
Back Up Database (Differential)
Back Up Database (Transaction Log)
Using these tasks in a maintenance plan is a great start to a solid backup and recovery
plan Refer to Chapter 33, “Database Maintenance,” for further details about creating a
maintenance plan
Summary
Having a database environment without a solid backup and recovery plan is like owning a
home without an insurance policy to protect it If you develop a plan to minimize the
possibility of losing a database, you have essentially bought an insurance policy for your
data In the event of a problem, you can call on the backups that you have invested in
and recover the loss with a minimal amount of cost
Chapter 15, “Database Mail,” explores a comprehensive mail feature offered with SQL
Server 2008 Database Mail allows you to send email notifications from SQL Server These
notifications can be tied to scheduled jobs and alerts within SQL Server, including jobs
that can execute those all-important database backups
Trang 4CHAPTER 15
Database Mail
IN THIS CHAPTER
What’s New in Database Mail Setting Up Database Mail Sending and Receiving with Database Mail
Using SQL Server Agent Mail Related Views and Procedures
Database Mail is SQL Server 2008’s emailing component,
built as the replacement for SQL Mail Although SQL Mail
can still be enabled in SQL Server 2008 (for backward
compatibility, although it is deprecated), it’s a simple task to
convert all your existing SQL Mail code and SQL Agent Mail
notifications to Database Mail And you’ll surely want to
What’s New in Database Mail
Database Mail is an enterprise-class implementation
designed with all the features you’d expect from this
next-generation database server, most of which are not available
in SQL Mail These features include support for multiple
email profiles and accounts, asynchronous (queued)
message delivery via a dedicated process in conjunction
with Service Broker, cluster-awareness, 64-bit compatibility,
greater security options (such as governing of mail
attach-ment size and prohibition of file extensions), and simplified
mail auditing Database Mail also utilizes the
industry-stan-dard Simple Mail Transfer Protocol (SMTP), signaling the
end of reliance on Extended Messaging Application
Programming Interface (Extended MAPI)
Database Mail has more capabilities and is more scalable
and reliable than SQL Mail, especially when stressed with
the heavier usage scenarios common today And, thankfully,
it’s a good deal easier to successfully configure than its
predecessor
Trang 5CHAPTER 15 Database Mail
Setting Up Database Mail
Unlike with SQL Mail, setting up profiles and accounts for use with Database Mail is easy
to accomplish, thanks mainly to the Database Mail Configuration Wizard, found in the
SQL Server Management Studio (SSMS) Object Browser You can use this wizard both to set
up and manage Database Mail Before using it, you need to switch on the Database Mail
feature, which is off by default, in keeping with Microsoft’s secure-by-default approach
Follow these steps to do so
Configure the Database Mail XPs configuration option by running the following T-SQL
code in a new query window (while logged in as sysadmin, of course):
use Master
GO
sp_configure ‘show advanced options’, 1;
GO
RECONFIGURE;
GO
sp_configure ‘Database Mail XPs’, 1;
GO
RECONFIGURE
GO
Configuration option ‘show advanced options’ changed from 0 to 1 Run the
RECONFIGURE statement to install
Configuration option ‘Database Mail XPs’ changed from 0 to 1 Run the
RECONFIGURE statement to install
If you ever want to disable Database Mail, you can run this:
sp_configure ‘Database Mail XPs’, 0;
This statement prevents Database Mail from starting in response to a call to
sysmail_start_sp (discussed later in this chapter) If Database Mail is running when you
make this call, it sends unsent queued mail until the mail sending process
(DatabaseMail.exe) has been idle for the duration of the
DatabaseMailExeMinimumLifeTime configuration setting (discussed later in this chapter);
then it stops
You also need to enable Service Broker in msdb (if not done already) because Database Mail
relies on it as part of its implementation To do this, you stop the SQL Server Agent service
and then execute the following script:
USE master
GO
ALTER DATABASE msdb SET ENABLE_BROKER
Trang 6Setting Up Database Mail
You can check the status of Service Broker on msdb by using the following code:
Use Master
GO
SELECT is_broker_enabled
FROM sys.databases
WHERE name = ‘msdb’
GO
is_broker_enabled
————————-1
(1 row(s) affected)
To receive message send requests from outside the SQL Server instance, you need to create
an endpoint (preferably a certificate-secured one) associated with Service Broker To
accom-plish this, refer to the “Service Broker Routing and Security” section in Chapter 49, “SQL
Server Service Broker” (on the CD), or consult the “Create Endpoint” topic in Books Online
To complete this configuration, you need to return to SSMS and establish a connection to
the same SQL Server instance for which you just enabled Database Mail You connect the
Object Browser to that instance and expand the Management folder to reveal the
Database Mail node Then you right-click the Database Mail node and select the
Configure Database Mail menu option to launch the Database Mail Configuration Wizard
Creating Mail Profiles and Accounts
After you pass the Database Mail Configuration Wizard’s welcome screen, you are
presented with the opportunity to set up Database Mail (“for the first time”) You can
achieve this by creating the required profiles, profile security settings, SMTP accounts, and
system-wide mail settings You should leave the first radio button (Set Up Database Mail
by Performing the Following Tasks) selected and then click Next
NOTE
In Database Mail, you use mail profiles A mail profile is simply a securable container
for a group of SMTP accounts that is used when sending mail In contrast to SQL Mail,
with Database Mail, you can set up multiple profiles containing multiple accounts,
allowing for finer-grained administrative control You can create one profile for
admintra-tors and another for regular users, for example, or create distinct profiles dedicated to
various software applications
Note also that to use Database Mail, you no longer need to run the SQL Server or SQL
Server Agent Windows services under user accounts (rather than using the default,
LocalSystem), nor do you need to install Microsoft Outlook (or any other Extended
MAPI client) on the machine hosting SQL Server 2008
Trang 7ptg CHAPTER 15 Database Mail
FIGURE 15.1 Using the Database Mail Configuration Wizard to set up SMTP accounts
click Add to add your first SMTP account This process is much like the process of setting
up the SMTP (or sending) portion of your email accounts with your regular email client
software To create the SMTP account, you specify a name, an optional description, a user
display name, an email address, an optional reply address, a server name, a port, and an
authentication mode, which is used to authenticate to the specified SMTP server (as
required by your SMTP provider) For many non-Windows SMTP providers, anonymous
(no authentication) or basic (simple user name/password) authentication is usually
required If your provider requires Windows Authentication, the credentials under which
the SQL Server Windows service runs are supplied to the SMTP server at runtime
Instead of using the wizard, you can add a new profile via T-SQL For example, the
follow-ing three examples introduce the Database Mail stored procedures
sysmail_add_profile_sp, sysmail_add_account_sp, and sysmail_add_profileaccount_sp
The first script creates the new profile:
EXEC msdb.dbo.sysmail_add_profile_sp
@profile_name = ‘Default SQL 2008 Profile’,
@description = ‘Used for general-purpose emailing.’
The second script creates the new SMTP account:
EXEC msdb.dbo.sysmail_add_account_sp
@account_name = ‘UnleashedMailAcct1’,
Trang 8Setting Up Database Mail
@description = ‘The first SMTP Account.’,
@email_address = ‘sql2008@samspublishing.com’,
@display_name = ‘SQL 2008 Mail Account 1’,
@mailserver_name = ‘smtp.samspublishing.com’ ;
The third script associates this new account with the new profile:
EXEC msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = ‘Default SQL 2008 Profile’,
@account_name = ‘UnleashedMailAcct1’,
@sequence_number =1;
The great thing you’ll find when adding SMTP accounts is that Database Mail allows you
to provide more than one SMTP account for the same profile You can order the SMTP
accounts by priority (using the Move Up/Move Down buttons) so that if a mail send via
the top-level (or first) account fails, the second account will be used to retry sending, and
so on This is called SMTP failover priority, and there are two mail settings that control how
it works These settings, found on the Configure System Parameters screen of the wizard,
are AccountRetryAttempts and AccountRetryDelay AccountRetryAttempts specifies how
many mail send retries Database Mail will make before failing over to the SMTP account of
next-highest priority AccountRetryDelay specifies (in seconds) how long to wait between
mail send retries These features represent a big improvement in reliability over SQL Mail,
which had no such retry capabilities
After adding the new account to the profile, click Next to set up the profile security
settings on the Manage Profile Security screen Database Mail profiles have two levels of
security (with two corresponding tabs on the wizard screen):
Public—The profile can be used by all msdb users
Private—The profile can be used only by specific users or members of a specific role
(Note that to send mail, users must have DatabaseMailUserRole membership in
msdb Use sp_addrolemember to accomplish this.) Specify these users on the Private
Profiles tab of the Manage Profile Security screen
In this case, check the check box under the Public column of the data grid on the Public tab;
then click the word No under the Default Profile column A drop-down list appears, allowing
you to make the profile the default (by changing the selection to Yes) The default profile on
the server is used when you invoke sp_send_dbmail (the successor to xp_sendmail) without
specifying any profile name for the @profile_name parameter It’s a good idea to have a
default profile set up for general mailing purposes, especially when testing
To set profile security using T-SQL, run the following call to the stored procedure
sysmail_add_principalprofile_sp:
exec msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = ‘Default SQL 2008 Profile’,
Trang 9TABLE 15.1 T-SQL Stored Procedures
sysmail_delete_profile_sp Delete a profile
sysmail_delete_account_sp Delete an account
sysmail_delete_principalprofile_sp Delete the association between a profile and a
user or role (revokes permission for the principal
on use of the profile)
sysmail_delete_profileaccount_sp Delete the association between a profile and an
account sysmail_update_profile_sp Update a profile
sysmail_update_account_sp Update an account
sysmail_update_principalprofile_sp Update the association between a profile and a
user or role sysmail_update_profileaccount_sp Update the association between a profile and an
account
A third way to configure all the previously mentioned mail objects (in the form of a T-SQL
script) is to use an SMSS Database Mail query template To do this, you open the Template
Explorer via the View menu (or by pressing Ctrl+Alt+T), and then you expand to the
Database Mail folder and double-click Simple Mail Database Configuration Then you
connect to your SQL Server instance and, from the Query menu, select the Specify Values
for Template Parameters option (or press Ctrl+Shift+M) to fill in the desired parameter
values, which correspond to the parameters of the stored procedures mentioned
previ-ously
Using T-SQL to Update and Delete Mail Objects
To delete or update profiles, accounts, profile-account associations, and profile security
settings (note: do so in reverse order), you use the stored procedures shown in Table 15.1
CHAPTER 15 Database Mail
For example, to delete a profile, you execute this:
exec msdb.dbo.sysmail_delete_profile_sp @profile_name=’Undesireable Profile Name’
To update a profile’s security, changing it from the default to the nondefault profile, you
execute the following:
exec msdb.dbo.sysmail_update_principalprofile_sp
@profile_name = ‘Default SQL 2008 Profile’,
Trang 10Setting Up Database Mail
@principal_name = ‘public’,
@is_default = 0;
Alternatively, you can simply return to the wizard and select one of the Manage options to
alter or drop any of the settings or objects (Of course, under the covers, the wizard
proba-bly uses all these stored procedures.)
Setting System-wide Mail Settings
You use the Configure System Parameters screen in the Database Mail Configuration
Wizard to configure the system-wide Database Mail settings (Click Next on the Select
Configuration Task screen to reach this screen, if you haven’t already.) You’ve seen the
first two settings that appear in the grid (AccountRetryAttempts and AccountRetryDelay)
in an earlier section (“Creating Mail Profiles and Accounts”) as they relate to SMTP
failover priority These are the other four:
Maximum File Size (Bytes)—This setting specifies the maximum size of any one
email attachment
Prohibited Attachment File Extensions—This setting specifies which potentially
dangerous or undesirable attachment types to ban from exchanged emails
Database Mail Executable Minimum Lifetime (seconds)—This setting specifies
how long (minimally) the database mail process (that is, DatabaseMail.exe, which is
activated by Service Broker) should run idly before closing after it finishes emptying
the mail send queue
Logging Level—This setting specifies the quality of email auditing to use, and it
can be set to Normal (errors only), Extended (errors, warnings, and informational
messages; this is the default), or Verbose (the same as Extended, plus success
mes-sages and other mesmes-sages that are useful when you debug problems with
DatabaseMail.exe) To view Database Mail’s primary log, right-click the Database
Mail folder in the Object Browser and then click the View Database Mail Log menu
option Examine and maintain the log by using the Log File Viewer that is launched
You can also use the built-in stored procedure sysmail_delete_log_sp to clear the
log, or query the msdb sysmail_event_log view to see its contents in tabular format
To change any of these configuration settings via T-SQL script, use the
sysmail_configure_sp stored procedure sysmail_configure_sp takes two parameters: the
name of the setting (minus any spaces) and its new value The following example uses the
sysmail_configure_sp procedure to change AccountRetryDelay to two minutes:
exec msdb.dbo.sysmail_configure_sp ‘AccountRetryDelay’, 1200
Testing Your Setup
The final step in setting up Database Mail is to ask SQL Server to send a test email To do
this, right-click the Database Mail folder in the Object Browser and then click the Send