banner



Which Of The Following Stored Procedures Add A New Job Executed By The Sqlserveragent Service

Configure SQL Jobs in SQL Server using T-SQL

SQL Server Amanuensis is a component used for the database tasks automation. For case, we need to perform Index maintenance on Production servers during the non-business hours only. And then, we create a SQL Server job of running index maintenance and schedule it for "off" hours.

When nosotros install SQL Server, the SQL Server Amanuensis service is disabled. First, we enable it and showtime information technology manually. Then, we configure the SQL Server job, using SQL Server Direction Studio and the system stored procedures of the MSDB database.

This article explains how to create a SQL Server Job using the system stored procedures of the MSDB database.

The system stored procedures of the MSDB database

SQL Server uses the following ones:

  1. sp_add_job: the procedure is for creating a new chore. If it is successful, information technology returns @job_id. The following arguments are applicable:
  • @job_name: Information technology is a unique job proper name.
  • @enabled: Job is enabled or disabled. Once a task is created, you tin gear up the parameter'due south value every bit 1 to enable the job.
  • @notify_level_eventlog: This parameter is used for writing the status of the SQL Job in Windows event viewer.

0 — The consequence of the job will not be written to the event log.

1 — If the task executes successfully, the event will be written to the event viewer

2 (default value) — If the chore fails, the consequence and an error message volition be written to the event viewer

3 — The outcome of the task is written to the event viewer.

  • @notify_level_email: This parameter serves to ship the email virtually the SQL Job issue. The valid values of the parameter are the same every bit the @notify_level_eventlog argument values.
  • @notify_level_page: This parameter serves to send the pager notification of the SQL Job consequence. The valid values of the parameters are the aforementioned equally the @notify_level_eventlog argument values.
  • @delete_level: This parameter serves to delete the job later completion. In this case, the value of the parameter should be i. Note that the default value is 0; then, it won't delete the task afterwards completion.
  • @category_level: This parameter indicates the job category values. The default value is NULL.
  • @owner_login_name: The value is the domain name or the job owner'south SQL Login name.
  • 2. Sp_add_jobserver: This stored process serves to specify the target server for the SQL Job execution. The procedure accepts the post-obit arguments:
  • @job_id: It is a UNIQUEIDENTIFIER of the SQL Job. The default value of this statement is Nix.
  • @job_name: It is the name of the SQL Task.
  • @server_name: It is the proper noun of the server where you want to run the SQL Job. The default statement value can be the local server (LOCAL) or the target server hostname.

3. sp_add_jobstep: This stored process works for calculation the job stride in SQL Job. The procedure uses the post-obit arguments:

  • @job_name: The name of the job in which you are calculation the step. It is an SYSNAME with NULL equally the default value.
  • @step_name: The proper noun of the step. It is an SYSNAME with Zero as the default value.
  • @step_id: The sequential ID of the job step. It is an incremental number without a gap. It is an INT value, and the default value is NULL.
  • @cmdexec_success_code: This value is returned by the CmdExec subsystem. It indicates whether the command execution was successful. The lawmaking is int value with 0 every bit a default value.
  • @on_sucess_action: This value indicates the activeness that should be performed later the task step completes successfully. The values can be any of the post-obit:

1 — Quit the chore and render success

2 — Quit the job and return failed

3 — Go to the side by side job step

4 — Go to the footstep id of on_success_step_id

  • @on_fail_action: specify what action to perform if the job steps fail. It is an INT value, and the default value is NULL.
  • @retry_attempt: specify the number of retry attempts subsequently the job footstep failure. It is an INT value, and the default value is Zilch.
  • @retry_interval: fix the time interval (minutes) between ii SQL Job step failure attempts. It is an INT value, and the default value is NULL.
  • @os_run_priority:
  • @Subsystem: specify the proper name of the subsystem used by SQL Server Agent to execute the command. The valid values are the post-obit:

CmdExec — Operating system control or the executable file(*.exe,*.bat)

ANALYSISQUERYSQL — Server assay service queries, for instance, MDX, DMX.

ANALYSISQUERYSQL — Server assay service command, for example, XMLA.

SSISSQL — Server integration service package.

PowerShell — PowerShell command or script.

T-SQL — T-SQL Query or Stored process

Distribution — SQL Server replication benefactor agent.

Snapshot — SQL Server replication snapshot amanuensis.

LogReader — SQL Server replication Log reader agent.

Queuereader — SQL Server replication queue reader.

  • @command: specify the command that the SQL Server Amanuensis Service should execute through the subsystem. The data type is varchar(max), and the default value is NULL.
  • @Database_name: Specify the name of the database where you desire to run the command. This parameter is useful when you are running a T-SQL script using SQL Server Agent.

4. Sp_add_jobschedule: the stored procedure serves to create the SQL Job schedule. This process uses the post-obit arguments:

  • @job_name: specify the name of the SQL Job. The schedule will be made for the SQL job specified in the @job_name statement.
  • @name: the name of the schedule. The information blazon is varchar, and the default value is NULL.
  • @enabled: set 1 to enable the schedule or 0 to disable the schedule.
  • @freq_type: indicates the time of the SQL task execution. The data type of the parameter is INT, and the default value is 0. The valid values are any of the following:

1 — The chore will exist executed merely One time.

4 — Daily.

8 — Weekly.

16 — Monthly.

64 — Execute the job when the SQL Server Agent Service starts

128 — Execute the SQL chore when the server is idle.

  • @freq_interval: indicates the day of the SQL job execution. The data type is INT, and the default value is 0. The value depends on the value specified in the @freq_type parameter. The valid values are whatsoever of the following:

  • @freq_subday_type: specify the unit of the freq_subday_interval. The information blazon is INT, and the default value is NULL.
  • @active_start_date: set up the date when y'all want to start the job execution. The data type is INT, and it does not have a default value. The date format is YYYYMMDD. The value must be greater or equal to 19900101.
  • @active_end_date: specify the engagement when to stop the job execution. The data blazon is INT, with no default value. The date format is YYYYMMDD, and the value must exist greater or equal to 19900101.
  • @active_start_time: specify the time when you want to start the job execution. The information type is INT, without a default value. The fourth dimension format is HHMMSS.
  • @active_end_time: specify the time when you want to cease the job execution. The data type is INT, without a default value. The time format is HHMMSS.

T-SQL Code to create a SQL Job

To illustrate the processes, we use the SQL Server 2019 on the workstation with the AdventureWorks2017 database, restored from a backup. We create a SQL Job named Daily Full Backup — it generates a backup of the AdventureWorks2017 database and copies it on C:\Backups location.

First, nosotros must enable the Agent XPs. It is an advanced selection. Therefore, we start enable the advanced configuration option and the Agent XPs component.

To do that, run the following query:

          EXEC Sp_configure            
'Show advanced options',
1
go RECONFIGURE WITH override EXEC Sp_configure
'Agent XPs',
one
get RECONFIGURE WITH override

Once the Agent is enabled, we get-go the Amanuensis service.

Open up SQL Server Direction Studio and connect to the SQL Server instance. Then, right-click on SQL Server Agent and click Start.

After the start of the Agent, nosotros can create the SQL Server agent jobs.

Every bit mentioned, we will create a SQL job to generate a backup of the AdventureWorks2017 database. For this, we run the post-obit command using SQL Server Amanuensis.

          North'Backup Database [AdventureWorks2017] to deejay=''C:\Backups\AdventureWorks2017.bak'' with compression'        

To create a new SQL Job named Daily Total Backup, execute the following script:

          Employ [msdb]            
become
DECLARE @jobId BINARY(16)
EXEC msdb.dbo.Sp_add_job
@job_name=N'Daily Full Fill-in',
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=2,
@notify_level_page=2,
@delete_level=0,
@category_name=N'[Uncategorized (Local)]',
@owner_login_name=N'NISARG-PC\Nisarg',
@job_id = @jobId output
SELECT @jobId
go

It will execute the job on my local workstation. Thus, we add it to the Job Server.

Execute the post-obit query:

          EXEC msdb.dbo.Sp_add_jobserver            
@job_name=N'Daily Full Fill-in',
@server_name = N'NISARG-PC'
become

The job step executes the backup database command. To configure the job step, use the following code:

          USE [msdb]            
get
EXEC msdb.dbo.Sp_add_jobstep
@job_name=N'Daily Full Fill-in',
@step_name=North'Generate Fill-in',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_fail_action=2,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0,
@subsystem=N'TSQL',
@command=
N'Backup Database [AdventureWorks2017] to disk=''C:\Backups\AdventureWorks2017.bak'' with compression'
,
@database_name=N'main',
@flags=0
go

The SQL Job volition run daily at 1:00 AM. To configure the schedule, use the following lawmaking:

          USE [msdb]            
go
DECLARE @schedule_id INT EXEC msdb.dbo.Sp_add_jobschedule
@job_name=N'Daily Full Backup',
@proper noun=North'Run Backup At',
@enabled=1,
@freq_type=4,
@freq_interval=1,
@freq_subday_type=one,
@freq_subday_interval=0,
@freq_relative_interval=0,
@freq_recurrence_factor=one,
@active_start_date=20200918,
@active_end_date=99991231,
@active_start_time=10000,
@active_end_time=235959,
@schedule_id = @schedule_id output
SELECT @schedule_id get

The entire code of the task is every bit follows:

          Utilize [msdb]            
go
DECLARE @jobId BINARY(16) EXEC msdb.dbo.Sp_add_job
@job_name=N'Daily Full Backup',
@enabled=ane,
@notify_level_eventlog=0,
@notify_level_email=2,
@notify_level_page=2,
@delete_level=0,
@category_name=North'[Uncategorized (Local)]',
@owner_login_name=N'NISARG-PC\Nisarg',
@job_id = @jobId output
SELECT @jobId
become
EXEC msdb.dbo.Sp_add_jobserver
@job_name=N'Daily Total Fill-in',
@server_name = N'NISARG-PC'
become USE [msdb]
get
EXEC msdb.dbo.Sp_add_jobstep
@job_name=North'Daily Full Backup',
@step_name=North'Generate Backup',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_fail_action=2,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0,
@subsystem=North'TSQL',
@control=
N'Backup Database [AdventureWorks2017] to disk=''C:\Backups\AdventureWorks2017.bak'' with compression'
,
@database_name=N'primary',
@flags=0
go
Apply [msdb]
get
DECLARE @schedule_id INT EXEC msdb.dbo.Sp_add_jobschedule
@job_name=Due north'Daily Total Fill-in',
@name=N'Run Backup At',
@enabled=1,
@freq_type=four,
@freq_interval=1,
@freq_subday_type=1,
@freq_subday_interval=0,
@freq_relative_interval=0,
@freq_recurrence_factor=1,
@active_start_date=20200918,
@active_end_date=99991231,
@active_start_time=10000,
@active_end_time=235959,
@schedule_id = @schedule_id output
SELECT @schedule_id
go

We run the task manually for the demonstration first, past executing the code below:

          use msdb
go
exec sp_start_job 'Daily Full Backup'

You can view the status of the chore by running the post-obit query:

          SELECT  NAME            
Every bit [Chore Proper name],
CONVERT(VARCHAR, Dateadd(s, ( run_time / 10000 ) * threescore * sixty

+ ( ( run_time - ( run_time / 10000 ) *
10000 ) /
100 ) * 60

+ ( run_time - ( run_time / 100 ) * 100
), Catechumen(DATETIME, Rtrim(run_date), 113)), 100)
As
[Job Executed Date and Fourth dimension],
CASE
WHEN enabled = i THEN 'Enabled'
ELSE 'Disabled'
Finish
[Chore Condition],
Case
WHEN JobHistory.run_status = 0 THEN 'Failed'
WHEN JobHistory.run_status = 1 THEN 'Succeeded'
WHEN JobHistory.run_status = ii And then 'Retry'
WHEN JobHistory.run_status = 3 And so 'Cancelled'
ELSE 'Unknown'
END
[Job Upshot]
FROM sysjobhistory JobHistory
JOIN sysjobs Jobs
ON JobHistory.job_id = Jobs.job_id
WHERE Name = 'Daily Full Fill-in'

Output:

To view the fill-in file, Open the C:\Backups location:

Every bit you can see, the fill-in file has been created.

Which Of The Following Stored Procedures Add A New Job Executed By The Sqlserveragent Service,

Source: https://codingsight.medium.com/configure-sql-jobs-in-sql-server-using-t-sql-7b94f5b8787c

Posted by: jacksontallay.blogspot.com

0 Response to "Which Of The Following Stored Procedures Add A New Job Executed By The Sqlserveragent Service"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel