日期:2014-05-18  浏览次数:20766 次

能不能通过脚本代码生成一个作业?
sql   server数据库中,每天都要执行一小段代码,比如会员卡过了有效期以后就要将卡状态改为“失效”。现在是在企业管理器中手工新建一个作业,但是如果发布程序以后,就不应该还用人工方式来新建作业,应该有程序自动来添加作业。但是怎么用代码生成一个作业呢?

------解决方案--------------------
先手工创建Job,然后右键生成脚本即可。
------解决方案--------------------
给你一个例子

-- Script generated on 2007-3-24 10:58
-- By: sa
-- Server: (LOCAL)

BEGIN TRANSACTION
DECLARE @JobID BINARY(16)
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
IF (SELECT COUNT(*) FROM msdb.dbo.syscategories WHERE name = N '[Uncategorized (Local)] ') < 1
EXECUTE msdb.dbo.sp_add_category @name = N '[Uncategorized (Local)] '

-- Delete the job with the same name (if it exists)
SELECT @JobID = job_id
FROM msdb.dbo.sysjobs
WHERE (name = N 'job1 ')
IF (@JobID IS NOT NULL)
BEGIN
-- Check if the job is a multi-server job
IF (EXISTS (SELECT *
FROM msdb.dbo.sysjobservers
WHERE (job_id = @JobID) AND (server_id <> 0)))
BEGIN
-- There is, so abort the script
RAISERROR (N 'Unable to import job ' 'job1 ' ' since there is already a multi-server job with this name. ', 16, 1)
GOTO QuitWithRollback
END
ELSE
-- Delete the [local] job
EXECUTE msdb.dbo.sp_delete_job @job_name = N 'job1 '
SELECT @JobID = NULL
END

BEGIN

-- Add the job
EXECUTE @ReturnCode = msdb.dbo.sp_add_job @job_id = @JobID OUTPUT , @job_name = N 'job1 ', @owner_login_name = N 'sa ', @description = N 'No description available. ', @category_name = N '[Uncategorized (Local)] ', @enabled = 1, @notify_level_email = 0, @notify_level_page = 0, @notify_level_netsend = 0, @notify_level_eventlog = 2, @delete_level= 0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

-- Add the job steps
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobstep @job_id = @JobID, @step_id = 1, @step_name = N 's1 ', @command = N 'select * from customer ', @database_name = N 'AES000DATEnterprise ', @server = N ' ', @database_user_name = N ' ', @subsystem = N 'TSQL ', @cmdexec_success_code = 0, @flags = 0, @retry_attempts = 0, @retry_interval = 1, @output_file_name = N ' ', @on_success_step_id = 0, @on_success_action = 1, @on_fail_step_id = 0, @on_fail_action = 2
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXECUTE @ReturnCode = msdb.dbo.sp_update_job @job_id = @JobID, @start_step_id = 1

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

-- Add the Target Servers
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @JobID, @server_name = N '(local) '
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:


--主要的是
msdb.dbo.sp_add_job
msdb.dbo.sp_add_jobstep
msdb.dbo.sp_add_jobserver