Skip to main content

Create SQL Server Job in Easy Steps

Job is a set of one or more management tasks. The SQL Server Agent service is managing SQL server jobs. SQL Server Agent is a windows service.
This topic will help to beginners to create SQL Server Jobs in a easy steps. Install Sql Server Management Studio and Go SQL Server Agent.

Purpose:
Some time customer want to complete a specific action in periodically like “Daily”, “Weekly”, and “Monthly”.

  • DBA can Backup database
  • Log repor
  • Data Synchronization (bad practice).
  • Monitoring 

For this tutorial, have created a store procedure that basically calculate “Total Sales Amount”, “Total Discount Amount”, “Total Product” for daily sales and insert this record into a table. For beginners, using “Northwind” database download from codeplex or Microsoft


Create table DailySalesRecords to hold date wise total sale records.



USE [NORTHWIND]
GO

CREATE TABLE [dbo].[DailySalesRecords](
      [OrderDate] [datetime] NOT NULL,
      [TotalAmount] [decimal](18, 4) NOT NULL,

      [TotalDiscount] [decimal](18, 4) NOT NULL,
      [TotalProducts] [bigint] NOT NULL,
      [JobExecutionTime] [datetime] NOT NULL
) ON [PRIMARY]

GO



-- =============================================
-- Author:http://www.code-lake.blogspot.com/
-- Create date: 14-July
-- Description: Get datewise total sales 
-- EXEC DailyTotalSales  
-- =============================================
CREATE PROCEDURE [dbo].[DailyTotalSales] 
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 SET NOCOUNT ON;
 
 
 INSERT INTO DailySalesRecords 
 
 SELECT O.OrderDate, SUM( (OD.Quantity * OD.UnitPrice)) AS TotalAmount
  ,SUM(OD.Discount)AS TotalDiscount,SUM(OD.Quantity) AS TotalProduct, GETDATE()
 FROM 
  Orders O INNER JOIN 
  [Order Details] AS OD ON O.OrderID = OD.OrderID
  WHERE Convert (varchar(10),O.OrderDate,110)= Convert (varchar(10), GETDATE()-1,110)
  GROUP By O.OrderDate 
END


    
 1. Right clicks on Jobs and click New Job…


General:

      2.Give a proper job name, add job owner generally owner will be DBA. Select job category   optional. Category simply helps DBA to monitor jobs. We can create category and assign jobs to new category.




Step:    

    3. Click Steps => Click New to open Job Step Properties wizard. Give step name like “Step1-DailyExecute” => Select type “Transact-SQL script (T-SQL) => Select database where execute command script. In command area, we can add select statement, execute store procedure. We can add more steps.



   
   4.In advanced area, we can set next action after “On success action” and “On failure action”. Add no of “Retry attempts” when fail. Create a output file in your safe drive, in every action system will write log in output file




Schedule:

    5. Add New Schedule. Select Schedule = > click new. Give Schedule name, select  schedule type, select frequency daily, weekly or monthly in different recurs. We can    set start time and also end time. 



    
       Alert:


      6. We can set alert. For alert, give alert name = > checked enable => select type =>               Select you database = > Select Severity. Any kind of exception from alert can be sent to         email, pager, network 



       
         
        Notification:
     
        7. we can sent confirmation in E-mail, Page, net send and also write OS event log when j      job  succeeds , completes or fails 



   To complete this clicks Ok. We can create job with a single script.


USE [msdb]
GO

BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0

-- if Exist in same name
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Job_DailySales', --add job name
  @enabled=1, 
  @notify_level_eventlog=0, 
  @notify_level_email=0, 
  @notify_level_netsend=0, 
  @notify_level_page=0, 
  @delete_level=0, 
  @description=N'Daily total ordder calculaion, amount, discount', 
  @category_name=N'[Uncategorized (Local)]', 
  @owner_login_name=N'sa', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Step1-DailExecute]    Script Date: 07/15/2017 21:40:15 ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Step1-DailExecute',
  @step_id=1, 
  @cmdexec_success_code=0, 
  @on_success_action=1, 
  @on_success_step_id=0, 
  @on_fail_action=2, 
  @on_fail_step_id=0, 
  @retry_attempts=3, 
  @retry_interval=10, 
  @os_run_priority=0, @subsystem=N'TSQL', 
  @database_name=N'NORTHWIND.MDF', 
  @output_file_name=N'E:\Working Project\Documents\Code-Lake.Blogspot.com\Sql Server job\DailySalesLog', 
  @flags=2
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'DailySalesRecords', 
  @enabled=1, 
  @freq_type=4, 
  @freq_interval=1, 
  @freq_subday_type=1, 
  @freq_subday_interval=0, 
  @freq_relative_interval=0, 
  @freq_recurrence_factor=0, 
  @active_start_date=20170714, 
  @active_end_date=20170714, 
  @active_start_time=1000, 
  @active_end_time=235959, 
  @schedule_uid=N'cbdf1f2b-c6a9-4d3a-bb75-39ab3c1c781b'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:

GO

If have any query please leave a comments. 

Comments

Popular posts from this blog

Efficiently Paging Through Large Amounts of Data (PageIndex, Page Size) -SQL Server

In this article you learn how to fetch data according PageIndex and PageSize. In web application, it is much more important to increase webform performance, loadbalance. In my development experience, some of table hold large amount of records (more than 2GB) and user need to shows records in GridView. But problem is when we select all records and loads in webforms, webform has crashed. In that case, I will simply solved with Table Variable and using Grid Page Number and Page Size. 1. Create Procedure CREATE PROCEDURE Load_Data_WithPaging @PageIndex AS INT , /*Selected Row Index of selected grid*/ @PageSize AS INT , /*Total page size of selected grid*/ @TotalRecords AS INT OUT /*used for display virtual page no*/ AS BEGIN SET NOCOUNT ON ; DECLARE @FromIndex AS INT = 0 , @ToIndex AS INT = 0 ; SET @FromIndex = (@PageIndex * @PageSize) + 1 ; /*First row no selection*/ SET @ToIndex = ((@PageIndex

What is an Index? Explain Custered Index and Non-Clustered Index

Index Index is a database object, which can be created on one or more columns (16 Max column combination). When creating the index will read the column(s) and forms a relevant data structure to minimize the number of data comparisons. The index will improve the performance of data retrieval and adds some overhead on data modification such as create, delete and modify. So it depends on how much data retrieval can be performed on table versus how much of DML ( Insert , Delete and Update ) operations. clustered index A clustered index is something that reorganizes the way records in the table are physically stored. Therefore a table can have only one clustered index. The leaf nodes of a clustered index contain the data pages, by which I mean the key-value pair in the clustered index has the index key and the actual data value. Also remember, a clustered index will be created on a table by default the moment a primary key is created on the table. A clustered index is so

How to get all connected DBLINK information -SP_LINKEDSERVERS

I am working several remote server those are connected with DB link. I need create a DB link (remote server oracle db) with my SQL Server, but don't know the required server is connected or not.  at this moment used SQL server default procedure   EXEC SP_LINKEDSERVERS Found below results: all link server name, provider name, DataSource IP those are connected with DBLINK MSDN Column name Data type Description SRV_NAME sysname Name of the linked server. SRV_PROVIDERNAME nvarchar( 128 ) Friendly name of the OLE DB provider managing access to the specified linked server. SRV_PRODUCT nvarchar( 128 ) Product name of the linked server. SRV_DATASOURCE nvarchar( 4000 ) OLE DB data source property corresponding to the specified linked server. SRV_PROVIDERSTRING nvarchar( 4000 ) OLE DB provider string property corresponding to the linked server. SRV