SQL Server Agent Jobs
SQL Server Agent Jobs are automated tasks that can be scheduled to run at specified intervals, such as daily, weekly, or monthly. They can be used to perform a variety of operations, such as database backups, data transfers, and maintenance tasks.
Via GUI -
To create an SQL Server Agent Job using the GUI, follow these steps:
- Open SQL Server Management Studio (SSMS) and connect to the SQL Server instance.
- Expand the SQL Server Agent node and right-click on Jobs.
- Select New Job from the context menu to open the New Job window.
- In the General tab, enter a name and description for the job.
- In the Steps tab, add one or more steps to the job. Each step defines a specific task to be performed.
- In the Schedules tab, define the schedule for the job. You can choose from a variety of options, such as daily, weekly, or monthly.
- In the Notifications tab, configure the job to send an email notification when it completes or fails.
Here's an example of an SQL Server Agent Job that performs a database backup:
- Open SSMS and connect to the SQL Server instance.
- Expand the SQL Server Agent node and right-click on Jobs.
- Select New Job from the context menu to open the New Job window.
- Enter a name and description for the job, such as "Database Backup".
- In the Steps tab, click New to add a new step.
- Enter a name for the step, such as "Backup Database".
- In the Type drop-down list, select Transact-SQL script.
- In the Command box, enter the backup command, such as "BACKUP DATABASE [AdventureWorks] TO DISK='D:\Backup\AdventureWorks.bak'".
- Click OK to save the step.
- In the Schedules tab, click New to create a new schedule.
- Enter a name for the schedule, such as "Daily Backup".
- Choose the frequency, such as daily, and set the time for the backup.
- Click OK to save the schedule.
In the Notifications tab, configure the job to send an email notification when it completes or fails.
Click OK to save the job.
Once the job is created, it will run according to the schedule you defined. You can view the status of the job in the SQL Server Agent node in SSMS, and you can also view the job history to see when it ran and whether it succeeded or failed.
Via T-SQL -
To create an SQL Server Agent Job using T-SQL, follow these steps:
- Open SQL Server Management Studio (SSMS) and connect to the SQL Server instance.
- Open a new query window.
- Type the following T-SQL script to create a new job:
USE msdb;
GO
EXEC dbo.sp_add_job
@job_name = N'Database Backup',
@enabled = 1,
@description = N'Backup the AdventureWorks database';
GO
This creates a new job called "Database Backup" with a description of "Backup the AdventureWorks database". The job is also enabled by default.
- Type the following T-SQL script to add a step to the job:
- Type the following T-SQL script to schedule the job to run:
- Finally, type the following T-SQL script to start the job:
Comments
Post a Comment