Develop an SQL Server Job from scratch - Database - Techguide

Develop an SQL Server Job from scratch

 

Summary

The ability to automate administrative tasks is vital in almost any SQL Server database environment.

Events

IBM Technology Conference & Expo 2012
May 22, 2012

One World Hotel, First Avenue, Bandar Utama City Centre, 47800 Petaling Jaya, Selangor

Echelon 2012
June 11 and 12, 2012

University Cultural Centre, National University of Singapore

Startup Asia Jakarta 2012
June 7 and 8, 2012

12th Floor, Annex Building, Wisma Nusantara Complex, Jl. M.H. Thamrin No. 59 Jakarta 10350, Indonesia

MMA Forum Singapore
April 23-25, 2012

Grand Hyatt Singapore

In the SQL Server world, this scheduling of work is known as a "Job".

It allows you to perform such tasks as database maintenance, invoke executables, ActiveX script, Integration Services packages, and business transactions.

I'll show you how to develop a SQL Server Job from scratch to monitor the size of the database files on your server.

SQL Agent
The SQL Agent is a Windows service that is installed with SQL Server; it is the application responsible for the scheduling and executing of SQL Server Jobs.

These Jobs include: one or more steps in which operations are performed; different schedules to determine when the Jobs are executed; and alerts set up so that business owners are notified when Jobs are successful, when they fail, or when they complete.

Example
In a previous article, I describe how to use built-in system views in SQL Server 2005 to capture a snapshot of the size of the database files on your system. While it's a great method for illustrating how you can capture this information, it would be better to automatically capture this information at regular intervals and alert the appropriate people if any of the databases grow outside of what is expected.

In this example, I will detail how you can develop a SQL Server Job to capture this data at regular intervals and send a Database Mail e-mail to alert you when one or more databases get too big.

To create a Job, I open SQL Server Management Studio and right-click the Jobs folder under the SQL Server Agent heading and select New Job. This opens the window in Figure A.

Figure A

Figure A

This screen presents me with all of the available options for creating the Job. I need to give the Job a name and an owner. I also have the option of assigning a category, as well as a description, to the Job. By using the options on the left-hand side of the screen, I can assign steps to the Job, one or more Job schedules, and alerts.

Most of the work of defining a Job occurs in the Steps section. To create a new Job step, navigate to the Steps option on the left side of the New Job menu. Select the New Job button at the bottom of the new window.

When creating a new step, you give the step a name, indicate what type of action will occur (such as a TSQL script, command prompt, or an Integration Services package), and the command involved. The only step in my Job will execute a TSQL script that will load data into the DatabaseFiles table and send an e-mail if any of my databases are over 5 gigabytes. See Figure B.

Figure B

Figure B

Here is the script used in the Job step:

IF OBJECT_ID('DatabaseFiles') IS NULL
  BEGIN
      SELECT TOP 0 * INTO DatabaseFiles
      FROM sys.database_files            

      ALTER TABLE DatabaseFiles
      ADD CreationDate DATETIME DEFAULT(GETDATE())
  END        

 TRUNCATE TABLE DatabaseFiles        

 EXECUTE sp_msforeachdb 'INSERT INTO DatabaseFiles SELECT *, 
 GETDATE() FROM [?].sys.database_files'        

 IF EXISTS
 (
         SELECT SizeInMB = CAST(((SIZE * 8.00)/1024.00) AS DECIMAL(18,2))
         from DatabaseFiles
         WHERE CAST(((SIZE * 8.00)/1024.00) AS DECIMAL(18,2)) > 5000
 )
 BEGIN
         EXECUTE msdb.dbo.sp_send_dbmail
         @recipients=N'chapman.tim@gmail.com',
         @body='The size of one or more databases have 
         grown outside of the expected bounds.',
         @subject ='Database(s) possibly need attention.',
         @profile_name ='Database-mailProfile';
 END

In the Advanced section of Job Steps, I can define how to handle when the step of the Job succeeds or fails. I can add logic to skip to a separate step or skip to the next defined step, or quit the Job reporting success or failure. In addition, I can output the results of the Job step to an output file or database table.

I find it really helpful to keep a long running history of Job step successes and failures; this assists me in finding problems that may have occurred in the distant past. See Figure C.

Figure C

Figure C

I want this to run at regular intervals, so I need to define a schedule for the Job. I want this Job to run at midnight every night, so I really just need to define one schedule. However, you can define as many schedules for a Job as you'd like. See Figure D.

Figure D

Figure D

It really is this easy

This simple example shows you how easy it is to define a SQL Agent Job for SQL Server; it also outlines the basics involved in defining the Jobs. I bet that about 90 percent of the Jobs you'll ever define will be simple ones that involve only one Job step and one schedule.

Talkback

Develop an SQL Server Job from scratch

I initially thought that this is creating jobs from scratch without the use of the SSA.
Do you know if it's possible to create and schedule jobs if SSA is not enabled/intalled?

Elsa Evaner May 14, 2009

Develop an SQL Server Job from scratch

Very good article for newbie's like me :)

Srinath February 25, 2010
Add your opinion

In order to post a comment, you need to be registered. (Sign In or register below)

Post your comment

ZDNet Asia Live

Mac users' indifference toward security 'worrying' http://t.co/MBTwqilk

RT @Bilafer: 25% of top VC firms investing in China, India or both. Good news for innovation, #SAPAPJ http://t.co/wkCXKkxU

Mac users' indifference toward security 'worrying' http://t.co/AkSlHrCH #cyber #infosec

RT @zdnetasia: Gartner: Mobile CRM gives better ROI than social. http://t.co/nTgj44H8

China hits back at Pentagon report on spy claims. http://t.co/CccR4SBM

China hits back at Pentagon report on spy claims http://t.co/YP380BYQ http://t.co/erFX4aVv #arcavir

http://t.co/VNaZtseV China hits back at Pentagon report on spy claims: Annual report by Pent... http://t.co/TvgCi5RE http://t.co/wiqY9ktt

#AntiVirus News: Mac users' indifference toward security 'worrying' http://t.co/spWS0CpU #AdAware

Mac users' indifference toward security 'worrying' http://t.co/BtVn1BAk
> expected! They still remember Mac vs PC ads
#infosec #news #apple

Pentagon report says China exploit US tech, conduct cyberespionage, China says it has been "unjustly criticized" http://t.co/P5wgqy6I #in

Mac users' indifference toward security 'worrying': 59 Jakarta 10350, Indonesia In light of the recent spate of ... http://t.co/Lxgnc1wM

Pakistan lifts block on Twitter - ZDNet Asia: Pakistan lifts block on TwitterZDNet Asia59 Jakarta 10350, Indones... http://t.co/61n85ajh

Pakistan lifts block on Twitter http://t.co/WHqoJOqm http://t.co/erFX4aVv #arcavir

http://t.co/VNaZtseV Pakistan lifts block on Twitter: Country restores access after briefly ... http://t.co/5gqegFWK http://t.co/wiqY9ktt

Pakistan lifts block on Twitter. http://t.co/y0arswpE

I reckon your view: "CRM is strategy, not software", if a company replicating the approach uses in ERP implementation into CRM, what they...

3 hours ago by wykoong on Gartner: Mobile CRM gives better ROI than social

This video will teach you about the Excel fill handle but also provide you with a workook to download... http://www.youtube.com/watch?v=...

20 hours ago by TradeBrother on A quick fill handle trick for Microsoft Excel

waiting...

2 days ago by eapete on What should count in a company's market value?

Boy, you've opened a can of worms now.

Wait for the rants & raves.

2 days ago by eapete on What should count in a company's market value?

I was puzzling before this whether to replicate the success formula we executed for a financial institute, and come out with a standard s...

3 days ago by wykoong on Drop the egos, copy ideas, then innovate