The Wayback Machine - https://web.archive.org/web/20240905202939/https://www.geeksforgeeks.org/configure-sql-jobs-in-sql-server-using-t-sql/
Open In App

Configure SQL Jobs in SQL Server using T-SQL

Last Updated : 15 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let’s discuss it one by one.

Introduction :
SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production servers during the non-Business hours only. So, we create a SQL Server job of running index maintenance and schedule it for “off” hours. When we install SQL Server, the SQL Server Agent is disabled. So at first we will enable it and start it manually. Then, we will configure the SQL Server job using SQL Server Management Studio and the system stored procedures of the MSDB database. So, this article explains how to create SQL Server Job using the system stored procedures of the MSDB database.

System stored procedures of the MSDB database :
SQL Server uses the following ones are as follows.

Query-1 : sp_add_job :
The procedure is for creating a new job. If it is successful, it returns @job_id. The following arguments are applicable as follows.

  • @job_name – 
    It is a unique job name.
  • @enabled – 
    Job is enabled or disabled. Once a job is created, you can set the parameter’s value as 1 to enable the job.
  • @notify_level_eventlog – 
    This parameter is used for writing the status of the SQL Job in Windows event viewer.
Value                             Description
0 The outcome of the job will not be written to the event log.
1 If the job executes successfully, the outcome will be written to the event viewer
2(default value) If the job fails, the outcome and error message will be written to the event viewer.
3 The outcome of the job is written to the event viewer.
  • @notify_level_email – 
    It will send the mail on the basis of job outcome. The valid values of the parameter are the same as the @notify_level_eventlog argument values.
  • @notify_level_page – 
    This parameter serves to send the pager notification of the SQL Job outcome. The valid values of the parameters are the same as the @notiify_level_eventlog argument values.
  • @delete_level – 
    This parameter serves to delete the job after completion. In this case, the value of the parameter should be
  • Note –
    The default value is 0; then, it won’t delete the job after 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’s SQL Login name.

Query-2: Sp_add_jobserver : 
For SQL job execution, it specifies the target server. It accepts the following arguments as follows.

  • @job_id – 
    In SQL job, it identifies the unique values, and it is a UNIQUEIDENTIFIER. Its default value is NULL.
  • @job_name – 
    In SQL job, this parameter specifies the name of job.
  • @server_name – 
    It is the name of the server where you want to run the SQL Job. The default argument value can be the local server (LOCAL) or the targeted server hostname.

Query-3: sp_add_jobstep : 
This stored procedure works for adding the job step in SQL Job. The procedures use the following arguments as follows.

  • @job_name – 
    The name of the job in which you are adding the step. It is an SYSNAME with NULL as the default value.
  • @step_name – 
    The name of the step. It is an SYSYNAME with NULL as 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 code is int value with 0 as a default value.
  • @on_success_action – 
    This value indicates the action that should be performed after the job step completes successfully. The values can be any of the following :
Value Description
1 Quit the job and return success.   
2 Quit the job and return failed.
3 Go to the next job step
4 Go to the step id of on_success_step_id
  • @on_fail_action – 
    Specify what action to be performed if the job steps fail. It is an INT value, and the default value is NULL.
  • @retry_attempt – 
    Specify the number of retry attempts after the job step failure. It is an INT value, and the default value is NULL.
  • @retry_interval – 
    Set the time interval between two SQL job step failure attempts. It is an INT value, and the default value is NULL.
  • @Subsystem – 
    Specify the name of the subsystem used by SQL Server Agent to execute the command. The valid values are the following:
Subsystem value               Description
CmdExec file(*.exe,*.bat) Operating system command or the executable
ANALYSYISQUERY            SQL Server analysis service queries, for example, MDX, DMX
ANALYSISQUERY           SQL Server analysis service command, for example, XMLA.
SSIS                    SQL Server integration service package.
PowerShell                     PowerShell command on the script.
T-SQL                         T-SQL Query or Stored procedure
Distribution                  SQL Server replication distributor agent.
Snapshot                 SQL Server replication snapshot agent.
LogReader                SQL Server replication Log reader agent.
QueueReader           SQL Server replication queue reader.
  • @command – 
    Specify the command that the SQL Server Agent 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 want to run the command. This parameter is useful when you are running a T-SQL script using SQL Server Agent.

Query-4:Sp_add_jobschedule : 
The stored procedures serve to create the SQL Job schedule. This procedure uses the following arguments as follows.

  • @job_name –
    Specify the name of the SQL Job. The schedule will be made for the SQL Job specified in the @job_name argument.
  • @name – 
    Name of the schedule. The data type is varchar, and the default value is NULL.
  • @enabled – 
    Set  1 to enable the schedule or 0 to disable the schedule.
  • @freq_types – 
    Indicates the time of the SQL Job execution. The data type of the parameter is INT, and the default value is 0. The valid values are any of the following :
Value Description
1 The JOB will be executed only One Time.
4 Daily
8  Weekly
16 Monthly
64 Executes the job when the SQL Server Agent Services start.
128 Execute the SQL Job 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 any of the following :
Value Effect on the job schedule
1(Once) The @Freq_interval will not be used.
4(Daily) Every @freq_interval days
8

 The value of the @Freq_interval can be any of the following as follows.

                          1=Sunday

                          2=Monday

                          4=Tuesday

                          8=Wednesday

                          16=Thursday

                          32= Friday

                          64= Saturday

16 Run the job on the @Freq_interval day of the month
64 The @Freq_interval  will not be used.
128 The @Freq_interval will not be used.
  • @freq_subday_type – 
    Specify the unit of the freq_subday_interval. The data type is INT, and the default value is NULL.
  • @active_start_date – 
    Set the date when you want to start the job execution. The data type is INT, and it does not have a default value. The date format is YYMMDD. The value must be greater or equal than 19900101.
  • @active_end_date – 
    Specify the date when to stop the job execution. The data type is INT, with no default value. The date format is YYMMDD, and the value must be greater or equal than 19900101.
  • @active_start_time – 
    Specify the time when you want to start the job execution. The data type is INT, without a default value . The time format is HHMMSS.
  • @active_end_time – 
    Specify the time when you want to stop the job execution. The data type is INT, without a default value. The time format is HHMMSS.


Similar Reads

Microsoft Azure - Configure Azure SQL
Pre-requisite: Azure VM Azure SQL Database is a cloud-based PaaS database service that is completely managed and extremely scalable. When you need to establish a new application in the cloud, this service includes the essential database-level capabilities of an on-premises SQL Server. The Azure SQL Database can be used as a single database or as pa
2 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
SQL Server | Convert tables in T-SQL into XML
In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let's discuss it one by one. Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms.
2 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
Top 10 High Paying Jobs That Demand SQL in 2024
SQL can execute queries, retrieve data, insert or delete records, create tables or stored procedures in a database, and so on. SQL is the most adaptable niche in the market. Switching jobs once you enter the IT industry is not a big deal. The hardest part is at the beginning. But most of the students who are going to begin their career in the datab
7 min read
How to Configure PostgreSQL in Linux?
Quick Preview to Configure PostgreSQL on Linux:Install PostgreSQL on Linux:On Linux Terminal, execute the command sudo apt-get updateTo install and execute the command, sudo apt install postgresql postgresql-contrib Check the Status of PostgreSQL on Linux:Checking status use command service postgresql status.Enter Into PostgreSQL Configuration:Ente
5 min read
Copy tables between databases in SQL Server using Import-and-Export Wizard
Introduction to Import-and-Export Wizard : The wizard allows easy steps through a process, and to execute the data copy process with writing very little or no code. However, for importing and exporting data from one source into another, the below steps could be followed - Open the Object Explorer, select the database, right-click on the database na
2 min read
Capturing Deleted Rows in SQL Server Without Using a Trigger
Introduction : Working with triggers can be difficult and time-consuming at times. Triggers can slow down the server's output and place additional pressure on the system's resources. Many people use triggers to keep track of all the data that has been removed from tables. Instead of using triggers, we might use another process, as seen in the examp
2 min read
How to Export Data to the .CSV File Using SQL Server Stored Procedure?
CSV (Comma-separated values) is a file that consists of plain text data in which data is separated using comma(,). It is also known as Comma Delimited Files because comma act as a delimiter for CSV files. Here we will see, the process of exporting Data to the .CSV file using the SQL Server Stored Procedure. Step to Export Data to the .CSV File Usin
2 min read
How to Update Multiple Records Using One Query in SQL Server?
To update multiple records in the SQL server, use the UPDATE Statement. Using the SQL UPDATE statement with the WHERE clause users can update multiple records in the table based on some condition. There can be two cases in this situation: Table of Content Update Multiple Records Based on One Condition in SQL ServerUpdate Multiple Records Based on M
4 min read
QUOTENAME() Function in SQL Server
QUOTENAME() function : This function in SQL Server is used to return a Unicode string with delimiters added in order to make the string a valid SQL Server delimited identifier. Features : This function is used to find a Unicode string with delimiters added. This function accepts only strings and delimiters. This function add delimiters by default i
3 min read
SQL Server Identity
Identity column of a table is a column whose value increases automatically. The value in an identity column is created by the server. A user generally cannot insert a value into an identity column. Identity column can be used to uniquely identify the rows in the table. Syntax: IDENTITY [( seed, increment)] Seed: Starting value of a column. Default
1 min read
SQL SERVER | Conditional Statements
While loop: In SQL SERVER, while loop can be used in similar manner as any other programming language. A while loop will check the condition first and then execute the block of SQL Statements within it as long as the condition evaluates true. Syntax: WHILE condition BEGIN {...statements...} END; Parameters: 1. Condition: The condition is tested in
2 min read
SQL Server | SERVERPROPERTY()
SQL Server provides a System Defined function SERVERPROPERTY(propertyname). SERVERPROPERTY(): SERVERPROPERTY() function is used to return the information about different properties of system or so called the instance information. propertyname: This expression contains the information about property in question and returns the same. Following are fe
2 min read
Mean and Mode in SQL Server
Mean is the average of the given data set calculated by dividing the total sum by the number of values in data set. Example: Input: 1, 2, 3, 4, 5 Output: 3 Explanation: sum = 1 + 2 + 3 + 4 + 5 = 15 number of values = 5 mean = 15 / 5 = 3 Query to find mean in the table SELECT Avg(Column_Name) FROM Table_Name Example: Creating Table: Table Content: Q
1 min read
Allow only alphabets in column in SQL Server
There may occur some situations when data in column should only be in alphabets, for example: Name column in details table. If user try to input other than alphabets, it will give error. To allow only alphabets in a column check constraint can be applied over column. To get information about Constraints and Check Constraints, refer below article li
1 min read
SQL SERVER | IN Condition
IN condition is an alternative to multiple OR conditions in SELECT, INSERT, UPDATE, or DELETE statement. The IN operator allows multiple values to be tested against the expression and thus reduces the use of multiple OR conditions with each test value. Syntax: expression IN (value1, value2, .... value_n); Where 1. expression : value/attribute to be
1 min read
REVERSE() Function in SQL Server
REVERSE() function : This function in SQL Server is used to reverse the stated string and return the output. Features : This function is used to reverse the stated string. This function accepts strings as parameter. This function always returns string. This function can also take set of integers and reverse it. This function can even reverse float
1 min read
Reverse Statement Word by Word in SQL server
To reverse any statement Word by Word in SQL server we could use the SUBSTRING function which allows us to extract and display the part of a string. Pre-requisite :SUBSTRING function Approach : Declared three variables (@Input, @Output, @Length) using the DECLARE statement. Use the WHILE Loop to iterate every character present in the @Input. For th
2 min read
How to Export Data From SQL Server to Flat File in SSIS?
In this article, we will learn how to Export Data From SQL Server To Flat File in SSIS. For this, we are going to create a package to select the data from the SQL server database and export SQL Server table data to the Flat File in the local drive. Prerequisites:Make sure Visual Studio 2019 is installed.Ensure that SQL Server Management Studio is i
3 min read
How to Turning a Comma Separated String into Individual Rows in SQL Server?
Given a column in the table having strings with comma-separated values. The task is to split all the comma-separated values and insert them as new rows. So, let's start by creating a database first. Step 1: Create a Database. Query : CREATE DATABASE GFGStep 2: Use the GFG Database. Query : USE GFGStep 3: Create a table Create a table (CommaSeparate
1 min read
Difference between MySQL and MS SQL Server
SQL is an acronym for Structured Query Language. It is used to access, manipulate and retrieve information from a database. MySQL is an open source Relational Database Management System (RDBMS) based on Structured Query Language (SQL). It runs on platforms like Linux, UNIX and Windows. SQL Server is owned and developed by Microsoft Corporation. The
2 min read
SESSIONPROPERTY() Function in SQL Server
SESSIONPROPERTY() function : This function in SQL Server is used to return the settings of the session that is specified in the argument section. Features : This function is used to find the settings of the session state.This function comes under Advanced Functions.This function accepts only one parameter namely option. Syntax : SESSIONPROPERTY(opt
2 min read
Comparisons between Oracle vs SQL Server
Among several electronic database Management System, the 2 most well-liked and widely used are Oracle and SQL Server. Oracle supports operating systems such as Windows, Linux, Solaris, HP-UX, OS X, etc. Whereas SQL Server supports only windows and Linux operating systems. There are several basic variations between Oracle and SQL Server one of the f
2 min read
Backup Database in MS SQL Server
Prerequisite – Create database in MS SQL Server To Create a Full Database Backup, the below methods could be used - SQL Server Management Studio. Transact-SQL. Restriction : Backups created on a newer version of SQL Server cannot be restored in previous versions of SQL Server. Facts to know : When the database size increases, full database backups
3 min read
List the available Databases for Current User in SQL SERVER
Introduction : One of the pre-needful of Database Performance Health Check is to have access to the database which we're going to tune. As SQL DBAs we can also additionally discover it unexpected that quite sometimes, we ended up in a scenario in which we've got a customer who needs us to assist with their database overall performance however they
2 min read
Article Tags :