Post

SQL Job & Stored Procedure


A SQL Job is a scheduled task or process in Microsoft SQL Server that automates the execution of one or more SQL Server Agent jobs.


A Stored Procedure is a precompiled and stored collection of one or more SQL statements or queries. It can be called with a single command, providing a way to encapsulate and reuse code in a database.



In this scenario, we aim to periodically move data that is 2 months or older from main table to the backup table. We’ll store the SQL Query used for this task in a Stored Procedure and then execute it automatically everyday with an SQL Job.

x



Creating Stored Procedures

First, we create a stored procedure to copy the data older than 2 month to the backup table

x


Then the second stored procedure to delete the already copied data from the main table

x



Creating SQL Jobs

Now we create a Job to execute 2 procedures created above, we name the Job Daily_Backup_Conv

x


Then on first step, execute the first Stored Procedure

x


Then the second step to execute the second Stored Procedure

x


Here’s how the steps ended up

x


On schedule, select Daily Recurring at the desired time

x


To finsih things up, i like to log the operation onto Event Viewer everytime the job executes

x



Executing SQL Jobs

To immediately start the Job, right click on it and select Start Job

x


Then start from the first step

x


And looks like its a success

x


Right click on the Job and select History, we can see the execution history

x


We can also see the history on the Event Viewer

x


And checking on the tables, we can see the data has been successfully moved from the main table to the backup one

x


This post is licensed under CC BY 4.0 by the author.