Professional Documents
Culture Documents
CHAPTER 10
233
Job Steps
Job steps are the execution elements within a job. The types of job steps that can be executed are: Transact-SQL (T-SQL) Replication tasks Operating system tasks or executable les Analysis Services tasks Integration Services packages ActiveX scripts Like any executable code, each job step runs under a security context. The default security context for a job step corresponds to the login that is set as the owner of the job. You can also override the security context by specifying a proxy account that the SQL Server Agent uses for the job step based on credentials assigned to the proxy account. In addition to the commands to execute, a job step can be congured with: Logging Notication to an operator Retry settings that specify the number of times to retry a step as well as the number of minutes between retries Control ow logic
234
CHAPTER 10
The control ow options allow you to specify an action based on either success or failure as follows: Quit job reporting success Quit job reporting failure Go to next step Go to a specic step number Logging can be directed to a le that is overwritten each time the step executes or you can append to an existing le. You can also log step output to a table, although this is not generally recommended due to the extra overhead of logging to a table versus logging to a text le.
BEST PRACTICE E
Every job step that you create should be congured to log to a le. The most common way to congure logging is to create a new log le in the rst step of a job, and then each subsequent job step appends information to the log le.
Job Schedules
After you have added one or more steps to your job, you are ready to specify a schedule. Schedules are dened and stored as independent objects, allowing you to dene a single schedule that can be applied to multiple jobs. A job schedule can be created through either the Manage Schedules dialog box or during the creation of a job. Some of the properties that you can set for a schedule are: Frequency type; for example, daily, weekly, or monthly Recurrence within a daily, weekly, or monthly recurrence; for example every third day of every second month for a monthly frequency type Recurrence within a day on a minute or hourly basis Start and stop times Start and end date for the schedule to be valid For example, you could create a schedule to execute the rst Monday of every third month and then every 15 minutes between the hours of 3:00 A.M. and 7:00 P.M.
Job History
When a job is executed, any errors or messages are sent to the log le or table that is specied for each step, allowing you to review the log le in the event of a job execution error.
CHAPTER 10
235
In addition to any logging congured for a job step, each time a job executes, SQL Server logs information into the dbo.sysjobhistory table in the msdb database for each job step that is executed within the job. Some of the information that is recorded is: Job step Status Execution date and time Duration If an error occurs, the number, severity, and text of the last error message generated
EXAM TIP
You need to know where to nd information to diagnose the cause of an error in a job step.
Operators
An operator is an alias for a person, group, or device. Operators are used to send notications when jobs fail or an alert is generated. For each operator, you specify a name along with contact information such as an e-mail address, pager number, or NET SEND address. In addition, you can designate which day(s) and operator(s) are available and the start and end time of a workday.
NOTE E
The start and end time of a workday is based on the U.S. standard workweek of Monday Friday and does not accommodate any other workweek denition.
Q Quick Check
1 . If a job fails, where can you look to diagnose the problem? 2. What types of job steps can be executed?
2. You can create jobs that execute T-SQL, ActiveX scripts, operating system
commands, or executable les. You can also congure specic tasks for replication, Analysis Services, and Integration Services.
236
CHAPTER 10
PR ACTICE
In these practices, you dene an operator for SQL Server to notify. You also create a job to reindex the AdventureWorks database.
PR ACTICE 1
Create an Operator
In this practice, you create an operator that will be subsequently used to send notications for jobs and alerts.
1. 2.
In SQL Server Management Studio, expand the SQL Server Agent node, right-click Operators, and select New Operator. Give the operator a name and specify an e-mail address, as shown here.
3.
PR ACTICE 2
Create a Job
Execute the following code in the AdventureWorks database to create a stored procedure to reindex tables:
CREATE PROCEDURE dbo.asp_reindex @database SYSNAME, @fragpercent INT AS DECLARE @cmd @table @schema NVARCHAR(max), SYSNAME, SYSNAME
CHAPTER 10
237
--Using a cursor for demonstration purposes. --Could also do this with a table variable and a WHILE loop DECLARE curtable CURSOR FOR SELECT DISTINCT OBJECT_SCHEMA_NAME(object_id, database_id) SchemaName, OBJECT_NAME(object_id,database_id) TableName FROM sys.dm_db_index_physical_stats (DB_ID(@database),NULL,NULL,NULL,'SAMPLED') WHERE avg_fragmentation_in_percent >= @fragpercent FOR READ ONLY OPEN curtable FETCH curtable INTO @schema, @table WHILE @@FETCH_STATUS = 0 BEGIN SET @cmd = 'ALTER INDEX ALL ON ' + @database + '.' + @schema + '.' + @table + ' REBUILD WITH (ONLINE = ON)' --Try ONLINE build first, if failure, change to OFFLINE build. BEGIN TRY EXEC sp_executesql @cmd END TRY BEGIN CATCH BEGIN SET @cmd = 'ALTER INDEX ALL ON ' + @database + '.' + @schema + '.' + @table + ' REBUILD WITH (ONLINE = OFF)' EXEC sp_executesql @cmd END END CATCH FETCH curtable INTO @schema, @table END CLOSE curtable DEALLOCATE curtable GO
2. 3.
Below SQL Server Agent, right-click the Jobs node and select New Job. Give your new job a name, set the owner to sa, select Database Maintenance for the job category, and add a description, as shown here.
238
CHAPTER 10
4. 5.
Select the Steps page and click New to open the New Job Step dialog box. Specify a name for the step, select Transact-SQL for the step type, leave Run As blank, enter the Database name as AdventureWorks, and enter the SQL command shown here for the reindex procedure you created in the previous practice.
CHAPTER 10
239
6. 7.
Select the Advanced page and specify an output le of C:\Test\Dailymaintenance.txt to log to. Click OK. Select the Schedules page and click New to dene a new daily schedule, as shown here, and click OK to close the New Job Schedule dialog box.
8. 9.
Click OK to save the new job and close the New Job dialog box. Expand Jobs. Right-click the Re-index Databases job and select Start. Upon completion of the job, review the job execution history and the logging le.
Lesson Summary
An operator is an alias for a person, group, or device to which you want to be the target of notications. A job can be created that contains multiple steps with control ow dependency, logging, and one or more schedules.
Lesson Review
The following question is intended to reinforce key information presented in Lesson 1, Creating Jobs. The question is also available on the companion CD if you prefer to review it in electronic form.
240
CHAPTER 10
NOTE E
ANSWERS
Answers to this question and an explanation of why each answer choice is correct or incorrect is located in the Answers section at the end of the book.
1.
Where would you look to retrieve a list of jobs that have failed?
A. The Windows event log B. The job history in SSMS C. The SQL Server Agent error log D. The SQL Server error log
CHAPTER 10
241
242
CHAPTER 10
By specifying a job to execute when an alert is raised, you can congure your environment to trap and attempt to x errors on an automated basis, eliminating the need for an administrator to respond to routine events.
EXAM TIP
You need to know the types of alerts that can be dened in SQL Server and the response criteria that can be specied for an alert.
Q Quick Check
1 . What are the three types of alerts that can be created? 2. What are the two response actions that can be congured for an alert?
2. You can have an alert send a notication or execute a job in response to the alert
condition.
PR ACTICE
Creating Alerts
In this practice, you create alerts to send notications when you are running out of transaction log space and when a Level 22 error occurs.
PR ACTICE 1
In this practice, you create an alert to send a notication when the percentage of the transaction log space used for the AdventureWorks database exceeds 90 percent.
1. 2. 3.
In SQL Server Management Studio, below SQL Server Agent, right-click Alerts and select New Alert. Give your alert a name, and from the Type drop-down list, select SQL Server Performance Condition Alert. From the Object drop-down list, select the SQLServer:Databases object. From the Counter drop-down list, select Percent Log Used. Select the AdventureWorks instance from the Instance drop-down list, and set the alert for when the counter rises above 90 by selecting Rises Above from the Alert If Counter drop-down list and entering 90 into the Value text box.
CHAPTER 10
243
4. 5.
Select the Response page, select the Notify Operators check box, and select the check boxes for the notication options for your operator. Select the Options page and select the E-mail check box to include the alert error text. Click OK.
PR ACTICE 2
Right-click Alerts and select New Alert. Give your alert a name by entering it into the Name text box, and select SQL Server Event Alert from the Type drop-down list. Specify All Databases and an error severity of 22, as shown here. Select the Response page, select the Notify Operators check box, and select the notication options for your operator. Select the Options page and select the E-mail check box to include the alert error text. Click OK.
244
CHAPTER 10
Lesson Summary
Alerts enable you to notify operators as well as execute jobs to x problems when an event occurs.
Lesson Review
The following question is intended to reinforce key information presented in Lesson 2, Creating Alerts. The question is also available on the companion CD if you prefer to review it in electronic form.
NOTE E
ANSWERS
Answers to this question and an explanation of why each answer choice is correct or incorrect is located in the Answers section at the end of the book.
1.
Your Orders database crashed last night, and you have determined that the crash was caused by a data le running out of space. What tool do you use to send a notication to an administrator as well as expand the data le before it runs out of space?
A. SQL Server Agent B. System Monitor C. Event Viewer D. Network Monitor
Lesson 2: Creating Alerts CHAPTER 10 245
Chapter Review
To practice and reinforce the skills you learned in this chapter further, you can perform the following tasks: Review the chapter summary. Review the list of key terms introduced in this chapter. Complete the case scenario. This scenario sets up a real-world situation involving the topics in this chapter and asks you to create a solution. Complete the suggested practices. Take a practice test.
Chapter Summary
SQL Server Agent provides a scheduling engine that can be used to execute jobs. Jobs can have one or more steps with basic control ow dependencies, logging, notication, and one or more execution schedules. Operators are used to encapsulate the settings used to send a notication to a person, group, or device.
Key Terms
Do you know what these key terms mean? You can check your answers by looking up the terms in the glossary at the end of the book. Alert Job step Operator
Case Scenario
In the following case scenario, you apply what youve learned in this chapter. You can nd answers to these questions in the Answers section at the end of this book.
Company Overview Coho Vineyard was founded in 1947 as a local, family-run winery. Due to the award-winning wines it has produced over the last several decades, Coho Vineyards has experienced signicant growth. To continue expanding, several existing wineries were acquired over the years. Today, the company owns 16 wineries; 9 wineries are in Washington, Oregon, and
246
CHAPTER 10
California, and the remaining 7 wineries are located in Wisconsin and Michigan. The wineries employ 532 people, 162 of whom work in the central ofce that houses servers critical to the business. The company has 122 salespeople who travel around the world and need access to up-to-date inventory availability. Planned Changes Until now, each of the 16 wineries owned by Coho Vineyard has run a separate Web site locally on the premises. Coho Vineyard wants to consolidate the Web presence of these wineries so that Web visitors can purchase products from all 16 wineries from a single online store. All data associated with this Web site will be stored in databases in the central ofce. When the data is consolidated at the central ofce, merge replication will be used to deliver data to the salespeople as well as to allow them to enter orders. To meet the needs of the salespeople until the consolidation project is completed, inventory data at each winery is sent to the central ofce at the end of each day.
EXISTING DATA ENVIRONMENT
Databases Each winery presently maintains its own database to store all business information. At the end of each month, this information is brought to the central ofce and transferred into the databases, shown in Table 10-1.
TABLE 10-1 Coho Vineyard Databases
DATABASE
SIZE
After the database consolidation project is complete, a new database named Order will serve as a data store to the new Web store. As part of their daily work, employees also will connect periodically to the Order database using a new in-house Web application. The HR database contains sensitive data and is protected using Transparent Data Encryption (TDE). In addition, data in the Salary table is encrypted using a certicate.
Database Servers A single server named DB1 contains all the databases at the central ofce. DB1 is running SQL Server 2008 Enterprise on Windows Server 2003, Enterprise edition.
Chapter Review
CHAPTER 10
247
Business Requirements
You need to design an archiving solution for the Customer and Order databases. Your archival strategy should allow the Customer data to be saved for six years. To prepare the Order database for archiving procedures, you create a partitioned table named Order.Sales. Order.Sales includes two partitions. Partition 1 includes sales activity for the current month. Partition 2 is used to store sales activity for the previous month. Orders placed before the previous month should be moved to another partitioned table named Order. Archive. Partition 1 of Order.Archive includes all archived data. Partition 2 remains empty. A process needs to be created to load the inventory data from each of the 16 wineries by 4 A.M. daily. Four large customers submit orders using Coho Vineyards Extensible Markup Language (XML) schema for Electronic Data Interchange (EDI) transactions. The EDI les arrive by 5 P.M. and need to be parsed and loaded into the Customer, Accounting, and Inventory databases, which each contain tables relevant to placing an order. The EDI import routine is currently a single-threaded C++ application that takes between three and six hours to process the les. You need to nish the EDI process by 5:30 P.M. to meet your Service Level Agreement (SLA) with the customers. After the consolidation project has nished, the EDI routine loads all data into the new Order database. You need to back up all databases at all locations. You can lose a maximum of ve minutes of data under a worst-case scenario. The Customer, Account, Inventory, Promotions, and Order databases can be off-line for a maximum of 20 minutes in the event of a disaster. Data older than six months in the Customer and Order databases can be off-line for up to 12 hours in the event of a disaster. Answer the following question.
1.
What would you congure to ensure that administrative processes were automated?
Suggested Practices
To help you master the exam objectives presented in this chapter, complete the following tasks.
Create Jobs
Practice
Create jobs to execute full, differential, and transaction log backups within your environment.
Create Alerts
Practice Create an alert that is raised when the disk drive that your data les is on has less than 15 percent free space available.
248
CHAPTER 10
PRACTICE TESTS
For details about all the practice test options available, see the section entitled How to Use the Practice Tests, in the Introduction to this book.
CHAPTER 10
249