使用TSQL建立作業

2021-04-01 20:25:46 字數 2142 閱讀 4257

使用tsql建立作業

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]

gocreate 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分

asif 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'

使用TSQL建立作業

使用tsql建立作業 if exists select from dbo.sysobjects where id object id n dbo p createjob and objectproperty id,n isprocedure 1 drop procedure dbo p create...

用T SQL建立和刪除SQL作業

以下是 片段 定義建立作業 declare jobid uniqueidentifier,jobname sysname set jobname n 作業名稱 if exists select from msdb.dbo.sysjobs where name jobname exec msdb.db...

使用T sql建立資料庫

使用t sql語句建立 myshool 資料庫及刪除資料庫。要求 myshool 資料庫的主資料檔名為 myshool.mdf,初始大小為3mb,最大為50mb,增長方式為10 日誌檔案的初始大小為1mb,最大為5mb,增長方式為1mb。資料檔案和日誌檔案均存放在d盤根目錄下。create data...

使用T SQL語言建立資料庫

use master if exists select from sysdatabases where name score 檢查score資料庫是否存在 drop database score 存在就刪除 create database score 建立score資料庫 on primary na...

使用T SQL語句建立資料庫

if exists select from sysdatabases where name ssh drop database ssh 建立資料 create database 09網路1 on primary 檔案所在的檔案組 name 09網路1 data 資料庫主檔案的名稱 filename ...