Sunday, February 7, 2010

SQL Server Agent Jobs Examples !

USE [msdb]
GO
DECLARE @jobId BINARY(16)
EXEC msdb.dbo.sp_add_job @job_name=N'backup_system_db',
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=2,
@notify_level_netsend=2,
@notify_level_page=2,
@delete_level=0,
@category_name=N'Database Maintenance',
@owner_login_name=N'HOME-BIX5T88DR6\Administrator',
@notify_email_operator_name=N'sudarsan', @job_id = @jobId OUTPUT
select @jobId
GO
EXEC msdb.dbo.sp_add_jobserver @job_name=N'backup_system_db', @server_name = N'HOME-BIX5T88DR6\CSFSPD1CASPRO'
GO
USE [msdb]
GO
EXEC msdb.dbo.sp_add_jobstep @job_name=N'backup_system_db', @step_name=N'master_backup',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_fail_action=2,
@retry_attempts=3,
@retry_interval=2,
@os_run_priority=0, @subsystem=N'TSQL',
@command=N'backup database master
to disk=N''G:\Backups\mast.bak''
with init,stats=25,description=''master db backup'';
GO

print ''backup of master db successfully completed on''+convert(varchar(50), GETDATE())',
@database_name=N'master',
@database_user_name=N'dbo',
@output_file_name=N'G:\Backups\outputonbackup',
@flags=0
GO
USE [msdb]
GO
EXEC msdb.dbo.sp_update_job @job_name=N'backup_system_db',
@enabled=1,
@start_step_id=1,
@notify_level_eventlog=0,
@notify_level_email=2,
@notify_level_netsend=2,
@notify_level_page=2,
@delete_level=0,
@description=N'',
@category_name=N'Database Maintenance',
@owner_login_name=N'HOME-BIX5T88DR6\Administrator',
@notify_email_operator_name=N'sudarsan',
@notify_netsend_operator_name=N'',
@notify_page_operator_name=N''
GO
USE [msdb]
GO
DECLARE @schedule_id int
EXEC msdb.dbo.sp_add_jobschedule @job_name=N'backup_system_db', @name=N'schedule1',
@enabled=1,
@freq_type=8,
@freq_interval=1,
@freq_subday_type=1,
@freq_subday_interval=0,
@freq_relative_interval=0,
@freq_recurrence_factor=1,
@active_start_date=20100208,
@active_end_date=99991231,
@active_start_time=0,
@active_end_time=235959, @schedule_id = @schedule_id OUTPUT
select @schedule_id
GO

The above job simply creates a backup of master db,outputs the step output to a file.

Example2 :

USE [msdb]
GO
EXEC msdb.dbo.sp_add_alert @name=N'alert2',
@enabled=1,
@delay_between_responses=120,
@include_event_description_in=0,
@performance_condition=N'MSSQL$CSFSPD1CASPRO:Databases|Data File(s) Size (KB)|kali|>|256000',
@job_id=N'00000000-0000-0000-0000-000000000000'
GO
EXEC msdb.dbo.sp_add_notification @alert_name=N'alert2', @operator_name=N'sudarsan', @notification_method = 1
GO