4. Working with
SQL Server Agent
SQL Saturday Night #11
Sep 17, 2011
Antonios Chatzipavlis
Solution Architect - Principal Consultant
SQL Server Evangelist & MVP
MCT, MCITP, MCPD, MCSD, MCDBA, MCSA, MCTS, MCAD, MCP, OCA
SQL Saturday Night #11
5. Antonios G. Chatzipavlis
• 1982 – The first contact with computers.
• 1988 – I started my professional carrier in IT, especially in
software development.
• 1998 – I earned my 1st Certification as MCSD (3rd in Greece)
• Since then I certified as MCP, MCSD, MCT, MCDBA, MCAD, MCTS,
MCITP, MCPD, MCSA, and OCA.
• 1999 – I started my Trainer carrier as MCT
• Since then I have more than 13.500 hours of training
• 2010 – I became for first time Microsoft MVP on SQL Server.
also
• Leader of MCT Europe Greek Chapter
• Moderator of autoexec.gr
• Member of the dotNETZone.gr
SQL Saturday Night #11
6. Agenda
• What is the SQL Server Agent
• Configuring SQL Server Agent
• Security for SQL Server Administration
• Tools for Automating Administrations
• Monitoring and Responding to Events
• Automating Administration Across an Enterprise
SQL Saturday Night #11
7. What is the SQL Server Agent
• Overview of SQL Server Agent
• Components of Automatic Administration
• Jobs
• Schedules
• Alerts
• Operators
SQL Saturday Night #11
8. Overview of SQL Server Agent
SQL Server Agent is the component of SQL Server
that is responsible for automation
• Run as Windows Service
• Must be running to
• Execute jobs
• Fire alerts
• Contact operators
• Start Mode should be set to Automatic
SQL Saturday Night #11
9. Jobs
A job is a specified series of actions
that SQL Server Agent performs
• You can run jobs in several ways:
• According to one or more schedules
• In response to one or more alerts
• By executing the sp_start_job stored procedure
SQL Saturday Night #11
10. Schedules
A schedule specifies when a job runs.
More than one job can run on the same schedule,
and
more than one schedule can apply to the same job.
• A schedule can define the following conditions for
the time when a job runs:
• Whenever SQL Server Agent starts.
• Whenever CPU utilization of the computer is at a level you
have defined as idle.
• One time, at a specific date and time.
• On a recurring schedule.
SQL Saturday Night #11
11. Alerts
An alert is an automatic response
to a specific event.
• An alert can respond to one of the following
conditions:
• SQL Server events
• SQL Server performance conditions
• WMI events on the computer where SQL Server Agent is
running
• An alert can perform the following actions:
• Notify one or more operators
• Run a job
SQL Saturday Night #11
12. Operators
An operator defines contact information for
an individual responsible for the maintenance
of one or more instances of SQL Server.
• SQL Server can notify operators of alerts through
one or more of the following:
• E-mail
• Pager (through e-mail)
• net send
SQL Saturday Night #11
13. Configuring SQL Server Agent
• Starting, Stopping, and Pausing SQL Server Agent Service
• Selecting an Account for the SQL Server Agent Service
• Service Account Types Supported for SQL Server Agent
• Windows Domain Account Permissions
• Using the SQL Server Agent Error Log
• Managing Services
• Using Performance Objects
SQL Saturday Night #11
14. Starting, Stopping, and Pausing
SQL Server Agent Service
• Using SQL Server Configuration Manager
(preferred)
• net Commands
SQL Saturday Night #11
15. Selecting an Account for the
SQL Server Agent Service
• Built-in accounts
Local System Local Service Network Service
• The name of NT • The SQL Server Agent service The name of NT
•
AUTHORITYSystem windows cannot be run under this account. AUTHORITYNetworkService
account • It is not supported because it windows account
• Has unrestricted access to all local •
accesses network resources as aAll services that run under the
null
system resources session with no credentials Network Service account are
• Member of Windows Administrators authenticated to network resources
group on local computer as the local computer
• Member of SQL Server sysadmin • Because multiple services can use
server role the Network Service account, it is
• Provided for backward compatibility difficult to control which services
• Has permissions that SQL Server have access to network resources
Agent does not require
• This account (Windows Account)
• Recommended option
• Use a Windows user account that is not a member of the
Windows Administrators group
SQL Saturday Night #11
16. Service Account Types Supported for
SQL Server Agent
Domain
Non-clustered Clustered
Service account type controller
Server server
(non-clustered)
Microsoft Windows domain account
Supported Supported Supported
(member of Windows Administrators group)
Windows domain account Supported Supported Supported
(non-administrative) 1 1 1
Network Service account Supported Not Not
(NT AUTHORITYNetworkService) 1, 3, 4 supported supported
Local user account Supported Not Not
(non-administrative) 1 supported applicable
Local System account Supported Not Supported
(NT AUTHORITYSystem) 2 supported 2
Local Service account Not Not Not
(NT AUTHORITYLocalService) supported supported supported
1. Using Non-administrative Accounts for Multiserver Administration
2. Using the Local System Account for Multiserver Administration
3. Using the Network Service Account When It Is a SQL Server User
4. Using the Network Service Account When SQL Server Reporting Services Is Running on the Same Computer
SQL Saturday Night #11
17. Windows Domain Account Permissions
• Log on as a service
• Must be a member of the sysadmin fixed server role.
• To use multiserver job processing, must be:
• a member of the TargetServersRole database role in msdb on
the master server
• Required permissions for SQL Server Agent proxies
support:
• Permission to act as part of the operating system (SeTcbPrivilege) (only
on Windows 2000)
• Permission to bypass traverse checking (SeChangeNotifyPrivilege)
• Permission to replace a process-level token
(SeAssignPrimaryTokenPrivilege)
• Permission to adjust memory quotas for a process
(SeIncreaseQuotaPrivilege)
• Permission to log on using the batch logon type (SeBatchLogonRight).
SQL Saturday Night #11
18. Using the SQL Server Agent Error Log
• Error log records warnings and errors by default.
• Warnings and errors displayed in the log:
• Warning messages that provide information about potential
problems
• Error messages that usually require intervention by a
system administrator
• SQL Server maintains up to nine SQL Agent error
logs
• Execution trace messages are not written to error
log
• Consider carefully what value you obtain by capturing
execution trace messages to the error log
• You can cycle the SQL Server Agent log at any time
SQL Saturday Night #11
19. demo
SQL Server Agent Error Log
SQL Saturday Night #11
20. Managing Services
• The SQL Server Agent service and the SQL Server service
monitor each other.
• After both services have started, if one service fails, the other service
restarts the failed service
• Auto-restart should not be enabled for the SQL Server service
or the SQL Server Agent service on failover cluster instances.
• Jobs that are running at the time of a failover event on a SQL
Server failover cluster instance do not resume after failover to
another failover cluster node.
• Jobs that are running at the time a Hyper-V node is paused
do not resume if the pause causes a failover to another node.
• Jobs that begin but fail to complete because of a failover
event are logged as started,
• Do not show additional log entries for completion or failure.
• SQL Server Agent jobs in these scenarios appear to have never ended.
SQL Saturday Night #11
21. Using Performance Objects
• SQLAgent:Jobs
• Performance information about jobs that have been started,
success rates, and current status
• SQLAgent:JobSteps
• Status information about job steps
• SQLAgent:Alerts
• Information about number of alerts and notifications
• SQLAgent:Statistics
• General performance information
SQL Saturday Night #11
22. Security for
SQL Server Administration
• SQL Server Agent Fixed Database Roles
• SQL Server Agent Proxies
• SQL Server Agent Subsystems
SQL Saturday Night #11
23. SQL Server Agent Fixed Database Roles
• SQLAgentUserRole
• Control permission for jobs and schedules that they own
• SQLAgentReaderRole
msdb
• All permissionsSQLAgentUserRole SQLAgentReaderRole SQLAgentReaderRole
of the SQLAgentUserRole plus permission
to view the list of all available jobs and job schedules
(owned schedules
(owned jobs only)
Job schedules
Job schedules
Job schedules
Local jobs
Local jobs
Local jobs
Operators
Operators
Operators
Proxies
Proxies
Proxies
• SQLAgentOperatorRole
only)
Action
• Permission to manage local jobs , view properties for
operators and proxies, and enumerate Y N N proxies
Create/modify/delete N Y Y N N Y N available Y N
and alerts
View list (enumerate) Y Y Y Y Y Y Y Y Y Y Y Y
Enable/disable N Y Y NA N Y N Y N N Y N
View properties N Y Y N N Y Y Y Y Y Y Y
Execute/stop/start NA Y NA NA N Y N Y N N Y N
View job history NA Y NA NA NA Y N NA NA NA Y N
Delete job history NA N NA NA NA Y Y NA NA NA Y Y
Attach/detach NA NA Y NA NA N N NA NA NA Y N
SQL Saturday Night #11
24. SQL Server Agent Proxies
• SQL Server Agent uses proxies to manage security
contexts
• Each proxy corresponds to a security credential.
• Credentials to store information about Windows user
accounts.
• The user specified in the credential must have "Log
on as a batch job" permission on the computer on
which SQL Server is running.
• Each proxy can be associated with a set of
subsystems and a set of logins.
• The proxy can be used only for job steps that use a
subsystem associated with the proxy.
SQL Saturday Night #11
25. SQL Server Agent Subsystems
• Is a predefined object that represents a set of
functionality available to a SQL Server Agent proxy
• Subsystems provide security because they delimit
access to the functionality that is available to a proxy
Subsystem name Description
Microsoft ActiveX Script Run an ActiveX scripting job step. REMOVED IN FUTURE VERSIONS
Operating System (CmdExec) Run an executable program.
PowerShell Run a PowerShell scripting job step.
Because Transact-SQL jobthe replication Distribution Agent.
Replication Distributor Run a job step that activates steps do not use
Replication Merge Run a job step that activates the replication Merge Agent.
proxies, there job step that SQLthe replication Queue Reader Agent.
Replication Queue Reader Run a
is no activates Server Agent
subsystem fora job step that activates the replication Snapshot Agent.
Replication Snapshot Run Transact-SQL job steps.
Replication Transaction Log Reader Run a job step that activates the replication Log Reader Agent.
Analysis Services Command Run an Analysis Services command.
Analysis Services Query Run an Analysis Services query.
SSIS package execution Run an SSIS package.
SQL Saturday Night #11
26. Tools for
Automating Administrations
• Maintenance Plan
• Implementing Jobs
• Monitoring Jobs Activity
SQL Saturday Night #11
27. Maintenance Plan
• Helps you set up the core maintenance tasks to
make sure that your database performs well
• To create or manage maintenance plans, you must
be a member of the sysadmin fixed server role
• You can perform the following tasks:
• Reorganize the data on the data and index pages by
rebuilding indexes
• Compress data files by removing empty database pages
• Update index statistics
• Perform internal consistency checks
• Back up the database and transaction log files
• Run SQL Server Agent jobs
SQL Saturday Night #11
29. Implementing Jobs
• A job is a specified series of operations performed
sequentially.
• A job can perform a wide range of activities
• Jobs can run repetitive or schedulable tasks
• Automatically notify users of job status
• To create a job user must be a member of one of
• SQLAgentUserRole
• SQLAgentReaderRole
• SQLAgentOperatorRole
• or sysadmin fixed server role.
• A job can be edited only by its owner or members of the
sysadmin role
• Jobs can be written to run on the local instance of SQL
Server or on multiple instances across an enterprise
SQL Saturday Night #11
31. Monitoring Jobs Activity
• SQL Server Agent creates a new session each time
the service starts.
• Information about these sessions is stored in the
syssessions table of the msdb database
• When a new session is created, the sysjobactivity
table in the msdb database is populated with all the
existing defined jobs.
• Jobs Activity Monitor
SQL Saturday Night #11
32. demo
Monitoring Jobs Activity
SQL Saturday Night #11
33. Monitoring and Responding
to Events
• Overview of Alerts
• Alert Event Types
• Overview of Operators
• Fail-Safe Operator
SQL Saturday Night #11
34. Overview of Alerts
• Events are generated by SQL Server and entered
into the Microsoft Windows application log.
• SQL Server Agent reads the application log and
compares events written there to alerts that you
have defined.
• When SQL Server Agent finds a match, it fires an
alert, which is an automated response to an event.
SQL Saturday Night #11
35. Alert Event Types
• SQL Server events
• Error number
• Severity level
• Database
• Event text
• SQL Server performance conditions
• Object
• Counter
• Instance
• Alter if counter and Value
• WMI events
• Namespace
• Query
SQL Saturday Night #11
36. Overview of Operators
• Operators are aliases for people or groups that can
receive electronic notification when jobs have
completed or alerts have been raised
• Operators can be notified by
• Email
• DB Mail (SMTP)
• SQL Mail (Extended MAPI)
• Pager
• Paging is implemented by e-mail
• Must install software on the mail server that processes inbound mail
and converts it to a pager message
• net send command
• net send is NOT available in Windows Server 2008 R2
Pager & net send will be removed in a future versions
SQL Saturday Night #11
37. Fail-Safe Operator
• The fail-safe operator receives an alert notification after
all pager notifications to the designated operators have
failed
• The fail-safe operator is notified when:
• The operators responsible for the alert could not be paged.
• Reasons for failure to reach primary operators include incorrect pager
addresses and off-duty operators.
• SQL Server Agent cannot access system tables in the msdb
database.
• The sysnotifications system table specifies operator responsibilities for
alerts.
• The fail-safe operator is a security feature.
• You cannot delete the operator assigned to fail-safe duty
without reassigning fail-safe duty to another operator, or
deleting the fail-safe assignment altogether.
SQL Saturday Night #11
38. demo
Alerts & Operators
SQL Saturday Night #11
39. Automating Administration Across
an Enterprise
• Overview of Multiserver Environment
• Choosing the Right SQL Server Agent Service Account for
Multiserver Environments
• Setting Encryption Options on Target Servers
• Polling Intervals
• Event forwarding
SQL Saturday Night #11
40. Overview of Multiserver Environment
• One master server
• At least one target server
• Master server distributes jobs to, and receives
events from, target servers.
• Master server also stores the central copy of job
definitions for jobs that are run on target servers.
• Target servers connect periodically to the master
server to update their schedule of jobs.
• If a new job exists on the master server, the target server
downloads the job.
• After the target server completes the job, it reconnects to
the master server and reports the status of the job
SQL Saturday Night #11
41. Choosing the Right SQL Server Agent Service
Account for Multiserver Environments
• If you run the SQL Server Agent service under an
account that is not a member of the local Windows
Administrators group, enlisting target servers to master
servers may fail
• "The enlistment operation failed."
• Restart the SQL Server and the SQL Server Agent services to resolve
this issue.
• When the SQL Server Agent service is run under the
Local System account, master server-target server
operations are supported only if both the master server
and the target server reside on the same computer
• "Ensure the agent start-up account for
<target_server_computer_name> has rights to log on as
targetServer."
• You can ignore this informational message. The enlistment operation
should complete successfully.
SQL Saturday Night #11
42. Setting Encryption Options on Target
Servers
• If you cannot use a certificate for Secure Sockets
Layer (SSL) encrypted communications between
master servers and some or all of your target
servers, but you want to encrypt the channel
between them
• HKEY_LOCAL_MACHINESOFTWAREMicrosoft
Microsoft SQL Server
<instance_name>SQLServerAgent
MsxEncryptChannelOptions(REG_DWORD)
Value Description
Disables encryption between this target server and the master server. Choose this option only
0 when the channel between the target server and master server is secured by another means.
Enables encryption only between this target server and the master server, but no certificate
1 validation is required.
Enables full SSL encryption and certificate validation between this target server and the master
2 server. This setting is the default. Unless you have specific reason to choose a different value, we
recommend not changing it.
SQL Saturday Night #11
43. Polling Intervals
• The polling interval controls how frequently the
target server connects to the master server to
download instructions and upload the results of job
execution.
• Target server polls the master server and reads the
operations assigned to from the sysdownloadlist
table in the msdb database.
• Operations are posted to the sysdownloadlist table
in either of the following ways:
• Explicitly by using the sp_post_msx_operation stored
procedure.
• Implicitly by using other job stored procedures.
SQL Saturday Night #11
44. Event forwarding
• Advantages Guidelines for Using an Event forwarding
• Centralization
• Avoid running critical or heavily used
• Scalability. applications on the alerts management
• Efficiency. server.
• Carefully plan for the network traffic
• Disadvantages involved in configuring many servers to
• Increased traffic share the same alerts management
server.
• Single point of
failure. • Define alerts on the local instance of
• Server load. SQL Server that require a server-
specific response, instead of forwarding
the alerts to the alerts management
server.
• After configuring your alert system,
periodically check the Microsoft
Windows application log for SQL Server
Agent events.
SQL Saturday Night #11
45. demo
Implementing Multiserver Environment
SQL Saturday Night #11
Selecting an Account for the SQL Server Agent Service
To view SQL Server Agent error logIn Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.Expand SQL Server Agent, expand Error Logs, right-click the error log you want to view, and then click View Agent Log.In the Select logs pane, click a type of logged item to filter the log contents.Optionally, click the Filter button and enter parameter values in the Filter Settings dialog box to filter the log contents.Check Apply Filter if you have selected filter parameters, and click OK in the Filter Settings dialog box.Under Log file summary, view the log contents.To rename a SQL Server Agent error logIn Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.Expand SQL Server Agent.Right-click Error Logs and select Configure.In the Error log file box, enter the new path and file name, or find it using the browse (...) button.SQL Server Agent will not write to the new log file until the SQL Server Agent service is restarted.To send SQL Server Agent error messagesIn Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.Right-click SQL Server Agent, and then click Properties.On the General page, in the Net send recipient box, type the user name or computer name. The Microsoft Windows Messenger service must be running to receive net send events.To write execution trace messages to the SQL Server Agent error logIn Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.Right-click SQL Server Agent, and then click Properties.On the General page, check Include execution trace messages.Because this option can cause the error log to become large, set it only when investigating a specific SQL Server Agent problem.
Selecting an Account for the SQL Server Agent Service
Selecting an Account for the SQL Server Agent Service
Selecting an Account for the SQL Server Agent Service
select * from msdb.dbo.sysjobactivityselect * from msdb.dbo.syssessionsShow job activity monitor