if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_createjob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_createjob]
GO
create proc p_createjob
@jobname varchar(100),             --作業排程名稱
@sql varchar(8000),                --要執行的命令
@serverName sysname='',            --job server名
@dbname sysname='',                --默認爲當前的資料庫名
@freqtype varchar(6)='day',        --時間周期,month 月,week 周,day 日
@fsinterval int=1,                 --相對於每日的重復次數
@time int=170000                   --開始執行時間,對於重復執行的作業排程,將從0點到23:59分
as
if isnull(@dbname,'')='' set @dbname=db_name()
--建立作業排程
exec msdb..sp_add_job @job_name=@jobname
--建立作業排程步驟
exec msdb..sp_add_jobstep @job_name=@jobname,
        @step_name = '資料處理',
        @subsystem = 'TSQL',
        @database_name=@dbname,
        @command = @sql,
        @retry_attempts = 5, --重試次數
        @retry_interval = 5  --重試間隔
--建立調度
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 @fsinterval when 1 then 0 else 8 end
if @fsinterval<>1 set @time=0
set @ffactor=case @freqtype when 'day' then 0 else 1 end
EXEC msdb..sp_add_jobschedule @job_name=@jobname, 
        @name = '時間安排',
        @freq_type=@ftype ,                        --每天,8 每周,16 每月
        @freq_interval=1,                          --重復執行次數
        @freq_subday_type=@fstype,                 --是否重復執行
        @freq_subday_interval=@fsinterval,         --重復周期
        @freq_recurrence_factor=@ffactor,
        @active_start_time=@time                   --下午17:00:00分執行
if @servername=''
set @servername=@@servername
EXEC msdb..sp_add_jobserver @job_name = @jobname, 
     @server_name = @servername
go 
--調用
--每月執行的作業排程
exec p_createjob @jobname='mm'
                 ,@sql='insert A select ''AAA'''
                 ,@servername='FUDAN-OXI9Y1PYT'
                 ,@dbname='test'
                 ,@freqtype='month'
                 ,@time='000000'

 
 
沒有留言:
張貼留言