Dela via


sp_attach_schedule (Transact-SQL)

Sets a schedule for a job.

Topic link iconTransact-SQL Syntax Conventions

Syntax

sp_attach_schedule
     { [ @job_id = ] job_id | [ @job_name = ] 'job_name' } , 
     { [ @schedule_id = ] schedule_id 
     | [ @schedule_name = ] 'schedule_name' }

Arguments

  • [ @job_id= ] job_id
    The job identification number of the job to which the schedule is added. job_idis uniqueidentifier, with a default of NULL.

  • [ @job_name = ] 'job_name'
    The name of the job to which the schedule is added. job_nameis sysname, with a default of NULL.

    Note

    Either job_id or job_name must be specified, but both cannot be specified.

  • [ @schedule_id = ] schedule_id
    The schedule identification number of the schedule to set for the job. schedule_idis int, with a default of NULL.

  • [ @schedule_name = ] 'schedule_name'
    The name of the schedule to set for the job. schedule_nameis sysname, with a default of NULL.

    Note

    Either schedule_id or schedule_name must be specified, but both cannot be specified.

Remarks

The schedule and the job must have the same owner.

A schedule can be set for more than one job. A job can be run on more than one schedule.

This stored procedure must be run from the msdb database.

Permissions

By default, members of the sysadmin fixed server role can execute this stored procedure. Other users must be granted one of the following SQL Server Agent fixed database roles in the msdb database:

  • SQLAgentUserRole

  • SQLAgentReaderRole

  • SQLAgentOperatorRole

For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles.

SQL Server checks if the user owns both the job and the schedule.

Examples

The following example creates a schedule named NightlyJobs. Jobs that use this schedule execute every day when the time on the server is 01:00. The example attaches the schedule to the job BackupDatabase and the job RunReports.

Note

This example assumes that the job BackupDatabase and the job RunReports already exist.

USE msdb ;
GO

EXEC sp_add_schedule
    @schedule_name = N'NightlyJobs' ,
    @freq_type = 4,
    @freq_interval = 1,
    @active_start_time = 010000 ;
GO


EXEC sp_attach_schedule
   @job_name = N'BackupDatabase',
   @schedule_name = N'NightlyJobs' ;
GO

EXEC sp_attach_schedule
   @job_name = N'RunReports',
   @schedule_name = N'NightlyJobs' ;
GO