自己看了mssql 帮助文档写,方便以后用啊!
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Pro_AddTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Pro_AddTask]
GO
create proc Pro_AddTask
@taskname varchar(100), --task name
@sql varchar(8000), --slq command
@dbname sysname='', -- default the current db
@freqtype varchar(6)='day', --the frequence of time :month ,week ,day
@freqsubtype varchar(6)='no' ,--no, hour ,minute
@fqinterval int=1, --the execute times
@fqsubinterval int=1, --the sub interval
@time int=000000 -- execute on some time format(hhmmss)
as
/*--creat task
--author:sky 2008.02.27
discription:
when @freqtype='week' when @fqinterval=
1 = 星期日
2 = 星期一
4 = 星期二
8 = 星期三
16 = 星期四
32 = 星期五
64 = 星期六
*/
/*--eg.
--每月执行的作业
exec Pro_AddTask @taskname='mm',@sql='seleCT * from syscolumns',@freqtype='month'
--每周执行的作业
exec Pro_AddTask @taskname='ww',@sql='select * from syscolumns',@freqtype='week'
--每日00000执行的作业
exec Pro_AddTask @taskname='ab',@sql='select * from syscolumns'
--每日12:00:00作业
exec Pro_AddTask @taskname='d12',@sql='select * from syscolumns',@time=12000
--每周六12:00:00作业
exec Pro_AddTask @taskname='w12',@sql='select * from syscolumns',@freqtype='week',@fqinterval=64,@time=12000
--每月20号12:00:00作业
exec Pro_AddTask @taskname='m20',@sql='select * from syscolumns',@freqtype='month',@fqinterval=20,@time=12000
--*/
if isnull(@dbname,'')='' set @dbname=db_name()
--create task
exec msdb..sp_add_job @job_name=@taskname
--create task step
exec msdb..sp_add_jobstep @job_name=@taskname,
@step_name = 'data process',
@subsystem = 'TSQL',
@database_name=@dbname,
@command = @sql,
@retry_attempts = 5,
@retry_interval = 5
--create schedule
declare @ftype int,@fstype int,@ffactor int
select @ftype=case @freqtype
when 'day' then 4
when 'week' then 8
when 'month' then 16
end
,@fstype=case @freqsubtype
when 'no' then 1
when 'hour' then 4
when 'minutue' then 8
else 0
end
set @ffactor=case @freqtype when 'day' then 0 else 1 end
EXEC msdb..sp_add_jobschedule @job_name=@taskname,
@name = 'schedule',
@freq_type=@ftype , ---4 每天,8 每周,16 每月
@freq_interval=@fqinterval, --作业执行的天数
@freq_subday_type=@fstype, --是否重复执行,0x1 在指定的时间, 0x4 分钟, 0x8 小时
@freq_subday_interval=@fqsubinterval, --重复周期
@freq_recurrence_factor=@ffactor, --重复执行,则设置为1,否则设置为0
@active_start_time=@time --下午00:00:00分执行
-- add the goal server
EXEC msdb.dbo.sp_add_jobserver
@job_name = @taskname ,
@server_name = N'(local)'