To make sure the agent is logging on with a domain account, you should open theServices applet in Control Panel if you are using Windows 2000, you will find it inAdministrative Tools und
Trang 113 Click OK on the message that informs you of success and then click Close on
the Log Detail screen to complete the Wizard
The Copy Database Wizard is a simple tool that makes a complex task much easier
There are four types of backups to help you thwart the evils that would claim yourdata First, there is the full backup, the basis of all other backups, which makes a copy
of the entire database Next, the differential backup grabs all of the changes made to
Trang 2the database since the last full backup The transaction log backup came next and isvery useful for quick backup strategy, point-in-time restores, and clearing the transac-tion log on a periodic basis Finally, there is the filegroup backup, used to make back-ups of small chunks of very large databases.
After a discussion of backups, we hashed out the fine points of index maintenance
It is very important to keep your indexes up to snuff so that data access will always befast To keep them in top shape, use DBCC SHOWCONTIG to determine fragmenta-tion and then use CREATE INDEX with the DROP_EXISTING option or DBCCDBREINDEX to reconstruct fragmented indexes
After that, we looked at the importance of monitoring the SQL Server event logs aswell as the mechanics of doing so Finally, we discussed the Copy Database Wizard
Now that you know that you need to perform all of these tasks, probably on anightly or weekly basis, wouldn’t it be nice if you could have someone else do it foryou? In the next chapter, we’ll discuss automation; you will learn how to make SQLServer do a lot of your work for you, including backups
Trang 4CHAPTER 17
Automating Administration
F E A T U R I N G : Automation Basics 625 Configuring Mail Support 627 Creating Operators 629
Creating Alerts 647 Using the Database Maintenance
Working with SQL Mail 671
Trang 5T hroughout this book, we have discussed administrative activities that would
best be performed during off-hours These activities include backing up bases, creating large databases, reconstructing indexes—the list goes on.Most of these activities will need to be performed on a regular basis, not justonce For example, you will need to back up at frequent intervals Because mostadministrators would rather not need to stand at the SQL Server to start the task inquestion, SQL Server has the built-in capability to automate tasks
data-The first thing we need to discuss is the basics of how automation works in SQLServer We’ll explain some of the basic concepts of automation and how theSQLServerAgent service plays a part
After we discuss the basics of automation, we will need to set up and configure e-mail support, because SQL Server is capable of sending you e-mail when there is aproblem as long as e-mail is configured properly Not only that, but SQL Server canreceive and process queries via e-mail, and send the result set back in an e-mail to thesender However, all of this can be done only when e-mail is configured
Next we will configure operators An operator is a person who is able to receivemessages from SQL Server via e-mail, pager, or Net Send Configuring an operator tellsSQL Server whom to contact and when they are available
After we have operators in place, we can start creating jobs, the heart of tion Jobs are the activities that you need to administer, such as database backups orindex reconstruction We will discuss each part of a job, the steps required to com-plete the job, and the schedules that tell SQL Server when to run the job We will also
automa-go over the process of creating multiserver jobs, which can be created on one serverand run on multiple servers over a network
Next we will configure alerts, which are used to warn you of problems or eventsthat have occurred on the server Not only will we discuss how to configure standardSQL Server alerts, but we will discuss the methods for creating your own user-definedalerts to cover any possible event that may occur on your server
After all of this, we will discuss the Database Maintenance Wizard This specialWizard is designed to automate all of the standard database maintenance proceduressuch as backups, index reconstruction, transaction log backup, etc
Finally, we will discuss the uses and configuration of SQL Mail Using this tool, youcan e-mail a query to SQL Server and have it respond with a result set via e-mail Thistool can potentially save you a lot of time and effort with reporting when used properly.We’ll start this chapter with a discussion of the basics of automation
Trang 6Automation Basics
Nearly any administrative task you can think of can be automated through SQLServer True, that may sound like an exaggeration, but look at the things that you canautomate:
• Any Transact-SQL code
• Scripting languages such as VBScript or JavaScript
• Operating system commands
• Replication tasks (which we’ll learn about in Chapter 27) Some popular tasks to automate using this functionality are as follows:
At the very heart of SQL Server’s automation capability is the SQLServerAgent
ser-vice (also referred to as the agent) In fact, automation and replication are the sole
functions of that service This service uses three subcomponents to accomplish itsautomation tasks: alerts, operators, and jobs
Alerts: An alert is an error message or event that occurs in SQL Server and is
recorded in the Windows NT Application log Alerts can be sent to users via e-mail, pager, or Net Send If an error message is not written to the Windows NTapplication log, an alert will never be fired off
Operators: When an alert is fired, it can be sent to a user Users who need to
receive these messages are known in SQL Server as operators Operators are used
to configure who will receive alerts and when they are available to receive thesemessages
Jobs: A job is a series of steps that define the task to be automated It also
defines schedules, which dictate when the task is to be executed Such tasks can
be run only one time or on a recurring basis
Trang 7These three components work together to complete the tapestry of administration.Here is an example of what may happen:
1 A user may define a job that is specified to run at a certain time.
2 When the job runs, it fails and thus writes an error message to the Windows NT
event log
3 When the SQLServerAgent service reads the Windows NT event log, the agent
finds the error message that the failed job wrote and compares that to thesysalerts table in the MSDB database
4 When the agent finds a match, it fires an alert.
5 The alert, when fired, can send an e-mail, pager message, or Net Send message
to an operator
6 The alert can also be configured to run another job, designed to repair the
prob-lem that caused the alert
For any of this to function, though, the SQLServerAgent service must be properlyconfigured To start, the agent must be running for automation to work There arethree ways to verify this: First, you can open Enterprise Manager, expand Manage-ment, and notice the SQL Server Agent icon—if it is a red square, the service isstopped; if it is a green arrow, the service is started You can even start the service byright-clicking the icon and selecting Start Other methods of checking and changingthe state of the service are by using the Service Manager (which can be found in thetask tray of the Start bar) or by using the Services applet in the Control Panel
Not only should the agent be running, but it is best to have it log on with adomain account as opposed to a local system account, because using the local systemaccount will not allow you to work with other SQL Servers on your network Thismeans that you will not be able to perform multiserver jobs (discussed later in thischapter), replication (discussed in Chapter 27), or use SQL Server’s e-mail capabilities
To make sure the agent is logging on with a domain account, you should open theServices applet in Control Panel (if you are using Windows 2000, you will find it inAdministrative Tools under Programs on the Start menu), double-click the SQLServer-Agent service, and select a domain account by clicking the ellipsis box next to ThisAccount
Once all of this is in place, you are nearly ready to begin working with automation.First, you should configure SQL Server to be able to send and receive e-mail
Trang 8Configuring Mail Support
The services that comprise SQL Server can send and receive e-mail Specifically, theSQLServerAgent service works with SQLAgentMail, which the agent uses to send e-mail to administrators when an alert has fired The MSSQLServer service works withSQL Mail, which the service uses to receive queries from users and reply with a resultset; it is a lot like executing a query through Query Analyzer, only via e-mail
To configure either of these types of mail, you must have a mail account where Exchange works best because both Exchange and SQL Server are parts of theMicrosoft BackOffice family, but it is also possible to use an Internet e-mail account
some-The first step in making this work is to create a mailbox on the e-mail server towhich you will be connecting If you are using Microsoft Exchange 5.5, this is whatyou do:
1 Open the Exchange Administrator from the Microsoft Exchange 5.5 group
under Programs on the Start menu
2 From the File menu, select New User.
3 Select the user account that the SQL Server services use to log on as the Primary
Account for the mailbox
4 Fill in the remaining information as appropriate.
If you are using Exchange 2000:
1 Open up Active Directory Users and Computers.
2 Right-click the account that the SQL Server services use to log on and select
Exchange Tasks
3 Follow the steps in the subsequent Wizard to Mail-Enable the account.
Once you have a mailbox on the server, you need to install Microsoft Outlook sothat the server can make a MAPI connection to the server with which it will be work-ing The process of installing Outlook is a little outside the scope of this book, but it is
a relatively easy process driven by a Wizard
After Outlook has been successfully installed, you need to create a mail profile forthe SQL Server account:
1 Log on to the SQL Server as the SQL Server services account.
2 Open Outlook.
3 Outlook will come up with an error message stating that it is improperly
config-ured Click OK
Trang 94 A dialog box will pop up asking you which mail transports you would like to
use If you have an Exchange server, select it from the list If not, you can selectInternet Mail from the list
5 If you selected Exchange, a dialog box will appear asking you for the names of
the mailbox and e-mail server Fill both of these in and click OK
6 If you are using Internet Mail, you will be asked for your Internet mail account
information
7 Outlook will now configure a series of sample messages, and the Microsoft
Office Assistant should appear (only if you opted to install it) Click the StartUsing Outlook choice
8 Close Outlook and log off Windows.
Once Outlook is installed and you have a mail profile created, you can configurethe SQLServerAgent and MSSQLServer services to start using the new profile to sendand receive mail:
1 Open Enterprise Manager by selecting it from the SQL Server 2000 group under
Programs on the Start menu
2 Expand your server, then Management.
3 Right-click the SQLServerAgent and select Properties.
4 In the Properties dialog box, select the mail profile that you created while
logged in as the SQL Server service account
Trang 105 Click Test to verify that the mail profile works.
6 Click OK at the bottom of the dialog box, and then click OK when asked to stop
and restart the SQLServerAgent service
With a mail profile successfully configured, you can now create operators that willreceive e-mail from the SQL Server
Creating Operators
Several settings need to be configured for SQL Server to be able to contact you whenthere are problems Such settings include whom to contact, when they are available,how those people should be contacted (via e-mail, pager, or Net Send), and of whatproblems should they be alerted An operator is the object used in SQL Server to con-figure all of these settings
NOTE Net Send messages are messages that are sent from a source machine to a tination machine, where they pop up on a user’s screen as a dialog box over all of theopen applications
des-Suppose, for example, that there are several people in your company who need to
be alerted when there is a problem with SQL Server, each of them needing to bealerted for different problems and in various ways Your database administrator mayneed to be alerted of any administration issues (for example, a failed backup or fulltransaction log) via e-mail and pager Your developers may need to be alerted to pro-gramming issues (for example, deadlocks) via e-mail Perhaps managers in your com-pany need to know of other issues, such as when a user deletes a customer from acustomer database, and they want to be alerted by a Net Send message These types ofusers would be handled by creating separate operators for each and configuring thedesired settings
Let’s configure an operator here to demonstrate:
1 Open Enterprise Manager by selecting it from the SQL Server 2000 group under
Programs on the Start menu
2 Expand your server, then Management, then the SQLServerAgent.
3 Click the Operators icon and select New Operator from the Action menu.
4 In the Name box, enter Administrator.
Trang 115 If you configured your system to use SQLServerAgent Mail, enter your e-mail
address as the e-mail name If you did not configure your system to use e-mail,skip this step
6 Type the name of your machine in the Net Send box This can be found by
right-clicking the My Computer icon on the desktop and selecting Properties,then the Network Identification tab The computer name is the first section ofthe full computer name (before the first period) If your full computer name isinstructor.domain.com, the computer name is instructor
7 At the bottom of the screen, select the days and times this operator is available
for notification If a day is checked, the operator will be notified on that daybetween the start and end times noted under Workday Begin and Workday End
8 To test the operator, click the Test buttons next to each of the three notification
methods The e-mail and pager tests will both send an e-mail, and the Net Sendtest will cause a dialog box to pop up on your screen
9 We’ll discuss the Notifications tab later; for now, click OK to create the operator.
Because operators can be made active at different times, it is possible to tally leave a small period of time uncovered If there is an error in that window oftime, no operator would receive the alert, because none are on duty To avoid such a
Trang 12acciden-problem, you should create a fail-safe operator, which is designed to receive alertswhen no one is scheduled to be on duty Here is how to create one:
1 In Enterprise Manager, right-click the SQL Server Agent icon under
Manage-ment and select Properties
2 On the Alert System tab, select yourself in the drop-down list next to Fail-Safe
Operator
3 Check the box next to Net Send so that you will receive Net Send messages as a
fail-safe operator
4 Click OK to apply the changes.
With an operator in place, you are ready to start creating jobs to automate tasks
Creating Jobs
A job is a series of tasks that can be automated to run whenever you need them to Itmay be easier to think of it as being somewhat like cleaning your house Most of usthink of cleaning our house as one big job that needs to be done, but it is really just aseries of smaller tasks such as dusting the furniture, vacuuming the carpet, doing thedishes, etc Some of these steps need to be accomplished in succession (for example,dusting before vacuuming); others can happen anytime (for example, the dishes don’tneed to be done before you can wash the windows)
Any job on SQL Server works in much the same way Take, for example, a job thatcreates a database This is not just one big job with one step to accomplish beforeyou’re done; there are several steps that should take place Step one would be to createthe database The next step would be to back up the newly created database, because
it is in a vulnerable state until it is backed up After the database has been backed up,you can create some tables in it and then perhaps import data into those tables fromtext files Each of these tasks is a separate step that needs to be completed before thenext can be started, but not all jobs are that way
By controlling the flow of the steps, you can build error correction into your jobs
For example, in the create-database job listed above, each step would have simple
logic that states on success go to the next step; on failure quit the job So if the hard disk
turned out to be full, the job would stop If you create a step at the end of the job that
is designed to clear up some hard-disk space, you could create logic that states if step
one fails, go to step five; if step five succeeds, go back to step one With the steps in place,
you are ready to tell SQL Server when to start the job
Trang 13To tell SQL Server when to run a job, you need to create schedules, and you have alot of flexibility there With a job that creates a database, it would not make muchsense to have it run more than once, so you would create a single schedule that willactivate the job after-hours If you were creating a job that is designed to performtransaction log backups, you would want a different schedule You may want to per-form these backups every 2 hours during the day (from 9:00 A.M to 6:00P.M.) andthen every 3 hours at night (from 6:00 P.M to 9:00 A.M.) In this instance, you wouldneed to create two schedules, one that is active from 9:00 A.M to 6:00 P.M that acti-vates the job every 2 hours and another that is active from 6:00 P.M to 9:00 A.M thatactivates the job every 3 hours If you think that’s fancy, you’ll love this next part.Not only can you schedule a job to activate at certain times of the day, you canschedule them to activate only on certain days of the week (for example, every Tues-day), or you can schedule them to run only on certain days of the month (for example,every third Monday) Jobs can be scheduled to run every time the SQLServerAgent service starts up, and they can even be scheduled to run every time the processorbecomes idle.
Schedules can be set to expire after a certain amount of time, so if you know youare going to be done with a job after a few weeks, you can set it to expire—it willautomatically be disabled (not deleted, just shut off)
You also have the capacity to be notified of the outcome of a job On the final tab
of the Create Job dialog (which you will see very soon), you can add an operator tothe job that can be notified on success, on failure, or on completion (no matterwhether it failed or succeeded) This comes in very handy when the job you are run-ning is critical to your server or application
With the ability to change the logical flow of steps, schedule jobs to run wheneveryou want, and have them notify you on completion, you can see how complex jobscan become With this complexity in mind, it is always a good idea to sit down withpencil and paper, and plan out your jobs before creating them; it will make your jobeasier in the long run
There are two types of jobs in SQL Server, local and multiserver Let’s look at each
of these, starting with local jobs
Creating Local Server Jobs
Local jobs are standard jobs with a series of steps and schedules They are designed to
run on the machine where they are created, hence the name local jobs To
demon-strate local jobs, let’s create one that will create a new database and then back it up:
1 Open Enterprise Manager by selecting it from the SQL Server 2000 group under
Programs on the Start menu
2 Expand your server, then Management, then SQLServerAgent.
3 Select Jobs and, from the Action menu, select New Job.
Trang 144 In the Name box, type Create Test Database (leave the rest of the boxes on
this tab with the default settings)
5 Go to the Steps tab and click the New button to create a new step.
6 In the Step Name box, type Create Database.
7 Leave the type as Transact-SQL and enter the following code to create a database
named Test on the C: drive:
CREATE DATABASE TEST ONPRIMARY (NAME=test_dat,FILENAME=’c:\test.mdf’,SIZE=10MB,
MAXSIZE=15,FILEGROWTH=10%)
Trang 158 Click the Parse button to verify that you entered the code correctly, then move
to the Advanced tab
9 On the Advanced tab, verify that the On Success Action is set to Go to the Next
Step and that the On Failure Action option is set to Quit the Job Reporting ure, then click OK
Fail-10 To create the second step of the job, click the New button.
11 In the Name box, enter Backup Test.
12 Leave the Type as Transact-SQL Script and enter the following code to back up
the database once it is created:
EXEC sp_addumpdevice ‘disk’, ‘Test_Backup’, ‘c:\Test_Backup.dat’BACKUP DATABASE TEST TO Test_Backup
Trang 1613 Click OK to create the step.
14 Move to the Schedules tab and click the New Schedule button to create a schedule,
which will instruct SQL Server when to fire the job
15 In the Name box, type Create and Backup Database.
16 Under Schedule Type, select One Time and set the time to be 5 minutes from
the time displayed in the system tray (the indented part of the Start bar, usually
at the bottom right of your screen)
17 Click OK to create the schedule, and move to the Notifications tab.
18 On the Notifications tab, check the boxes next to E-Mail Operator (if you
con-figured SQL Agent Mail earlier) and Net Send Operator, choosing yourself as theoperator to notify Next to each, select Whenever the Job Completes from thelistbox (this will notify you no matter what the outcome of the job is)
Trang 1719 Click OK to create the job and wait until the time set in step 16 to verify
comple-tion You should see a message pop up on your screen notifying you of complecomple-tion
So what just happened? You created a job with two steps; the first step created anew database named Test, and the second step backed up the database to a newbackup device This job was scheduled to run only one time and notify you of com-pletion (whether or not it was a success) The two steps in this job were Transact-SQLtype jobs, which means that they were just standard Transact-SQL statements, muchlike you have been using throughout this book You can run any Transact-SQL state-ment in this fashion, but that’s not all
Not only can you schedule Transact-SQL statements, you can schedule any activescripting language: VBScript, JavaScript, Perl, etc This frees you from the boundaries
of Transact-SQL, because the scripting languages have features that SQL Server doesnot implement For example, you cannot directly access the file structure on the harddisk using Transact-SQL (to create a new text file, for example), but you can with ascripting language Listing all of the advantages of scripting languages goes beyondthe scope of this book, but to demonstrate how SQL Server schedules such tasks, let’screate a job that prints a statement:
1 Open Enterprise Manager by selecting it from the SQL Server 2000 group under
Programs on the Start menu
2 Expand your server, then Management, then SQLServerAgent.
3 Select Jobs and, from the Action menu, select New Job.
4 In the Name box, type VBTest (leave the rest of the boxes on this tab with the
default settings)
5 Go to the Steps tab and click the New button to create a new step.
Trang 186 In the Step Name box, type Print.
7 Select Active Script as the Type and then check VBScript.
8 Enter the following code in the Command box:
sub main()Print “Your job was successful”
end sub
9 Click the Parse button to verify that you entered the code correctly, then click OK.
10 Move to the Schedules tab and click the New Schedule button.
11 In the Name box, type Run Print.
12 Under Schedule Type, select One Time and set the time to be 5 minutes from
the time displayed in the system tray (the indented part of the Start bar, usually
at the bottom right of your screen)
Trang 1913 Click OK to create the job and wait until the time set in step 12 to verify
To verify whether your VBScript job succeeded, let’s check the history of the job:
1 In Enterprise Manager, right-click the VBTest job and select View Job History.
2 To show the status of each step of the job, check the box at the top right of the
Job History dialog box labeled Show Step Details
3 Select the Print step and look for the text “Your job was successful” at the
bot-tom of the dialog box in the Errors and/or Messages box This is the text ated by the VBScript function
gener-4 Click Close to exit the dialog box.
The history for each job is stored in the MSDB database By default, 1000 lines oftotal history can be stored, and each job can take up to 100 of those records If youneed to change those defaults, follow these steps:
1 In Enterprise Manager, right-click the SQLServerAgent and select Properties.
Trang 202 Select the Job System tab.
3 To change the amount of data saved for all jobs, modify the Maximum Job
His-tory Log Size
4 To change the number of rows that each job can take, change the Maximum Job
History Rows per Job
5 Clicking the Clear Log button will erase all of the history for all jobs on the
server
6 Click OK when you have made the necessary changes.
It’s not hard to see the value of creating local jobs on SQL Server, but there is more
Multiserver jobs are designed to make automation easier across multiple servers
Creating Multiserver Jobs
A growing number of companies today have multiple database servers Each of theseservers will require jobs; some are unique to the server, but many are repetitive, eachserver having the same job One way to solve this problem is to create local jobs oneach server separately, but this is time-consuming and hard to manage A better way
to make this happen is to create multiserver jobs
Trang 21A multiserver job is a job that is created once, on one server, and downloaded to
other servers over the network, where the job is run To create multiserver jobs, you
must first designate two types of servers: a master and targets The master server (or MSX) is where the multiserver jobs are created and managed The target servers poll
the master server at regular intervals for jobs (we’ll see how to change this a little later
in the chapter), download those jobs, and then run them at the scheduled time This
is done using the Make MSX Wizard; let’s run it now
NOTE To perform this series of steps, you will need to have a second instance of SQLServer running on your machine To do this, please refer to Appendix B: “InstallingMicrosoft SQL Server 2000.”
1 Open Enterprise Manager from the SQL Server 2000 group under Programs on
the Start menu
2 Expand your server (not the \SECOND server), then Management.
3 Right-click the SQLServerAgent, and select Multiserver Administration and
Make This a Master This will start the Make MSX Wizard
4 On the opening screen of the Wizard, click Next.
5 Fill in the information for the MSXOperator This is the operator that will
receive notification of multiserver jobs If you configured e-mail support earlier,
Trang 22enter your own e-mail address as the E-Mail Address and your machine name asthe Net Send Address.
6 In the Select Servers to Enlist dialog, check the box next to servername\SECOND
to enlist this as a target server (it will now accept jobs from the master server)
Trang 238 On the final screen, click Finish to create the master server and enlist the target.
9 After this is complete, expand SQLServerAgent under Management and then
expand Jobs Notice that you now have local and multiserver jobs available.Now that you have created a master server and enlisted a target server, let’s create ajob on the master that will run on the target and notify the MSXOperator (you) when
it is complete:
1 Under SQLServerAgent, select Multiserver Jobs and, from the Action menu,
select New Job
Trang 242 In the Name box, type Create Database on Target.
3 Under Source, select Target Multiple Servers and click the Change button.
4 Under Available Servers, select the \SECOND server, click the Add button (the
arrow pointing right), and click OK
5 Verify that the target server is listed on the General tab and select the Steps tab.
6 On the Steps tab, click the New button and enter Create Target Database in
the Name box
Trang 257 Leave the Type as Transact-SQL Script and enter the following code to create a
database named TARGET on the C: drive:
CREATE DATABASE TARGET ONPRIMARY (NAME=target_dat,FILENAME=’c:\target.mdf’,SIZE=10MB,
MAXSIZE=15,FILEGROWTH=10%)
8 Click OK to create the new step and then move to the Schedules tab.
9 Click the New button to create a new schedule.
10 In the Name box, enter Create Target Database.
11 Select One Time for the Schedule Type and set the time to be 10 minutes from
the time listed in the system tray