通过编程添加自动化作业
有时候看一些程序,他们在安装的时候,会在SQL Server里面创建一些特定的作业,以便为其执行自动化任务。我就在想,这是怎么做到的呢?我们以前一般都是通过SSMS的界面来完成这个事情的
1. 通过T-SQL的方式,基本上几个步骤:add_job,add_job_step,add_job_schedule,add_job_server
USE [msdb] --所有的作业信息都是存储在msdb数据库的
GO
/****** Object: Job [syspolicy_purge_history] Script Date: 04/29/2009 07:41:53 ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object: JobCategory [[Uncategorized (Local)]]] Script Date: 04/29/2009 07:41:53 ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
END
DECLARE @jobId BINARY(16)
EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'syspolicy_purge_history',
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=0,
@description=N'无描述。',
@category_name=N'[Uncategorized (Local)]',
@owner_login_name=N'sa', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object: Step [Verify that automation is enabled.] Script Date: 04/29/2009 07:41:54 ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Verify that automation is enabled.',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=3,
@on_success_step_id=0,
@on_fail_action=1,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N'TSQL',
@command=N'IF (msdb.dbo.fn_syspolicy_is_automation_enabled() != 1)
BEGIN
RAISERROR(34022, 16, 1)
END',
@database_name=N'master',
@flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object: Step [Purge history.] Script Date: 04/29/2009 07:41:54 ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Purge history.',
@step_id=2,
@cmdexec_success_code=0,
@on_success_action=3,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N'TSQL',
@command=N'EXEC msdb.dbo.sp_syspolicy_purge_history',
@database_name=N'master',
@flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object: Step [Erase Phantom System Health Records.] Script Date: 04/29/2009 07:41:54 ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Erase Phantom System Health Records.',
@step_id=3,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N'PowerShell',
@command=N'(Get-Item SQLSERVER:\SQLPolicy\THINKER\SQL2008).EraseSystemHealthPhantomRecords()',
@database_name=N'master',
@flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'syspolicy_purge_history_schedule',
@enabled=1,
@freq_type=4,
@freq_interval=1,
@freq_subday_type=1,
@freq_subday_interval=0,
@freq_relative_interval=0,
@freq_recurrence_factor=0,
@active_start_date=20080101,
@active_end_date=99991231,
@active_start_time=20000,
@active_end_time=235959
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:
GO
2. 通过SMO的方式
这里有一个完整的介绍
http://msdn.microsoft.com/zh-cn/library/ms162162.aspx
//Connect to the local, default instance of SQL Server. { Server srv = default(Server); srv = new Server(); //Define an Operator object variable by supplying the Agent (parent JobServer object) and the name in the constructor. Operator op = default(Operator); op = new Operator(srv.JobServer, "Test_Operator"); //Set the Net send address. op.NetSendAddress = "Network1_PC"; //Create the operator on the instance of SQL Server Agent. op.Create(); //Define a Job object variable by supplying the Agent and the name arguments in the constructor and setting properties. Job jb = default(Job); jb = new Job(srv.JobServer, "Test_Job"); //Specify which operator to inform and the completion action. jb.OperatorToNetSend = "Test_Operator"; jb.NetSendLevel = CompletionAction.Always; //Create the job on the instance of SQL Server Agent. jb.Create(); //Define a JobStep object variable by supplying the parent job and name arguments in the constructor. JobStep jbstp = default(JobStep); jbstp = new JobStep(jb, "Test_Job_Step"); jbstp.Command = "Test_StoredProc"; jbstp.OnSuccessAction = StepCompletionAction.QuitWithSuccess; jbstp.OnFailAction = StepCompletionAction.QuitWithFailure; //Create the job step on the instance of SQL Agent. jbstp.Create(); //Define a JobSchedule object variable by supplying the parent job and name arguments in the constructor. JobSchedule jbsch = default(JobSchedule); jbsch = new JobSchedule(jb, "Test_Job_Schedule"); //Set properties to define the schedule frequency, and duration. jbsch.FrequencyTypes = FrequencyTypes.Daily; jbsch.FrequencySubDayTypes = FrequencySubDayTypes.Minute; jbsch.FrequencySubDayInterval = 30; TimeSpan ts1 = default(TimeSpan); ts1 = new TimeSpan(9, 0, 0); jbsch.ActiveStartTimeOfDay = ts1; TimeSpan ts2 = default(TimeSpan); ts2 = new TimeSpan(17, 0, 0); jbsch.ActiveEndTimeOfDay = ts2; jbsch.FrequencyInterval = 1; System.DateTime d = default(System.DateTime); d = new System.DateTime(2003, 1, 1); jbsch.ActiveStartDate = d; //Create the job schedule on the instance of SQL Agent. jbsch.Create(); }