Wednesday 27 February 2013

how to schedule a job in sql server 2008 step by step


SQL Server Agent is at the heart of automating maintenance tasks. There are several things available in SQL Server Agent that can assist you with routine automation and preventative maintenance. You can create operators that will receive notification for certain events. You can define alerts that will capture certain events, and SQL Server Agent can then perform predefined actions in response to those events. You can create jobs that SQL Server Agent can run on a predefined schedule to perform routine preventative maintenance tasks. You can even create a master server in SQL Server Agent so you can manage jobs on multiple target servers from a single server.

1. Operators

The first thing you need to do is define an operator so you can receive automatic notifications through SQL Server Agent. An operator consists of two basic pieces of information: a name used to identify the operator and the contact information used to notify the operator. To add an operator using SQL Server Management Studio, expand SQL Server Agent in the Object Explorer, right-click the Operators folder, and select New Operator from the context menu. This will open the New Operator dialog box shown inFigure 1.
Figure 1. New Operator dialog box

Enter an operator name and email address, and click OK. Although you can configure net send and pager information, these options are deprecated and will be removed in a future version of SQL Server, so you should avoid using them. The only information you should enter here is the name of the operator and the email address that you will use to receive event notifications.
You can also add an operator using the sp_add_operator procedure located in the msdb. The following statement adds an operator named DBA Support and supplies an email address as the contact information.
EXEC msdb.dbo.sp_add_operator
     @name='DBA Support',
     @email_address='DBASupport@somecompany.com'

2. Enabling SQL Server Agent Notifications

You have to enable the alert system in SQL Server Agent before you can start receiving notifications. Once you have configured Database Mail and added an operator, the next thing you should do is enable the alert system and designate a fail-safe operator. This is a designated operator that will receive notifications in the event that the primary operator is unreachable. In SQL Server Management Studio, right-click SQL Server Agent and select properties from the context menu. This will bring up the SQL Server Agent Properties dialog box. Select the Alert System page, as shown in Figure 2.
Figure 2. SQL Server Agent Properties dialog box Alert System page

There are only a few settings on this page you need to configure. Under the Mail Session section, select Enable Mail Profile. This will allow you to select the mail system and profile that SQL Server Agent will use to send notifications. You should select Database Mail from the Mail System drop-down list. SQL Mail is the other available mail system option; however, you should avoid SQL Mail because it will be removed in a future release. Now select the profile SQL Server Agent will use to send alert notifications from the Mail Profile drop-down list. 
The next thing you need to do is select Enable Fail-Safe Operator under the Fail-Safe Operator section. Now you can select the operator from the drop-down list that you want to receive notifications in case the designated operator is unreachable. SQL Server stores the fail-safe operator information in the registry in case the operator tables in the msdb are unavailable. We are using an operator called DBA Support, as shown in Figure 13-10. You should then select the E-mail check box to specify that the fail-safe operator will receive notifications using email. Remember, you should avoid the Pager and Net Send options, since they will no longer be supported in a future release.
Select OK to close the SQL Server Agent Properties dialog box. You must restart SQL Server Agent before the new settings will take effect. You are now ready to start receiving automatic notifications from SQL Server Agent alerts and jobs.

3. Alerts

A SQL Server Agent alert is an automatic response to a predefined event. You can configure SQL Server Agent alerts to fire in response to SQL Server events, SQL Server performance counters, and Windows Management Instrumentation (WMI) events. Once an event has caused an alert to fire, you can respond to the alert by notifying operators of the event or even running a job after the event has occurred.
So, what kind of alerts should you have in place that will lead to proactive maintenance? At the very minimum, you should have a separate alert configured for fatal errors, which are indicated by severity codes 19 through 25. Let's walk through an example of creating an alert that will notify you of any fatal errors encountered with the severity of 19 called "Fatal Error in Resource." To add an alert using SQL Server Management Studio, expand SQL Server Agent in the Object Explorer, right-click the Alerts folder, and select New Alert from the context menu. This will open the New Alert dialog box shown in Figure 3.
Figure 3. New Alert dialog box General page

Give the alert a descriptive name and make sure the Enable check box is selected. We will call this alert "Fatal Error in Resource." Select SQL Server Event Alert from the Type dropdown list. The Event Alert Definition section will change depending on the type of alert you have selected. You can limit the alert to a specific database by selecting it from the Database name drop-down list; for this example, you should select <all databases>. We want to monitor errors with a severity of 19, so select the Severity option to enable the drop-down list, and then select 019 - Fatal Error in Resource. Select the Response page, as shown in Figure 4, to define the action that SQL Server Agent will perform when the event occurs.
Figure 4. New Alert dialog box Response page

The Response page allows you to perform two actions in response to an event: execute a job and notify an operator of the event. You can select an existing job to run from the Execute Job drop-down list, or select the New Job button to open the New Job dialog box and create a new job. If you choose a job from the drop-down list and select the View Job button, SQL Server will display the Job Properties dialog box that will allow you to view and edit an existing job.
All of the existing operators are displayed in the Operator List area. Check the E-mail column for each operator you would like to receive a notification email when the alert is triggered. Remember, the Pager and Net Send options are deprecated, so you should avoid these two options. You can select the New Operator button to open the New Operator dialog box, or select the View Operator button to open the Operator Properties dialog box for the selected operator. We have chosen to notify the DBA Supportoperator we created in the previous "Operators" section. Select the Options page, as shown in Figure 5, to make the final configurations to the new alert.
Figure 5. New Alert dialog box Options page

Select the E-mail check box at the top of the Options page so the error text for the event will be included in the email that the operator receives. The Additional Notification Message to Send text box will allow you to send further information or instructions along with the error text to the operator. You can use the Delay Between Responses section to suspend additional responses for the alert for a specified amount of time. Adding a delay between responses is useful for error messages that may occur in rapid succession; nobody wants to receive a hundred emails in five minutes. Click OK to close the New Alert dialog box and create the alert.
You can repeat this process for each alert you want to create on every SQL Server instance, or you can create a T-SQL script you can quickly run on all of your SQL Server instances. The code in Listing 1 will generate the same alert we just created for severity 19 using SQL Server Management Studio.
Example 1. Code to Create an Alert for Severity 19 Messages
USE msdb
GO
EXEC msdb.dbo.sp_add_alert
    @name=N'Fatal Error in Resource',
    @message_id=0,
    @severity=19,
    @enabled=1,
    @delay_between_responses=0,
    @include_event_description_in=1,
    @notification_message=N'This is a Fatal Alert. Please review immediately.'
GO

EXEC msdb.dbo.sp_add_notification
    @alert_name=N'Fatal Error in Resource',
    @operator_name=N'DBA Support',
    @notification_method = 1
GO

       

You can also define an alert for a specific error number, regardless of the severity, by entering the exact error number. We have seen some specific blog entries around the need to create an alert for error 825, which deals with an IO issue. You can read more on error 825 on Paul Randal's blog located athttp://sqlskills.com/BLOGS/PAUL/post/A-little-known-signof-impending-doom-error-825.aspx.
For a complete list of messages and their severity codes, you can query the sys.messages catalog view. There are far too many messages in the sys.messages catalog view to review each one manually. You can narrow down the messages by limiting the results by language and only showing the messages that SQL Server will log. You can also limit the results to messages with a severity of less than 19, as shown in the following query, since you should already be monitoring messages with a severity of 19 and above. You can review the list returned by the following query to determine if you want to add additional alerts for specific errors.
SELECT *
FROM sys.messages
WHERE language_id = 1033 and
            is_event_logged = 1 and
            severity < 19

SQL Server Agent jobs make it possible for you to perform routine scheduled maintenance on your SQL Server instances. A job is made up of a series of steps or actions that work together to perform a task. You can place each job in a category to group tasks that are similar in nature. For example, you can use the Database Maintenance category to group all of your maintenance jobs. You can execute a job using a predefined schedule or by using the sp_start_job stored procedure in the msdb. SQL Server Agent can notify an operator when a job fails, when a job succeeds, or any time a job completes.
Right-click the Jobs folder under SQL Server Agent and select New Job from the context menu to open the New Job dialog box, as shown in Figure 6.
Figure 6. New Job dialog box General page

Give the job a descriptive name, such as Cleanup Mail History. Select Database Maintenance from the Category drop-down list. If you do not have a Database Maintenance category or you want to create a new category, you can right-click the Jobs folder and select Manage Job Categories from the context menu. Provide a brief description, such as Database maintenance job used to purge mail history older than 30 days from the msdb. If Enabled is unchecked, the job will not run during the scheduled time; however, you can still execute the job using the sp_start_job stored procedure. A disabled job will also run if it is executed in response to an alert. Select the Steps page, as shown in Figure 7, to define the steps the job will perform.
Figure 7. New Job dialog box Steps page

You can use the Steps page to add, edit, and delete job steps, move the order of the steps, and set the start step for the job. Select the New button to display the New Job Step dialog box shown in Figure 8.
Figure 8. New Job Step dialog box General page

Give the job step a descriptive name, such as Delete Mail History. You can create job steps to execute many different actions, such as the following:
  • Operating system commands
  • Transact-SQL scripts
  • PowerShell scripts
  • ActiveX scripts
  • Replication tasks
  • Analysis Services tasks
  • Integration Services packages
ActiveX scripts will be removed from SQL Server Agent in a future version of SQL Server. Therefore, you should avoid using ActiveX scripts in any new jobs.

Since we are executing a SQL script, select Transact-SQL Script (T-SQL) from the Type drop-down list. The Run As drop-down list in the General page does not apply to T-SQL scripts; it only applies to other step types that interact with the OS, such as PowerShell scripts and CmdExec. The Run As option here is for designating a proxy account to run the job step. (We will discuss proxy accounts more in the next section.) Actually, if you change Type selection to something other than T-SQL, and then change it back to T-SQL, the Run As option will be disabled.
Change the Database option to msdb, since that is where the Database Mail cleanup stored procedures are located. Enter the following script in the Command text box. Select the Advanced page, as shown in Figure 9, to configure the remaining options for the job step.
DECLARE @BeforeDate DateTime =
                      (Select DATEADD(d,-30, GETDATE()))

EXEC sysmail_delete_mailitems_sp
           @sent_before = @BeforeDate

EXEC sysmail_delete_log_sp
           @logged_before = @BeforeDate

Figure 9. New Job Step dialog box Advanced page

You can use the Advanced page to define options for the job step, such as completion actions and logging. You can use the On Success Action and On Failure Action lists to quit the job reporting success, quit the job reporting failure, go to the next step, or to select a specific step that you would like to run next as a result of the action. You can use the Retry Attempts and Retry Interval options to set the number of times SQL Server Agent will try to run the steps and how long it will wait between retry attempts before it considers the step a failure. We have set our job step to retry one time 15 minutes after the initial failure. It is important to specify an output file to log the messages returned by the job step. Output files are a tremendous help when troubleshooting issues related to the job failures. The Run As User option in the Advanced page is only applicable for T-SQL scripts. If you create a step that is anything other than T-SQL, the option will not be displayed. The account specified here is the SQL Server account used by SQL Server Agent to execute the job step. Only users with sysadmin rights can set the Run As User option and create output files. Click OK to add the new step to the job.
You can use the Schedules page of the New Job dialog to pick an existing schedule or create a new schedule for the job. Click the Schedules page and select New to open the New Job Schedule dialog box shown in Figure 10.
Figure 10. New Job Schedule dialog box

Give the new schedule a descriptive name, such as Midnight Every Sunday. The options are pretty self-explanatory. Select the appropriate schedule for the new job. You will see a Summary area at the bottom that you can use to validate the choices you have made. As indicated by the name, we have created a schedule to run every Sunday at 12:00 AM. Select OK to add the job to the new schedule.
You can use the Alerts page to create a new alert that will execute the job in response to an event. Since we do not need to clean up Database Mail for an alert, skip this page and select Notifications, as shown in Figure 11.
Figure 11. New Job dialog box Notifications page

You can use the Notifications page to specify the actions SQL Server Agent will perform when the job completes. All of the drop-down lists on this page have the same three options: When the Job Fails, When the Job Succeeds, and When the Job Completes. You can use these options to notify an operator, write to the Windows Application event log, and automatically delete the job. In our case, we want to email the DBA Support operator when the job fails. Click OK to create the new Job.
You only need to worry about the Targets page if you are using master and target servers within SQL Server Agent. SQL Server Agent allows you to designate a SQL Server instance as a master (MSX) server and push jobs to target (TSX) servers. The Targets page allows you to define whether the job will be defined locally or if you will be targeting multiple servers. The jobs on the target servers are read-only and cannot be deleted. In order to set up a MSX server and enlist TSX servers, you can right click on SQL Server Agent, select Multi-Server Administration, and then select Make This a Master. This will start the Master Sever Wizard that will guide you through the process. For more information on master and target servers, search for "Creating a Multiserver Environment" in SQL Server Books Online.

5. Proxies

You can create a proxy account that allows SQL Server Agent to execute a job step that runs under the credentials of a specified Windows user account. You can use a proxy account to access subsystems external to SQL Server using Windows credentials; therefore, you cannot use a proxy account for a T-SQL job step, since T-SQL is an internal operation. In order to create a proxy account, you must first create a credential that maps to a Windows user account. To open the New Credential dialog box shown in Figure 12, expand the Security node in SQL Server Management Studio, right-click the Credentials folder, and select New Credential from the context menu.
Figure 12. New Credential dialog box

Enter a descriptive name for the credential. We named ours Ken_Credential, since that is the Windows account we are using. Enter a valid Windows user account in the Identity field. You can select the ellipsis next to the Identity field to display the Select User or Group dialog box, which will allow you to search for and verify Windows user accounts. Enter the password for the Windows user account and select OK to create the new credential. You may also choose to verify the Windows user account by an Extensible Key Management provider if you have one installed on the server.
Now that you have created a credential, you are ready to create a new proxy. Expand SQL Server Agent, right-click the Proxies folder, and select New Proxy from the context menu. This will display the New Proxy Account dialog box shown in Figure 13.
Figure 13. New Proxy Account dialog box General page

Give the new proxy account a descriptive name; we called ours Ken_Proxy. Now, enter the name of the credential created earlier in this section. You can also select the ellipsis next to the Credential Name text box to search for the credential. Enter a description for the new proxy account, such asProxy used to execute Operating System and PowerShell scripts. Select the subsystems the new proxy account will use. We have selected Operating System (CmdExec) and PowerShell. Select the Principals page, as shown in Figure 14, to manage the principals that can use the new proxy account in job steps.
Figure 14. New Proxy Account dialog box Principals page

Select the Add button to assign SQL Server logins or roles to the proxy account. Members of the sysadmin role have access to all proxy accounts, so you do not need to add them on the Principals page. Click OK to create the new proxy account.
The proxy account is now an available option in the Run As drop-down list on the General page of the New Job Step dialog box. The proxy account is only available in the Run As list if you select Operating System (CmdExec) or PowerShell as the step type, since they are the only two subsystems we allowed the proxy account to use.

No comments:

Post a Comment