MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
Day -17
Topic: SQL Server Agent
Mind Map
Configure SQL Server Agent
• Initial Setup (Configuration Manager)
o Open SQL Server Configuration Manager
o Select SQL Server Agent Service
o Logon Settings
▪ Local Account (Single Server)
▪ Managed Service Account (network)
▪ Group Managed Service Account (multiple servers)
o Startup Mode: Automatic (Crucial)
• Agent Properties (SSMS)
o Right-click SQL Server Agent in Object Explorer
o Select Properties
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
o General Tab
▪ Auto Restart SQL Server (unexpected stop)
▪ Auto Restart Agent (unexpected stop)
▪ Error Log Location
o Advanced Tab
▪ SQL Event Forwarding
• Forward events to different server
• Specify event types (unhandled, All)
• Specify event level (Severity 1, 17+ common)
▪ Idle CPU Condition
• Define idle for jobs
• Default: CPU<10% for 10 min
• Customize based on server behaviour
• Monitor CPU (resource monitor, perfmon, task manager)
o Alert System Tab
▪ Mail System: Database Mail
▪ Select Mail Profile (pre-configured)
▪ Used for job notifications
• Define Jobs
• Purpose
o Automate Administrative Tasks
o Reduce TCO
o Execute scheduled tasks (jobs)
• Nature
o Microsoft windows service
• Components
o Jobs
▪ Series of actions
▪ Define administrative tasks
▪ Run on local / remote servers
▪ Executive Methods
• Schedules
• Alert
• Sp start_job procedure
▪ Job Steps
• Individual actions
• Run T-SQL
• Execute SSIS package
• Run Analysis Services command
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
o Schedules
▪ Specify when job runs
▪ Multiple jobs run share
▪ Multiple schedules for one jobs
▪ Run Conditions
• Agent startup
• CPU utilization idle
• One time at specific date/time
• Recurrent schedule
o Alerts
▪ Automatic response to event
▪ Event ex: job starts, system resources threshold
▪ Respond to
• SQL Server events
• SQL Server performance conditions
• WMI (Windows Management Instrumentation)
▪ Action
• Notify operators
• Run a job
o Operators
▪ Contact for individuals / groups
▪ Responsible for SQL Server instance maintenance
▪ Notification Methods
• Emails (common)
• Pager (option)
• User Access
o Must be member of sql server agent roles
o SQL Agent User Role
o SQL Agent Reader Role
o SQL Agent Operator Role
SQL Server Agent: The Engine Behind Automation
Overview
SQL Server Agent is a built-in SQL Server component designed to automate and
schedule routine database tasks. Running as a dedicated Windows service, it
empowers administrators and developers to offload repetitive workloads such as
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
backups, maintenance plans, ETL operations, alerts, and more—all triggered by time or
system events.
Core Features
1. Job Scheduling
• Create one-time or recurring jobs.
• Schedule jobs based on time intervals (daily, weekly, monthly).
• Trigger jobs based on system startup or idle events.
2. Multi-Step Job Execution
• Each job can consist of multiple steps, such as:
o Executing T-SQL statements.
o Launching SSIS packages.
o Running PowerShell or OS-level commands.
• Jobs can be set to continue, fail, or retry depending on each step’s outcome.
3. Event-Driven Automation
• Use alerts tied to SQL Server error logs or performance conditions.
• Trigger corrective actions (e.g., restart a service, notify admins).
4. Notifications & Alerts
• Configure email notifications (via Database Mail) or Windows alerts.
• Notify operators on job success, failure, or completion.
5. Monitoring & Logging
• Built-in logging of job history.
• View execution durations, outcomes, and messages per step.
6. Security
• Use proxies and credentials to allow jobs to perform actions outside SQL
Server (e.g., file system access).
• Granular permissions for who can create, edit, or execute jobs.
7. Integration with SSMS
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
• Manage all aspects of jobs, alerts, schedules, and operators via SQL Server
Management Studio GUI.
• Convenient for non-scripted administrative tasks.
Why SQL Server Agent Matters
Benefit Description
Eliminates manual intervention for tasks like backups and
Automation
imports
Efficiency Improves resource usage by running jobs in off-peak hours
Reliability Ensures consistent job execution even after server restarts
Proactive Detects and responds to error conditions, helping prevent
Management downtime
Security Control Restricts task scope using proxy accounts and job ownership
🛠 How to Configure SQL Server Agent
Step 1: Enable & Start the Agent Service
• Go to SQL Server Configuration Manager.
• Locate SQL Server Agent (InstanceName) and set the Startup Type to
Automatic.
• Start the service.
Alternatively, in SSMS Object Explorer, right-click SQL Server Agent → Start.
Step 2: Configure Database Mail (Optional)
• Required for sending alerts and notifications.
• Configure under Management → Database Mail.
Step 3: Create a Job via SSMS
1. Expand SQL Server Agent → Jobs.
2. Right-click Jobs → New Job.
3. In the General tab, name the job.
4. Under Steps, define one or more actions (T-SQL, SSIS, PowerShell).
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
5. Under Schedules, set when the job runs.
6. Optionally, configure alerts and notifications.
7. Click OK to save.
T-SQL Example: Create and Schedule a Job
USE msdb;
EXEC sp_add_job
@job_name = N'DatabaseBackupJob';
EXEC sp_add_jobstep
@job_name = N'DatabaseBackupJob',
@step_name = N'Backup Step',
@subsystem = N'TSQL',
@command = N'BACKUP DATABASE [YourDB] TO DISK = ''C:\Backups\[Link]''';
EXEC sp_add_schedule
@schedule_name = N'DailyBackupSchedule',
@freq_type = 4, -- Daily
@freq_interval = 1,
@active_start_time = 020000; -- 2 AM
EXEC sp_attach_schedule
@job_name = N'DatabaseBackupJob',
@schedule_name = N'DailyBackupSchedule';
EXEC sp_add_jobserver
@job_name = N'DatabaseBackupJob';
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
Troubleshooting Tips
• Agent Not Running? → Check SQL Server Configuration Manager or service
status in SSMS.
• Notifications Not Working? → Verify Database Mail profiles and operator
setup.
• Permission Errors? → Review proxy accounts and job owner permissions.
• 🕰 Jobs Not Firing? → Check schedule settings and server time zone alignment.
Final Thoughts
SQL Server Agent is the heartbeat of SQL Server automation. It plays a vital role in:
• Ensuring data integrity through backups.
• Supporting data movement and reporting workflows.
• Providing early warning through alerting mechanisms.
Whether you’re managing a single database or an enterprise fleet of SQL Server
instances, mastering SQL Server Agent is a fundamental part of administering a reliable
and efficient environment.
# SQL Server Agent Components: A Comprehensive Guide
## Overview
**SQL Server Agent** is a key component of Microsoft SQL Server that enables the
automation of routine tasks such as backups, ETL, report generation, and system
monitoring. It acts as a scheduling and alerting mechanism, ensuring your SQL Server
environment runs smoothly and reliably—even during off-hours.
This chapter explores the key components of SQL Server Agent, how they interact, and
provides T-SQL examples for effective auditing and configuration.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
## Key SQL Server Agent Components
### Jobs
A **job** is a defined sequence of tasks (called job steps) that SQL Server Agent
performs. Jobs can execute:
- T-SQL scripts
- SSIS packages
- PowerShell scripts
- External applications
They can be triggered:
- On a schedule
- By an alert condition
- Manually via `sp_start_job`
**Important Caveat**
In cluster or failover scenarios, jobs running during a node transition may not resume or
complete. Always design jobs to be restartable and monitor logs.
#### T-SQL: View All Jobs on a Server
USE msdb;
GO
SELECT job_id, [name] FROM [Link];
Job Steps
Each job step defines an individual action. These may include:
• Running a query
• Importing data
• Sending messages
Each step runs under a specific security context using either:
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
• The EXECUTE AS clause (for T-SQL)
• A proxy account (for non-T-SQL tasks)
T-SQL: View Steps for a Specific Job
SELECT
s.step_id,
s.step_name,
[Link],
[Link]
FROM [Link] s
INNER JOIN [Link] j ON s.job_id = j.job_id
WHERE [Link] = 'YourJobName';
Schedules
A schedule dictates when and how often a job runs. You can configure:
• One-time execution
• Recurring intervals (daily, weekly)
• Event-based triggers (agent start, idle time)
Multiple jobs can share a single schedule, and a job can have multiple schedules.
T-SQL: Create a Daily Schedule
EXEC [Link].sp_add_schedule
@schedule_name = N'DailySchedule',
@enabled = 1,
@freq_type = 4, -- Daily
@freq_interval = 1,
@active_start_time = 080000; -- 8 AM
Alerts
An alert is a rule that watches for specific conditions:
• SQL Server error messages
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
• Performance thresholds
• WMI events
An alert can:
• Run a job automatically
• Notify an operator
T-SQL: Create an Alert for Severity 17 Errors (Out of Memory)
EXEC [Link].sp_add_alert
@name = N'MemoryErrorAlert',
@message_id = 0,
@severity = 17,
@enabled = 1,
@delay_between_responses = 600;
Operators
An operator represents a person or group responsible for handling job failures or alerts.
Operators can be notified via:
• Email (via Database Mail)
• Net send (deprecated)
• Pager (deprecated)
Operators don’t hold permissions or login credentials—they’re notification endpoints.
T-SQL: Create an Operator
EXEC [Link].sp_add_operator
@name = N'DBA_Admin',
@email_address = N'[Link]@[Link]';
T-SQL: Notify Operator When Job Fails
EXEC [Link].sp_update_job
@job_name = N'NightlyBackup',
@notify_level_eventlog = 2, -- Write to event log on failure
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
@notify_level_email = 2, -- Notify operator on failure
@notify_email_operator_name = N'DBA_Admin';
Managing SQL Server Agent Service
Use SQL Server Configuration Manager to:
• Set the service startup mode
• Start or stop the Agent
• Review service permissions
Alternatively, control from SSMS:
• Object Explorer → SQL Server Agent → Right-click → Start
Audit & Monitoring Tips
Use these queries for auditing:
Job History Summary
SELECT
[Link] AS JobName,
h.run_date,
h.run_time,
h.run_status,
[Link]
FROM [Link] h
INNER JOIN [Link] j ON h.job_id = j.job_id
WHERE h.step_id = 0 -- Summary for entire job
ORDER BY h.run_date DESC, h.run_time DESC;
Active Jobs
SELECT
ja.job_id,
[Link],
ja.start_execution_date,
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
ja.stop_execution_date,
ja.run_requested_date,
ja.run_status
FROM [Link] ja
INNER JOIN [Link] j ON ja.job_id = j.job_id
WHERE ja.stop_execution_date IS NULL;
Final Thoughts
SQL Server Agent is an indispensable part of the SQL Server toolkit. By mastering its
components—jobs, steps, schedules, alerts, operators—you gain the ability to build a
robust, automated, and self-healing data environment.
# Security Administration in SQL Server Agent: Roles, Subsystems, and Proxies
## Overview
SQL Server Agent is a powerful automation component in Microsoft SQL Server,
designed to execute jobs based on schedules, events, and user commands. But with
great power comes the need for precise control. That’s why **SQL Server Agent
employs a security framework** composed of roles, subsystems, and proxies to ensure
jobs run safely and with the **least privilege necessary**.
In this article, you’ll learn how Agent security is structured, how to administer it
effectively, and how to configure a secure real-world job with T-SQL and PowerShell.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
## Key Security Components
### 1Fixed Database Roles in `msdb`
| Role Name | Purpose |
|----------------------|---------|
| `SQLAgentUserRole` | Create and manage own jobs |
| `SQLAgentReaderRole` | View job history and job steps |
| `SQLAgentOperatorRole` | View job history, start/stop jobs, and manage alerts |
- These roles control access for non-`sysadmin` users.
- Membership is scoped to the `msdb` database.
#### View Assigned Roles
SELECT [Link] AS DatabaseUser, [Link] AS RoleName
FROM [Link].database_role_members drm
JOIN [Link].database_principals dp ON drm.member_principal_id = dp.principal_id
JOIN [Link].database_principals r ON drm.role_principal_id = r.principal_id
WHERE [Link] LIKE 'SQLAgent%';
2 Subsystems
Subsystems define the type of job step being executed (e.g., PowerShell, SSIS,
CmdExec). Each proxy must be authorized for one or more subsystems.
Subsystem Description
CmdExec Run OS-level commands
PowerShell Execute PowerShell scripts
SSIS Execute SSIS packages
Transact-SQL Run T-SQL (does not use proxies)
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
Subsystem Description
Replication Snapshot Start replication agents
Analysis Services Query Run MDX or DAX queries
Note: Transact-SQL steps use EXECUTE AS and do not require a proxy.
3 Proxies
Proxies allow jobs to run under specific credentials. Each proxy:
• Maps to a SQL credential
• Is granted access to one or more subsystems
• Can be shared across job steps
• Must be assigned to specific logins or roles
View Existing Proxies
SELECT proxy_id, name, credential_id
FROM [Link];
Real-World Security Example: PowerShell Job with Proxy
Use Case
You want to automate a PowerShell script that archives log files. For security:
• You’ll run the job under a non-sysadmin credential
• The job step will use the PowerShell subsystem
• A proxy will be used to bind that credential to the job
Step 1: Create a Credential
CREATE CREDENTIAL ArchiveCred
WITH IDENTITY = 'DOMAIN\UserAccount',
SECRET = 'StrongPassword123!';
Step 2: Create Proxy and Grant Subsystem Access
USE msdb;
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
EXEC sp_add_proxy
@proxy_name = 'ArchiveProxy',
@credential_name = 'ArchiveCred',
@enabled = 1;
-- Grant PowerShell subsystem access
EXEC sp_grant_proxy_to_subsystem
@proxy_name = 'ArchiveProxy',
@subsystem_id = 12; -- 12 = PowerShell
Step 3: Grant Proxy Usage to a User Role
EXEC sp_grant_login_to_proxy
@proxy_name = 'ArchiveProxy',
@login_name = 'YourLogin';
Step 4: Create Secure Job and Job Step
EXEC sp_add_job
@job_name = N'ArchiveLogsJob';
EXEC sp_add_jobstep
@job_name = N'ArchiveLogsJob',
@step_name = N'Run PowerShell Archive',
@subsystem = N'PowerShell',
@command = N'
#NOSQLPS
Import-Module SqlServer
Remove-Item "C:\Logs\*.log" -Recurse -Force
',
@proxy_name = 'ArchiveProxy';
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
EXEC sp_add_jobserver
@job_name = N'ArchiveLogsJob';
Optional: Schedule the Job
EXEC sp_add_schedule
@schedule_name = N'DailyArchiveSchedule',
@freq_type = 4, -- Daily
@active_start_time = 030000; -- 3 AM
EXEC sp_attach_schedule
@job_name = N'ArchiveLogsJob',
@schedule_name = N'DailyArchiveSchedule';
Additional Notes
• Starting with SQL Server 2019, prefix your PowerShell script with #NOSQLPS to
bypass loading the old SQLPS module.
• Always use least privilege: proxies should use service accounts with only the
required access.
• Maintain separation of duties: job owners and proxy creators don’t need to be
the same person.
Summary
SQL Server Agent provides a sophisticated security model built around:
• Role-based access control
• Subsystem isolation
• Credential-driven proxies
When properly configured, this model ensures that each job executes safely and only
with the permissions it truly needs. By combining sp_add_proxy,
sp_grant_proxy_to_subsystem, and careful role assignment, you can create secure,
scalable automation workflows.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
Job Activity Monitor
SQL Server Agent plays a crucial role in automating administrative tasks and running
scheduled jobs within SQL Server. The Agent Job Activity monitor provides a
comprehensive, read-only overview of all SQL Server Agent jobs and their current
status. This article outlines how to effectively use this tool and provides T-SQL scripts
for common job management tasks.
Understanding the Agent Job Activity Grid
The Agent Job Activity grid displays key information about each SQL Server Agent job.
While the grid itself is read-only, it serves as your primary interface for monitoring and
initiating further actions.
• Name: The unique identifier for the job.
• Enabled: Indicates whether the job is currently active (Yes) or inactive (No).
• Status*: The current operational state of the job (e.g., Running, Idle,
Suspended).
• Last Run Outcome: The final status of the job's most recent execution (e.g.,
Succeeded, Failed, Canceled).
• Last Run: The date and time (server's local time) when the job was last
executed.
• Next Run*: The date and time (server's local time) when the job is next
scheduled to run.
• Category: The user-defined category assigned to the job, aiding in organization.
• Runnable: Indicates if the job is capable of being executed (Yes) or not (No). A
job is not runnable if it lacks steps or a target server.
• Scheduled: Shows whether the job has an associated schedule (Yes) or not
(No).
Note on Permissions: The Status and Next Run columns are visible only to
members of the sysadmin fixed server role and the server administrators group.
Members of the SQLAgentOperatorRole cannot view these specific columns.
Interacting with the Agent Job Activity Monitor
While the grid is read-only for viewing, you can interact with it in several ways:
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
• Filtering: Click Filter to narrow down the displayed jobs based on various
criteria.
• Sorting: Click on any column header to sort the grid by that column's values.
• Modifying a Job: Double-click a job in the grid to open its Job Properties dialog
box, where you can make modifications.
• Context Menu Actions (Right-Click): Right-clicking a job brings up a context
menu with powerful options:
o Start Job at Step: Initiate the job from a specific step.
o Start Job: Run the job from its first step.
o Disable/Enable Job: Toggle the job's active status.
o Refresh Job: Update the status of a specific job.
o Delete Job: Remove the job permanently.
o View History: Access the job's execution history.
o View Properties: Open the Job Properties dialog box.
• Refreshing the Grid: Click Refresh to update all information in the grid to its
current state.
T-SQL Scripts for SQL Server Agent Job Management
You can perform many of the actions available in the Agent Job Activity monitor using T-
SQL, which is particularly useful for automation and scripting.
1. Viewing Job Activity
To get an overview of SQL Server Agent jobs and their status, you can query system
tables.
SELECT
[Link] AS JobName,
CASE [Link]
WHEN 1 THEN 'Yes'
ELSE 'No'
END AS Enabled,
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
s.current_execution_status AS Status, -- Requires sysadmin or server admin
CASE s.last_run_outcome
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 3 THEN 'Canceled'
WHEN 5 THEN 'Unknown' -- For jobs that haven't run yet or other statuses
ELSE 'Running/Other'
END AS LastRunOutcome,
[Link].agent_datetime(s.last_run_date, s.last_run_time) AS LastRun,
[Link].agent_datetime(s.next_run_date, s.next_run_time) AS NextRun, -- Requires
sysadmin or server admin
[Link] AS Category,
CASE j.has_schedule
WHEN 1 THEN 'Yes'
ELSE 'No'
END AS Scheduled,
CASE
WHEN j.has_no_steps = 1 THEN 'No (No Steps)'
WHEN j.target_server IS NULL THEN 'No (No Target Server)'
ELSE 'Yes'
END AS Runnable
FROM
[Link] AS j
LEFT JOIN
[Link] AS s ON j.job_id = s.job_id AND s.session_id = (SELECT TOP 1
session_id FROM [Link] ORDER BY agent_start_date DESC)
LEFT JOIN
[Link] AS c ON j.category_id = c.category_id
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
ORDER BY
JobName;
2. Starting a Job
You can start a SQL Server Agent job using sp_start_job.
-- Start a specific job by name
EXEC [Link].sp_start_job N'MyMaintenanceJob';
-- To start a job from a specific step, you would first need to know the step name.
-- This example assumes you want to start 'MyMaintenanceJob' from the step named
'Step2'.
-- (Note: sp_start_job does not directly support starting from a step by step name.
-- You would typically manage this logic within the job steps themselves or by
-- enabling/disabling steps, or by creating a separate job for specific steps.)
3. Enabling or Disabling a Job
Use sp_update_job to change a job's enabled status.
-- Disable a job
EXEC [Link].sp_update_job
@job_name = N'MyMaintenanceJob',
@enabled = 0;
-- Enable a job
EXEC [Link].sp_update_job
@job_name = N'MyMaintenanceJob',
@enabled = 1;
4. Deleting a Job
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
To remove a job, use sp_delete_job.
-- Delete a job
EXEC [Link].sp_delete_job
@job_name = N'MyOldJob';
5. Viewing Job History
The job history provides detailed information about past job executions.
SELECT
[Link] AS JobName,
h.step_name AS StepName,
h.sql_message_id,
h.sql_severity,
[Link] AS LogMessage,
CASE h.run_status
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled'
WHEN 4 THEN 'In Progress'
END AS RunStatus,
[Link].agent_datetime(h.run_date, h.run_time) AS RunDateTime,
h.run_duration AS RunDurationSeconds -- Duration in HHMMSS format needs
conversion for true seconds
FROM
[Link] AS h
INNER JOIN
[Link] AS j ON h.job_id = j.job_id
WHERE
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
[Link] = N'MyMaintenanceJob' -- Replace with your job name
ORDER BY
RunDateTime DESC;
SQL Server Agent is a powerful component for automating administrative tasks and
scheduling jobs. However, its capabilities also mean that proper security configuration
is paramount to protect your SQL Server environment. This article delves into the best
practices for implementing SQL Server Agent security, focusing on the principle of least
privilege, and provides T-SQL scripts for common security management tasks.
The Importance of SQL Server Agent Security
SQL Server Agent jobs often perform critical operations, such as backups, data
transfers, and maintenance routines. If an attacker gains control of SQL Server Agent or
its jobs, they could potentially compromise your entire SQL Server instance and the
data it contains.
The core of SQL Server Agent security revolves around proxies and fixed database
roles. Proxies allow you to run job steps under specific security contexts with only the
necessary permissions, while fixed database roles control which users can create, view,
or manage jobs.
Granting Access to SQL Server Agent
To interact with SQL Server Agent, users must be members of specific fixed database
roles within the msdb database. By default, no users are members of these roles.
• SQLAgentUserRole: Provides basic permissions to view and execute jobs
owned by the user.
• SQLAgentReaderRole: Allows users to read SQL Server Agent job properties
and history.
• SQLAgentOperatorRole: Grants more extensive control, enabling users to view,
start, stop, and enable/disable jobs they own, and also view the history of all
jobs.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
Users who are members of the sysadmin fixed server role automatically have full
access to SQL Server Agent and do not need to be explicitly added to these msdb roles.
If a user is not a member of any of these roles or sysadmin, the SQL Server Agent node
will not be visible in SQL Server Management Studio (SSMS).
T-SQL for Granting Access
You can grant users membership in these roles using sp_addrolemember:
-- Granting a login access to SQLAgentUserRole
USE msdb;
GO
EXEC sp_addrolemember N'SQLAgentUserRole', N'YourLoginName';
GO
-- Granting a login access to SQLAgentReaderRole
USE msdb;
GO
EXEC sp_addrolemember N'SQLAgentReaderRole', N'YourLoginName';
GO
-- Granting a login access to SQLAgentOperatorRole
USE msdb;
GO
EXEC sp_addrolemember N'SQLAgentOperatorRole', N'YourLoginName';
GO
Note: Replace YourLoginName with the actual SQL Server login or Windows login you
want to grant permissions to.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
Implementing Job Step Security with Proxies
A key security feature of SQL Server Agent is the ability to run job steps in a security
context separate from the SQL Server Agent service account. This is achieved through
SQL Server Agent proxies.
A proxy is a stored credential that maps to a specific security principal (e.g., a Windows
user account or a SQL Server credential) that has the necessary permissions to perform
the tasks within a job step. By assigning a proxy to a job step, you ensure that the step
only executes with the permissions explicitly granted to that proxy, adhering to the
principle of least privilege.
• Dedicated Proxy Accounts: Create dedicated Windows user accounts or SQL
Server credentials specifically for proxies. These accounts should have only the
minimum permissions required for the job steps they will execute.
• Reusing Proxies: A single proxy can be assigned to multiple job steps that
require the same permissions, simplifying management.
• sysadmin Role and Service Account: Members of the sysadmin fixed server
role can create, modify, and delete proxy accounts. They can also create job
steps that run directly as the SQL Server Agent service account (the account
used to start SQL Server Agent), which should generally be avoided for security
reasons unless absolutely necessary.
T-SQL for Proxy Management
Creating a Credential (if using SQL Server Login or Windows Account)
If your proxy will use a SQL Server login or a Windows user not already a SQL Server
login, you might need a credential first.
-- Creating a SQL Server credential for a Windows user
CREATE CREDENTIAL [MyProxyCredential]
WITH IDENTITY = N'MYDOMAIN\MyProxyUser',
SECRET = N'MyStrongPassword';
GO
-- Creating a SQL Server credential for a SQL Server login (less common for proxies,
but possible)
-- CREATE CREDENTIAL [MySqlLoginProxyCredential]
-- WITH IDENTITY = N'MySqlLogin',
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
-- SECRET = N'MySqlLoginPassword';
-- GO
Creating a Proxy Account
-- Creating a new SQL Server Agent proxy
EXEC [Link].sp_add_proxy
@proxy_name = N'MyAgentProxy',
@credential_name = N'MyProxyCredential', -- The credential created above
@description = N'Proxy for running specific maintenance tasks.';
GO
Assigning a Proxy to a Subsystem
Before a proxy can be used, it must be granted access to the subsystems it will operate
within (e.g., ActiveScripting, CmdExec, SSIS, T-SQL).
-- Granting a proxy access to the CmdExec subsystem
EXEC [Link].sp_grant_proxy_to_subsystem
@proxy_name = N'MyAgentProxy',
@subsystem_id = 3; -- 3 for CmdExec subsystem. Other IDs: 2=ActiveScripting,
5=SSIS, 7=T-SQL, etc.
GO
Modifying a Job Step to Use a Proxy
When creating or altering a job step, you specify the @proxy_name.
-- Example: Creating a job step that uses a proxy
EXEC [Link].sp_add_jobstep
@job_name = N'MyMaintenanceJob',
@step_name = N'RunCleanupScript',
@subsystem = N'CmdExec',
@command = N'C:\Scripts\[Link]',
@proxy_name = N'MyAgentProxy';
GO
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
-- Example: Modifying an existing job step to use a proxy
EXEC [Link].sp_update_jobstep
@job_name = N'MyMaintenanceJob',
@step_name = N'RunCleanupScript',
@proxy_name = N'MyAgentProxy';
GO
Using Proxies for Secure Job Steps
Proxies allow job steps (except T-SQL) to run under specific credentials, limiting access
and improving security.
Guidelines
• Use dedicated user accounts for proxies
• ✂️ Minimal permissions only for proxy accounts
• Avoid NT Admin or Windows Administrator accounts for services or proxies
• Create credentials first, then associate them with proxies
• Assign proxies to specific subsystems (e.g., PowerShell, SSIS)
🔧 Create a Proxy Example
-- Create Credential
CREATE CREDENTIAL ArchiveCred
WITH IDENTITY = 'DOMAIN\ServiceAccount', SECRET = 'StrongPassword123!';
-- Create Proxy
USE msdb;
EXEC sp_add_proxy
@proxy_name = 'FileArchiveProxy',
@credential_name = 'ArchiveCred',
@enabled = 1;
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
-- Grant access to PowerShell subsystem
EXEC sp_grant_proxy_to_subsystem
@proxy_name = 'FileArchiveProxy',
@subsystem_id = 12; -- PowerShell
-- Grant a login access to the proxy
EXEC sp_grant_login_to_proxy
@proxy_name = 'FileArchiveProxy',
@login_name = 'YourLogin';
General Security Guidelines for SQL Server Agent
Adhering to these guidelines strengthens the overall security posture of your SQL Server
Agent implementation:
• Dedicated Proxy User Accounts: Always create specific Windows user
accounts or SQL Server credentials exclusively for proxy use. Avoid reusing
existing accounts that might have broader permissions.
• Least Privilege Principle: Grant only the bare minimum permissions necessary
to proxy user accounts. If a proxy only needs to read a file, don't give it write
access.
• SQL Server Agent Service Account:
o Do not run the SQL Server Agent service under a Microsoft Windows
account that is a member of the Windows Administrators group.
o Do not specify the NT Admin account as a service account or proxy
account. This provides too much privilege and creates a significant
security risk.
• Proxy Security and Credentials: Proxies are only as secure as the underlying
SQL Server credential store. Ensure that your credentials are well-protected and
follow strong password policies.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
• NT Event Log: Be aware that if a user has write operations that can log to the NT
Event log, they could potentially raise alerts via SQL Server Agent, which might
be exploited for malicious purposes.
• Inter-Service Access: SQL Server and SQL Server Agent share a single process
space, and SQL Server Agent acts as a sysadmin on the SQL Server service. This
close relationship underscores the importance of securing SQL Server Agent
itself.
• Master/Target Servers (MSX/TSX): When a target server (TSX) enlists with a
master server (MSX), the MSX sysadmins gain total control over the TSX instance
of SQL Server. Secure your MSX environment rigorously.
• ACE (Application Compatibility Engine): ACE is an extension and needs to be
invoked by a host process like Chainer [Link] or
[Link]. ACE relies on specific configuration DLLs
([Link],
[Link],
[Link],
[Link]). Ensure the integrity and
security of these components.
SQL Server Agent and Linked Servers (Especially for Azure SQL Managed Instance)
When a SQL Server Agent job executes a T-SQL query on a remote server through a
linked server, a crucial security consideration is the mapping of logins. This is
particularly relevant in environments like Azure SQL Managed Instance, where
Windows logins are not directly supported for linked server impersonation without
explicit mapping.
To facilitate secure communication over linked servers for SQL Agent jobs, you need to
map a local login to a login on the remote server that possesses the necessary
permissions. The job then executes the T-SQL query in the context of this mapped
remote login.
Login Mapping Scenarios:
• User that is not sysadmin: If the SQL Agent job owner is a non-sysadmin user,
you must map that specific local user who owns the SQL Agent job to a
corresponding remote login.
• sysadmin: If the SQL Agent job owner is a sysadmin, you can map all local users
to the remote login by setting the @locallogin parameter to NULL.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
T-SQL for Linked Server Login Mapping
Use sp_addlinkedsrvlogin to create these mappings:
-- Scenario 1: Mapping a specific non-sysadmin local user to a remote login
-- This maps 'YourLocalUser' on the local server to 'RemoteLoginForJob' on
'YourLinkedServer'.
EXEC sp_addlinkedsrvlogin
@rmtsrvname = N'YourLinkedServer', -- Name of your linked server
@useself = N'FALSE',
@locallogin = N'YourLocalUser', -- The local SQL Server login that owns the job
@rmtuser = N'RemoteLoginForJob', -- The login on the remote server
@rmtpassword = N'RemoteLoginPassword';
GO
-- Scenario 2: Mapping all local users (for sysadmin job owners) to a remote login
-- This maps all local logins to 'RemoteLoginForSysadmin' on 'YourLinkedServer'.
-- Useful when a sysadmin owns the job.
EXEC sp_addlinkedsrvlogin
@rmtsrvname = N'YourLinkedServer', -- Name of your linked server
@useself = N'FALSE',
@locallogin = NULL, -- NULL indicates all local logins
@rmtuser = N'RemoteLoginForSysadmin', -- The login on the remote server
@rmtpassword = N'RemoteLoginPassword';
GO
Important: Failure to correctly map users for linked server operations in Azure SQL
Managed Instance can lead to errors such as:
• "Windows logins are not supported in this version of SQL Server"
• "Linked servers cannot be used under impersonation without a mapping for the
impersonated login"
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
Linked Servers and Job Execution in Azure SQL Managed Instance
When executing T-SQL on a remote SQL Server through a linked server, you must map
local logins to remote logins using sp_addlinkedsrvlogin.
Mapping Strategy Based on Job Owner
Job Owner Mapping Required
Non-sysadmin user Map local user to a remote login
Sysadmin Map all users to remote login using @locallogin = NULL
Example Mapping for Linked Server Jobs
-- Map specific user
EXEC sp_addlinkedsrvlogin
@rmtsrvname = N'MyLinkedServer',
@useself = N'False',
@locallogin = N'NonSysAdminUser',
@rmtuser = N'remote_login',
@rmtpassword = N'remote_password';
-- Map all users (for sysadmin)
EXEC sp_addlinkedsrvlogin
@rmtsrvname = N'MyLinkedServer',
@useself = N'False',
@locallogin = NULL,
@rmtuser = N'remote_login',
@rmtpassword = N'remote_password';
Common Errors
• Windows logins are not supported in this version of SQL Server
• Linked servers cannot be used under impersonation without a mapping for the
impersonated login
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
These usually indicate login mapping issues in Azure SQL Managed Instance.
Managing SQL Server Agent Components
Alerts, User-Defined Events, and Operators
SQL Server Agent provides robust capabilities for automating tasks and responding to
events within your SQL Server environment. Beyond just scheduling jobs, it allows you
to set up alerts for critical events, define user-defined events for custom monitoring,
and configure operators to receive notifications. This article details these essential
components, along with the T-SQL scripts to manage them.
Alerts
Alerts are automatic responses to specific events or performance conditions within
SQL Server. They allow SQL Server Agent to monitor the system and notify
administrators or execute jobs when predefined conditions are met. This is crucial for
proactive monitoring and ensuring system health and stability.
Key Aspects of Alerts:
• Event-Driven: Alerts can be triggered by SQL Server error messages (e.g.,
severity 19 or higher errors), specific message IDs, or WMI (Windows
Management Instrumentation) events.
• Performance Conditions: They can also respond to performance counter
thresholds, such as high CPU usage or low free disk space.
• Actions: When an alert fires, SQL Server Agent can:
o Notify one or more operators via email, pager, or net send.
o Execute a job.
o Log an event to the Windows application event log.
T-SQL for Managing Alerts
Creating an Alert
The sp_add_alert stored procedure is used to create a new alert.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
USE msdb;
GO
EXEC [Link].sp_add_alert
@name = N'High Severity Error Alert', -- Name of the alert
@message_id = 0, -- 0 for any message ID
@severity = 19, -- Trigger for severity 19 (fatal user errors) or higher
@enabled = 1, -- 1 to enable the alert immediately
@delay_between_responses = 60, -- Delay in seconds between responses (to
prevent flooding)
@include_event_description_in = 1, -- Include event description in notification
@category_name = N'Performance', -- Category for the alert
@job_name = N'Log High Severity Error', -- Optional: Job to execute when alert fires
@notification_message = N'A high severity error has occurred. Please investigate.', --
Custom message
@performance_condition = N'SQLServer:Memory Manager|Total Server Memory
(KB)>102400'; -- Example: Performance condition
-- (Note: message_id and severity cannot be combined with
performance_condition directly in one alert.)
GO
-- Example for a specific message ID (e.g., error 18456 for failed logins)
EXEC [Link].sp_add_alert
@name = N'Failed Login Attempts',
@message_id = 18456,
@severity = 0,
@enabled = 1,
@delay_between_responses = 300,
@include_event_description_in = 1,
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
@notification_message = N'Multiple failed login attempts detected. Check security
logs.';
GO
Modifying an Alert
Use sp_update_alert to change existing alert properties.
USE msdb;
GO
EXEC [Link].sp_update_alert
@name = N'High Severity Error Alert',
@new_name = N'Critical Error Alert', -- Renaming the alert
@enabled = 0; -- Disabling the alert
GO
Deleting an Alert
Use sp_delete_alert to remove an alert.
USE msdb;
GO
EXEC [Link].sp_delete_alert
@name = N'Critical Error Alert';
GO
User-Defined Events
While SQL Server has many predefined events, you might need to trigger actions based
on custom conditions specific to your applications or business logic. User-defined
events allow you to extend SQL Server's monitoring capabilities beyond the standard
set.
You can create user-defined events by raising custom errors or messages within your T-
SQL code. These messages can then be captured by SQL Server Agent alerts that are
configured to respond to specific message IDs or severities.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
T-SQL for Creating a User-Defined Event
To create a user-defined event, you typically use the RAISERROR statement within a
stored procedure, trigger, or batch script.
USE YourDatabase; -- Replace with your database name
GO
-- Example: Stored procedure to log a custom event
CREATE PROCEDURE [Link]
@EventMessage NVARCHAR(2000)
AS
BEGIN
-- Using a custom message ID (e.g., 50001) with a specific severity
RAISERROR (N'Application Event: %s', 10, 1, @EventMessage) WITH LOG;
-- The WITH LOG option ensures the message is written to the SQL Server error log
-- and the Windows application event log, making it detectable by SQL Server Agent.
END;
GO
-- Execute the procedure to raise the user-defined event
EXEC [Link] N'Inventory level for product XYZ is critically
low.';
GO
-- Now, create an alert in msdb to capture this event (message_id 50001)
USE msdb;
GO
EXEC [Link].sp_add_alert
@name = N'Inventory Low Alert',
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
@message_id = 50001, -- The custom message ID from RAISERROR
@severity = 0,
@enabled = 1,
@delay_between_responses = 600, -- 10-minute delay
@include_event_description_in = 1,
@notification_message = N'Custom application alert: Inventory low event.';
GO
Note: For RAISERROR messages to be picked up by SQL Server Agent alerts, they must
have a severity level of 10 or higher and be logged to the SQL Server error log using the
WITH LOG option.
Operators
Operators are aliases for administrators or other personnel whom SQL Server Agent
can notify when jobs complete, fail, or when alerts are triggered. Operators represent
individuals or groups who should receive notifications.
Key Aspects of Operators:
• Notification Methods: Operators can receive notifications via:
o Email: Using Database Mail (requires configuration).
o Pager: Using an email-to-pager gateway.
o Net Send: (Deprecated and generally not recommended due to security
and functionality limitations).
• Aliases: Operators are essentially aliases for actual contact information, making
it easier to manage notifications.
• Multiple Operators: You can define multiple operators and assign them to
receive notifications for different alerts or job outcomes.
T-SQL for Managing Operators
Creating an Operator
Use the sp_add_operator stored procedure to define a new operator.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
USE msdb;
GO
EXEC [Link].sp_add_operator
@name = N'DBA Team Lead', -- Name of the operator
@enabled = 1, -- Enable the operator
@email_address = N'[Link]@[Link]', -- Email address for notifications
@pager_address = N'[Link]@[Link]', -- Pager address (if applicable)
@weekday_pager_start_time = 080000, -- 8:00 AM
@weekday_pager_end_time = 170000, -- 5:00 PM
@saturday_pager_start_time = 090000, -- 9:00 AM
@saturday_pager_end_time = 120000, -- 12:00 PM
@sunday_pager_start_time = 090000, -- 9:00 AM
@sunday_pager_end_time = 120000; -- 12:00 PM
GO
Note: Before using email or pager notifications, ensure Database Mail is configured
and enabled on your SQL Server instance.
Modifying an Operator
Use sp_update_operator to change an operator's properties.
USE msdb;
GO
EXEC [Link].sp_update_operator
@name = N'DBA Team Lead',
@new_name = N'Primary DBA', -- Renaming the operator
@email_address = N'[Link]@[Link]'; -- Updating email address
GO
Deleting an Operator
Use sp_delete_operator to remove an operator.
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
USE msdb;
GO
EXEC [Link].sp_delete_operator
@name = N'Primary DBA';
GO
Notifying Operators from an Alert or Job
Once operators are created, you can associate them with alerts or jobs.
-- Associating an operator with an alert (when creating or updating the alert)
USE msdb;
GO
EXEC [Link].sp_update_alert
@name = N'Failed Login Attempts',
@job_id = NULL, -- Clear any associated job if not needed
@include_event_description_in = 1,
@category_name = N'Security',
@notification_message = N'Multiple failed login attempts detected. Check security
logs.',
@operators_to_email = N'DBA Team Lead'; -- Operator to email
GO
-- Notifying an operator from a job step (on job completion/failure)
-- This is typically set in the Job Properties -> Notifications tab in SSMS,
-- or when creating/updating the job using sp_add_job/sp_update_job.
USE msdb;
GO
EXEC [Link].sp_update_job
@job_name = N'MyMaintenanceJob',
@notify_level_email = 2, -- 2 = notify on job failure
@notify_email_operator_name = N'DBA Team Lead'; -- Operator to notify via email
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
Create User-Defined Events
Use Case
Custom alerts may be needed when your business logic detects a critical condition that isn't
covered by SQL Server error codes.
T-SQL: Raise a User-Defined Event
RAISERROR(50001, 16, 1) WITH LOG;
• The error number 50001 must exist in [Link].
• Severity 16 triggers standard alerting mechanisms.
• WITH LOG ensures SQL Server Agent can detect it.
Add a Message to [Link]
EXEC sp_addmessage
@msgnum = 50001,
@severity = 16,
@msgtext = N'Custom alert: Row count threshold breached.',
@with_log = 'TRUE';
Create an alert for this error:
EXEC [Link].sp_add_alert
@name = N'CustomRowCountAlert',
@message_id = 50001,
@enabled = 1;
Real-Life Monitoring Scenario
Imagine you want to monitor a table for excessive growth. Once it crosses 10 million
rows, you raise an alert.
IF (SELECT COUNT(*) FROM [Link]) > 10000000
BEGIN
RAISERROR(50001, 16, 1) WITH LOG;
END
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
This triggers the CustomRowCountAlert, which notifies the DBAdminTeam operator and
optionally starts a cleanup job.
Change step of SQL Server Agent Master Jobs
Using SQL Server Management Studio
To make changes to the steps of a SQL Server Agent master job
1. In Object Explorer, click the plus sign to expand the server that contains the job
where you want to modify steps.
2. Click the plus sign to expand SQL Server Agent.
3. Click the plus sign to expand the Jobs folder.
4. Right-click the job where you want to modify steps and select Properties.
5. In the Job Properties -job_name dialog box, under Select a page, select Steps.
6. Click Edit to open the Job Step Properties -job_step_name dialog box.
7. When finished, click OK.
8. In the Job Properties -job_name dialog box, click OK.
Using Transact-SQL
To make changes to the steps of a SQL Server Agent master job
1. In Object Explorer, connect to an instance of Database Engine.
2. On the Standard bar, click New Query.
3. Copy and paste the following example into the query window and click Execute.
-- changes the number of retry attempts for the first step
-- of the Weekly Sales Data Backup job.
-- After running this example, the number of retry attempts is 10
USE msdb ;
GO
EXEC dbo.sp_update_jobstep
@job_name = N'Weekly Sales Data Backup',
@step_id = 1,
SECURITY LABEL: OFFICIAL
MS SQL DATABASE ADMINISTRATOR 30 DAYS COURSE
BY: Mukesh Chaurasia
@retry_attempts = 10 ;
GO
Change Scheduled Details for Master Job
Using SQL Server Management Studio
To change the scheduling details for a job definition
1. In Object Explorer, click the plus sign to expand the server that contains the job
whose schedule you want to edit.
2. Click the plus sign to expand SQL Server Agent.
3. Click the plus sign to expand the Jobs folder.
4. Right-click the job whose schedule you want to edit and select Properties.
5. In the Job Properties -job_name dialog box, under Select a page,
select Schedules. For more information on the available options on this page,
6. When finished, click OK.
Using Transact-SQL
To change the scheduling details for a job definition
1. In Object Explorer, connect to an instance of Database Engine.
2. On the Standard bar, click New Query.
3. Copy and paste the following example into the query window and click Execute.
-- changes the enabled status of the NightlyJobs schedule to 0
-- and sets the owner to terrid.
USE msdb ;
GO
EXEC dbo.sp_update_schedule
@name = 'NightlyJobs',
@enabled = 0,
@owner_login_name = 'terrid' ;
GO
SECURITY LABEL: OFFICIAL