Chapter 16, “SQL Server Scheduling and Notification,” digs much deeper into configur-ing SQL Server Agent jobs and alerts, as well as usconfigur-ing Database Mail for job and alert notif
Trang 1On the left side of the alert properties dialog, you click the Response link Then you check
the Notify Operators check box and, in the Operator list, check the Email check box to
the right of the Test Database Mail Operator grid row Finally, you click OK to close and
save the new custom alert
Testing the Alert Notification
To test your new alert notification, you open a new query window in SMSS and enter the
following code:
USE AdventureWorks2008
go
RAISERROR(‘This is an alert mail test’, 10, 1) WITH LOG
go
‘This is an alert mail test’
Because you specified WITH LOG, this simple statement writes an event to the Windows
Event log, which in turn triggers the alert because the database context, message text, and
severity all match the conditions of the alert An email message should have appeared in
your inbox, indicating the alert’s successful triggering This message should contain body
text such as this:
DATE/TIME: 5/7/2009 9:00:45 PM
DESCRIPTION: Error: 50000 Severity: 10 State: 1 This is an alert
FIGURE 15.3 Creating a SQL Server event alert with a Database Mail notification
Trang 2mail test
COMMENT: (None)
JOB RUN: (None)
Related Views and Procedures
To report on the status of all your Database Mail objects without relying on wizards and
properties pages, you need some tabular views and stored procedures msdb contains many
system tables, views, and corresponding stored procedures that make this task easy The
following section lists the tables (or views) and their columns, noting the stored procedure
(if any) that you can use to read from them
Viewing the Mail Configuration Objects
The first set of msdb objects we’ll review are those related to system objects such as
profiles, profile security, and accounts:
sysmail_profile—Contains basic profile data, including the unique profile_id,
name, description, last_mod_datetime, and last_mod_user name You execute
sysmail_help_profile_sp to retrieve this data by @profile_name or @profile_id
sysmail_principalprofile—Contains profile security settings, including the
profile_id, associated principal (or user) (principal_SID), profile default status
(is_default: 1 for yes or 0 for no), last_mod_datetime, and last_mod_user name
You execute sysmail_help_principalprofile_sp to retrieve this data by
@profile_name, @profile_id, @principal_name, or @principal_id (not principal
SID) Here’s an example:
exec msdb.dbo.sysmail_help_principalprofile_sp
@profile_name=’Default SQL 2008 Profile’
sysmail_account—Contains basic account data, including the unique
account_id, name, description, email_address, display_name, replyto_address,
last_mod_datetime, and last_mod_user name You execute
sysmail_help_account_sp to retrieve this data by @account_id or @account_name
sysmail_server—Contains account SMTP server data, including the unique
related account_id and servertype, servername, port, server username, server
authentication data (credential_id), SSL status (enable_SSL), last_mod_datetime,
and last_mod_user name (sysmail_help_account_sp returns data from this table as
well.)
sysmail_servertype—Contains servertype data for accounts’ servers (SMTP is
the only currently supported type, although it seems this system was built for
exten-sibility, as the columns is_incoming and is_outgoing may leave the door open for
adding POP or IMAP servers sometime in the future.) Also includes
last_mod_datetime and last_mod_user name (sysmail_help_account_sp returns
data from this table as well.)
Trang 3To join sysmail_account, sysmail_server, and sysmail_servertype (as
sysmail_help_account_sp seems to do), you can try a query such as the following:
SELECT *
FROM msdb.dbo.sysmail_account a
JOIN msdb.dbo.sysmail_server s
ON a.account_id = s.account_id
JOIN msdb.dbo.sysmail_servertype st
ON st.servertype = s.servertype
sysmail_profileaccount—Maintains the profile-account relationship, including
the profile_id, account_id, account priority sequence_number, last_mod_datetime,
and last_mod_user name You execute sysmail_help_profileaccount_sp to retrieve
this data by @account_id, @account_name, @profile_id, or @profile_name
sysmail_configuration—Contains the system-wide mail configuration settings
(paramname, paramvalue, description), and when and by whom each was last
modi-fied (last_mod_datetime and last_mod_user name) You execute
sysmail_help_configure_sp to query this data by @parameter_name Here’s an
example:
exec msdb.dbo.sysmail_help_configure_sp
@parameter_name=’accountretrydelay’
Viewing Mail Message Data
The second set of msdb objects (and perhaps the more important ones) we’ll review are
those used to discover the status of mail messages
The first thing you need to do is to check on the status of the mail messages you’ve
attempted to send, without relying on inboxes to tell you if they’ve been received Several
views in msdb enable this, most of which may be filtered by mail account, sending user,
send date, status, and more To begin this process, you query the view sysmail_allitems,
which contains all the data about your messages (subjects, recipients, importance, and so
on) as well as send_request_date, sent_date, and sent_status Here’s an example:
SELECT mailitem_id, subject, sent_status
FROM msdb.dbo.sysmail_allitems
go
mailitem_id subject sent_status
———————————————————————————————————————-1 Database Mail Test sent
2 C Adams, Contact Info sent
3 XAML for HL Touring Seat/Saddle attached sent
4 SQL Server Job System: ‘Database Mail Test Job’ sent
(4 row(s) affected)
Trang 4Because all these messages have a sent_status of sent, the contents of this recordset are
analogous to what you’d find if you queried the view sysmail_sentitems But suppose
your sent_status column read failed In that case, you’d start by querying the
sysmail_faileditems view (a subset of sysmail_allmailitems) in conjunction with
sysmail_event_log (which contains the detailed textual reasons why failures have
occurred) Here’s an example:
SELECT f.subject, f.mailitem_id, l.description
FROM msdb.dbo.sysmail_event_log l
JOIN msdb.dbo.sysmail_faileditems f
ON f.mailitem_id = l.mailitem_id
WHERE event_type = ‘error’
ORDER BY log_date
go
subject mailitem_id description
—————————————————————————————————————————-Database Mail Test 3 The mail could not be sent because[ ]the
string is not in the form required for an e-mail address
(1 row(s) affected)
Note that the quality of the contents of sysmail_event_log depends on the Log Level
system-wide mail configuration setting (discussed earlier in the section “Setting
System-wide Mail Settings”) The Log File Viewer also uses this table’s contents To permanently
delete its contents, you use the stored procedure sysmail_delete_log_sp
To query how many messages are queued (waiting to be sent) and for how long, you use
the sysmail_unsentitems view Here’s an example:
SELECT
mailitem_id,
subject,
DATEDIFF(hh, send_request_date, GETDATE()) HoursSinceSendRequest
FROM msdb.dbo.sysmail_unsentitems
If you’re unsure why messages aren’t being sent, you can try the following:
Execute sysmail_help_queue_sp, whose resulting state column tells the state of the
mail transmission queues: INACTIVE (off) or RECEIVES_OCCURRING (on) To see the
status for only the mail (outbound) or status (send status) queues, you use the
@queue_type parameter
Execute sysmail_help_status_sp, whose resulting Status column tells you the state
of Database Mail itself: STOPPED or STARTED
Trang 5Summary
This chapter showed how Database Mail has elevated the status of emailing with SQL
Server from somewhat difficult to use to enterprise class Microsoft has achieved this goal
by relying on cross-platform industry standards, by making configuration easy, by
provid-ing a comprehensive set of system objects for storage and trackprovid-ing, by addprovid-ing failover
capability, and by utilizing the Service Broker infrastructure
Chapter 16, “SQL Server Scheduling and Notification,” digs much deeper into
configur-ing SQL Server Agent jobs and alerts, as well as usconfigur-ing Database Mail for job and alert
notifications
Trang 6SQL Server Scheduling
and Notification
What’s New in Scheduling and Notification
Configuring the SQL Server Agent
Viewing the SQL Server Agent Error Log
SQL Server Agent Security Managing Operators Managing Jobs Managing Alerts Scripting Jobs and Alerts Multiserver Job Management Event Forwarding
Automation is the key to efficiency, and the SQL Server
Agent is your automation tool in SQL Server 2008 This
chapter delves into the administrative capabilities of the
SQL Server Agent and its capability to schedule server
activ-ity and respond to server events
The SQL Server Agent, which runs as a Windows service, is
responsible for running scheduled tasks, notifying operators
of events, and responding with predefined actions to errors
and performance conditions The SQL Server Agent can
perform these actions without user intervention, utilizing
the following:
Alerts—Alerts respond to SQL Server or user-defined
errors, and they can also respond to performance
conditions An alert can be configured to run a job as
well as notify an operator
Jobs—A job is a predefined operation or set of
opera-tions, such as transferring data or backing up a
trans-action log A job can be scheduled to run on a regular
basis or called to run when an alert is fired
Operators—An operator is a user who should be
noti-fied when an alert fires or a job requests notification
The operator can be notified by email, by pager, or via
the NET SEND command
Trang 7NOTE
The SQL Server Agent is not supported with the SQL Server Express Edition or SQL
Server Express Advanced Edition It is supported in all the other editions of SQL
Server 2008, however You can use the Windows Task Scheduler as an alternative for
scheduling when using the SQL Server Express Editions The Task Scheduler has basic
scheduling capabilities but does not compare to the robust features found in the SQL
Server Agent
What’s New in Scheduling and Notification
A new feature added to SQL Server 2008 Scheduling and Notification is the capability to
execute PowerShell scripts PowerShell is a command-line scripting language that allows
administrators to achieve greater control and productivity SQL Server 2008 comes with
several PowerShell snap-ins that give you access to a variety of SQL Server objects Scripts
that are written to access these objects can be run from SQL Server jobs using the new
PowerShell job type You can find a more detailed discussion of PowerShell’s capabilities in
the next chapter, “Administering SQL Server 2008 with PowerShell.”
Policy-Based Management is another new feature in SQL Server 2008 This feature does
not fall directly under Scheduling and Notification, but it provides related management
features For example, some of the multiserver concepts discussed later in this chapter can
be replaced or augmented through the use of Policy-Based Management This feature is
covered in Chapter 22, “Administering Policy Based Management.”
Configuring the SQL Server Agent
The primary configuration settings for the SQL Server Agent are located within the Object
Explorer and SQL Server Configuration Manager Most of the settings that define how the
SQL Server Agent will execute are defined via the SQL Server Agent Properties accessible
from the Object Explorer The SQL Server Configuration Manager contains settings related
to the SQL Server Agent’s service The service settings are limited but contain important
properties such as the Startup Account for the SQL Server Agent
Configuring SQL Server Agent Properties
Figure 16.1 shows the SQL Server Agent Properties dialog that appears when you
right-click and select Properties on the SQL Server Agent node located on the root of the
Object Explorer tree
You can set several different types of properties in the SQL Server Agent Properties dialog
The General options are displayed by default, and they include the capability to set the
Trang 8FIGURE 16.1 SQL Server Agent properties
auto restart options and define an error log for the SQL Server Agent Selecting the option
Auto Restart SQL Server Agent If It Stops Unexpectedly is best for most installations There
is usually a heavy dependency on the Agent performing its actions, and you probably
want the service to be restarted if it has been inadvertently stopped
The Advanced page contains options for event forwarding and idle CPU conditions The
event forwarding options are discussed in detail in the section “Event Forwarding,” later
in this chapter The idle CPU options define conditions related to the execution of jobs
that have been set up to run when the CPU is idle You can define idle CPU conditions
such as the average CPU percentage that the CPU must be below to be considered idle
The Alert System page is related to configuring email notification and is discussed in the
“Configuring Email Notification” section, later in this chapter
The Job System page has an option to set the shutdown time-out interval This option
determines the amount of time the SQL Server Agent waits for jobs to complete before
finalizing the shutdown process There is also an option related to proxy accounts
discussed in the “SQL Server Agent Proxy Account” section, later in this chapter
The Connection page includes an option to set an alias for the local host server This
option is useful if you cannot use the default connection properties for the local host and
need to define an alias instead
Trang 9The History page options are related to the amount of job history that will be retained
You have the option to limit the size of the job history log and/or remove job history that
is older than a set period of time
TIP
Careful attention should be given to the amount of history that is retained Every time
a job is run, the history of that execution and the related detail is saved The need for
careful monitoring is particularly true when dealing with SQL Server instances that have
a large number of databases The msdb database contains the job history records and
can become sizable over time if the history is not removed For example, we have seen
environments where close to 700 databases were installed on one SQL Server
instance The company was performing SQL Server log backups every 15 minutes on
each of these databases and full backups each night When you do the math (4 log
backups/hour * 700 databases = 2800 backups/hour), you can see that the amount
of history written to the msdb database can be significant
Configuring the SQL Server Agent Startup Account
The startup account defines the Microsoft Windows account the SQL Server Agent service
uses The selection of this account is critical in defining the level of security that the SQL
Server Agent will have Access to resources on the server on which SQL Server is running
and access to network resources are determined by the startup account This selection is
particularly important in cases in which the SQL Server Agent needs to access resources on
other machines Examples of network access that the SQL Server Agent might need
include jobs that write backups to a drive on another machine and jobs that look for files
found on other servers on the network
The startup account for the SQL Server Agent is set initially during the installation of SQL
Server, but you can change it by using several different tools such as the Windows Service
Control Manager and SQL Server Configuration Manager The Windows Service Control
Manager is a good tool for viewing all the services on your server, but changes to the SQL
Server services are better made through the SQL Server Configuration Manager The
Configuration Manager is more comprehensive and makes additional configuration
settings, such as Registry permissions, that ensure proper operation
The SQL Server Configuration Manager is a consolidated tool that allows you to manage
network options and services related to SQL Server To launch this tool, you select Start,
Microsoft SQL Server 2008, Configuration Tools Figure 16.2 shows an example of the
Configuration Manager with the SQL Server 2008 services selected for viewing To change
the startup account for the SQL Server Agent, you can right-click on its service and select
Properties
The startup account used by the SQL Server Agent is initially determined during the
instal-lation of SQL Server You have the option of choosing one of several built-in accounts, or
you can select a domain account The built-in accounts are available by default and do not
Trang 10FIGURE 16.2 SQL Server Agent service properties
require any network administration to use them These accounts, however, should be used
with caution because they can provide network access to the SQL Server Agent that may
not be desired Generally, you want to provide the minimum amount of security necessary
for the SQL Server Agent to perform its tasks
The recommended startup account for the SQL Server Agent is a Windows account You
specify a Windows startup account for SQL Server Agent by using the This Account option
on the Service Properties window The Windows account can be a local user account or
domain user account It must be a member of the SQL Server sysadmin fixed server role on
the local SQL Server instance The use of this type of startup account provides the most
flexibility and allows you to tailor the network and local resources that the SQL Server
Agent has permission to access
The Windows account does not have to be a member of the Windows administrators
group In fact, exclusion from the administrators group is recommended in most cases
This approach adheres to the principle of least privileges, which says that you should limit
the amount of security provided to only that which is needed In many cases, inclusion in
the administrators group is not needed and only increases exposure to security threats
The Windows account you choose with the This Account option must have certain
secu-rity rights to be able to function as the startup account for SQL Server The account must
have permission to log on as a service You can set this permission and others by using the
Local Security Policy application, which can be found under Administrative Tools You can
select the Local Policies node and then select User Rights Assignment to display a list
of all the security settings, including Log On as a Service Policy You should make sure the
account you chose or the group that it is in is included in this policy
TIP
The Local Security Policy editor can be hard to find In most operating systems, you can
click Start Run then enter secpol.msc to launch the Local Security Policy editor