SQL語句創建SQL作業?

Tags: 作業, 語句,

本主題介紹如何使用 SQL Server Management Studio、Transact-SQL 或 SQL Server 管理對象,在 SQL Server 2014 中創建用於執行 Transact-SQL 腳本的 Microsoft SQL Server 代理作業步驟。

這些作業步驟腳本可以調用存儲過程和擴展存儲過程。 一個 Transact-SQL 作業步驟可以包含多個批處理和嵌入的 GO 命令。

工具/原料

SQL Server Management Studio

Transact-SQL

SQL Server 管理對象

方法/步驟

根據sendTab的SendTime定製作,並且在該作業完成時,可以自動刪除作業

SQL語句創建SQL作業

SQL語句創建SQL作業

SQL語句創建SQL作業

SQL語句創建SQL作業

SQL語句創建SQL作業

--示例

--測試表create table sendTab(ID int identity(1,1),Name varchar(10) ,SendTime datetime,AcceptUnit varchar(10) ,SendUnit varchar(10),Content varchar(8000))create table accepteTab(ID int identity(1,1),Name varchar(10) ,SendUnit varchar(10),AcceptUnit varchar(10),Content varchar(8000))go

--創建處理的存儲過程create proc [email protected] int, --要處理的sendTab的[email protected]_delete bit=0 --是否僅刪除,為0則否,為1則是asdeclare @dbname sysname,@jobname sysname ,@date int,@time intselect @jobname='定時發送作業_'+cast(@id as varchar) ,@date=convert(varchar,SendTime,112) ,@time=replace(convert(varchar,SendTime,108),':','')from sendTab where [email protected] exists(select 1 from msdb..sysjobs where [email protected]) exec msdb..sp_delete_job @[email protected] if @is_delete=1 return

SQL語句創建SQL作業

--創建作業exec msdb..sp_add_job @[email protected],@delete_level=1

--創建作業步驟declare @sql varchar(800)select @sql='insert accepteTab(name,SendUnit,AcceptUnit,Content) select name,AcceptUnit,SendUnit,Content from sendTab where id=' +cast(@id as varchar) ,@dbname=db_name()exec msdb..sp_add_jobstep @[email protected], @step_name = '發送處理步驟', @subsystem = 'TSQL', @[email protected], @command = @sql, @retry_attempts = 5, --重試次數 @retry_interval = 5 --重試間隔--創建調度EXEC msdb..sp_add_jobschedule @job_name = @jobname, @name = '時間安排', @enabled = 1, @freq_type = 1, @active_start_date = @date, @active_start_time = @time-- 添加目標服務器EXEC msdb.dbo.sp_add_jobserver @job_name = @jobname , @server_name = N'(local)' go

--創建處理的觸發器(新增/修改)create trigger tr_insert_update on sendTabfor insert,updateasdeclare @id intdeclare tb cursor local for select id from insertedopen tbfetch next from tb into @idwhile @@fetch_status=0begin exec p_JobSet @id fetch next from tb into @idendclose tbdeallocate tbgo--創建處理的觸發器(刪除)create trigger tr_delete on sendTabfor deleteasdeclare @id intdeclare tb cursor local for select id from deletedopen tbfetch next from tb into @idwhile @@fetch_status=0begin exec p_JobSet @id,1 fetch next from tb into @idendclose tbdeallocate tbgo--測試--插入數據insert sendTabselect '文書1','2004/5/1 12:00:00','UnitA','UnitB','txt'union all select '文書2','2004/5/12 12:00:00','UnitA','UnitB','txt'union all select '文書3','2004/5/21 12:00:00','UnitA','UnitB','txt'--修改update sendTab set name='檔案1',SendTime='2004/5/1 15:00:00'where id=1--刪除delete sendtab where id=3go--刪除測試drop table sendTab,accepteTabdrop proc p_JobSet

相關問題答案