DATABASE APPLICATION DEVELOPMENTMany DBAs are application developers who specialize in writing code to access datastored in SQL Server databases.. Although this is most commonly done usi
Trang 1316 C 23 Mobile data strategies
Unlike svcutil.exe, this process will not generate a config file to store the endpointinformation This information is stored in the client proxy code
To use this tool:
1 Open a Visual Studio command window
2 Change the directory to your mobile application directory
3 Enter this command:
NETCFsvcutil.exe http://<machinename>/yourservice/service.svcThe preceding command should generate two source files The one namedafter your service will contain the proxy class you will use to consume the WCFservice you created Add these classes to your project and compile the code.The code can be found at this book’s website, http://www.manning.com/SQLServerMVPDeepDives
Comparison
Much thought has been given to creating solutions to ensure that data remains in syncduring periods of connectivity All of the techniques—RDA, MR, and MSF—allow datasynchronization and replication; however, each has its own strengths and disadvan-tages, as shown in table 6
Summary
Which replication strategy you use is up to you, but if you are looking for a robust,developer-centric, scalable solution, the MSF should be your choice Notice the com-parison in table 6 MSF replaces the functionality in RDA with an enhanced plan and
Table 6 Key feature comparison of the three synchronization methodologies
Synchronize by using services No No Yes Supports heterogeneous databases No No Yes Incremental change tracking No Yes Yes Conflict detection and resolution No Yes Yes Easily create data views on the client No No Yes Automatically initialize schema and data Yes Yes Yes Supports large data sets Yes Yes Yes Query processor is locally available Yes Yes Yes Automatically propagate schema changes No Yes No Automatically repartition data No Yes No Use on devices Yes Yes Yes
Trang 2Summary
copies the functionality of MR If you require a DBA-centric approach with little code
to set up the process, then MR is your choice Both MSF and MR will keep your data insync With the techniques and code samples we have shown in this chapter, you will beable to take advantage of these methodologies to transfer, create, modify, and repli-cate your data from your mobile device to your desktop server
About the author
John Baird began his computer programming career while in the
US Navy In 1982, he helped form and direct the first PC-basedcomputer processing department for training and manpower inthe Department of Defense After leaving the military in 1988,John began a varied career as a consultant developing businessapplications ranging from computer-based training to verticalmarket software for resellers
Today, John is working for the industry leader in financial ware for fund administration John was awarded his MVP status fordevice application development beginning in 2008
Trang 4A good DBA works with actions rather than words: automating, monitoring,tuning, but above all learning and constantly realizing what they don’t know Noone can know everything, and a good DBA recognizes that—even embraces it Agood DBA is always looking to improve their systems, learn tips and tricks, andprototype new configurations A good DBA sets up alerts to be notified of errorsand problems as soon as they begin to happen, possibly solving them before theyturn into disasters Just as in life, the sooner you know there’s a problem, the eas-ier it may be to fix! (Did you know that you can set up SQL Server Alerts based onerror severity levels—not just specific error numbers? For severity levels 19 andhigher, a generic alert should notify you that an error has occurred.)
So, how does a DBA make this happen? Not only does a good DBA proactivelylook for faults before they become catastrophic but, when something does gowrong, a good DBA takes the time to do a root-cause analysis to make sure the risk
is avoided in the future Leveraging the SQL Server toolkit is imperative in ing this happen Auditing, leveraging the Dynamic Management Views (DMVs),using PowerShell, knowing the ins and outs of backup and restore, understand-ing security, understanding availability; there are a lot of areas to understand, and
Trang 5mak-a good DBA must be a jack of all trades and a master of at least some! It’s not easy, and
it’s more than just a job for a good DBA SQL Server is a passion for these DBAs—ahobby in addition to their job—and they’re constantly learning and expanding onwhat they know to improve their uptime, minimize data loss, and even allow them totake a vacation once in a while
This book won’t teach you everything you need to know to be a good DBA, but it’sone important part in the lifelong quest to get you there Specifically, this section con-sists of tips and tricks from some of the many MVPs who are either full-time DBAs (orused to be) or who consult with DBAs who are constantly improving their systems andskills Many of these topics are the particular passions of the authors, and they’vedonated their time and experiences to help us all become better DBAs We truly want
to thank them for their time and especially their passion
SQL Server is a passion for both of us and we’ve enjoyed reading and learning fromthese chapters and experiences Whether you’re a seasoned DBA or a newcomer to SQLServer, we know you’ll find material in this section that will help you learn, grow, andbecome a better DBA
About the editors
Paul S Randal and Kimberly L Tripp are a band-and-wife team who own and run SQL-skills.com, a world-renowned SQL Server consultingand training company They are both SQL ServerMVPs and Microsoft Regional Directors, with over
hus-30 years of combined experience on SQL Server Paul worked on the SQL Server team for nineyears in development and management roles, writ-ing many of the DBCC commands, with responsibil-ity for core Storage Engine for SQL Server 2008
Paul writes extensively on his blog (SQLskills.com/blogs/Paul) and for TechNet
Maga-zine, where he is a Contributing Editor.
Kimberly worked on the SQL Server team in the early 1990s as a tester and writerbefore leaving to found SQLskills and embrace her passion for teaching and consult-ing Kimberly has been a regular at worldwide conferences since she first presented atTechEd in 1996, and she blogs at SQLskills.com/blogs/Kimberly
Paul and Kimberly have written Microsoft white papers and books for SQL Server
2000, 2005, and 2008, and are regular, top-rated presenters worldwide on databasemaintenance, high availability, disaster recovery, performance tuning, and SQL Serverinternals Together they teach the SQLMCM certification throughout Microsoft
In their spare time they like to find frogfish in remote corners of the world
Trang 6The job of DBA encompasses many different roles (and often job titles), andthese vary widely from one organization to the next In short, there is no standardjob description for a DBA This is partly because the job title doesn’t have a long his-tory (relational databases were first used in the 1970s, and Microsoft SQL Server Ver-sion 4.21 was released in 1993) and partly because the DBA role is quickly evolving asnew technologies are released.
Because there is no commonly-accepted definition of a DBA, the goal of thischapter is to describe the types of tasks and roles that DBAs commonly perform, withthe aim of explaining to those new to the profession what DBAs do day-in and day-out
The first section of this chapter describes many of the tasks DBAs commonly form The second section classifies these tasks into specialty roles, as you will rarelyfind a DBA who performs all of these tasks all the time Throughout this chapter, I try
per-to answer the question: “What does it mean per-to be a DBA?”
Typical DBA tasks: A to Z
DBAs perform so many different tasks that it is hard to categorize them all Thealphabetized list that follows outlines the common DBA tasks This list is by nomeans comprehensive, and some of the tasks overlap
Trang 7322 C 24 What does it mean to be a DBA?
APPLICATION INTEGRATIONMost organizations use some combination of in-house and third-party applications;and few of these applications work in isolation Therefore, DBAs often have to makedisparate applications talk to one another, using a database as the means of sharingdata DBAs commonly get involved in figuring out the best way to integrate applica-tions, and often perform the integration themselves
ARCHIVING DATAData grows over time and can become costly to store and difficult to manage In addi-tion, increased data tends to exacerbate performance problems DBAs are oftenresponsible for monitoring data size and growth, and determining the best way tostore it In some cases, this may include archiving seldom-used data in another data-base, or it might mean purging data that is no longer needed Often, choices are lim-ited, as company policy and government regulations can restrict how and where data
is stored
ATTENDING MEETINGSMost DBAs hate attending meetings because it detracts from work time Meetings are afact of working life and, if used wisely, aren’t necessarily a waste of time With correctplanning and preparation, meetings are great opportunities for improving communi-cations The responsibilities of the DBA are often unknown or misunderstood by co-workers, so DBAs should always take advantage of opportunities, such as meetings, toshare with others what they do
AUDITING
An emerging task of the DBA is to identify which users are accessing, inserting, ing, or deleting data, and when Auditing might only be necessary for limited timeperiods, for specific data, or it might be required 24/7 for all data DBAs often workwith people outside their organization, such as external auditors, to perform this task.And to further complicate the lives of DBAs, many industries are subject to specificregulations on how data is accessed and protected, which means that DBAs have tocomply with some specific rules, with the potential for significant penalties, shouldthey not fully comply
updat-BACKUP AND RECOVERYOne of the most fundamental aspects of the DBA’s job is to protect the organization’sdata This includes making periodic backups of data and keeping it safe from acciden-tal or intentional destruction In addition, a well-developed recovery plan needs to beimplemented and tested so that when problems arise, data and access to critical sys-tems can be restored quickly
BUSINESS INTELLIGENCE AND DATA WAREHOUSINGAnother emerging trend is for DBAs to be tasked with the creation and maintenance
of data warehouses and business intelligence applications, so organizations can betteruse their data to make more effective business decisions Increasingly, DBAs are spe-cializing in this fast-growing area
Trang 8respon-CHANGE MANAGEMENTSQL Server configurations, database schema, T-SQL code, and many other facets of theapplication ecosystem change over time It is often the responsibility of the DBA toperform impact analysis before changes are made, implement changes, test changes,and document them.
DATA MODELING AND DATABASE DESIGNThe foundation of all efficient and scalable databases is good design DBAs often cre-ate database designs by performing needs and requirements analysis, creating a logi-cal model, and then implementing the physical model Larger organizations may haveDBAs who specialize in database design
DATABASE APPLICATION DEVELOPMENTMany DBAs are application developers who specialize in writing code to access datastored in SQL Server databases Although this is most commonly done using T-SQL, itcan include writing code that is used to access SQL Server data Many DBAs decide tomake this their area of specialty, because of the depth of knowledge required to be agood database applications developer
DEVELOPING AND MAINTAINING BEST PRACTICESSuccessful DBAs are proactive in their work, and one of the best ways to be proactive is
to develop sound database best practices, and to implement them in a consistent ner The better organized and managed the database operations, the more efficientthey will be One of the many ways that DBAs can perform this task is to create a run-book that describes the organization’s best practices and internal procedures Thisdocument is the DBA’s bible for performing all DBA-related functions
man-DISASTER RECOVERY
At some point in their careers, DBAs will have to recover lost data This may be as ple as restoring a database and its log files, or it may be as complex as moving aweather-damaged data center from one city to another To make dealing with disasterseasier (small or big), it’s the DBA’s responsibility to plan, implement, and regularlytest disaster recovery scenarios
sim-HARDWARE SETUP AND CONFIGURATION
In some organizations, hardware is handled by dedicated hardware technicians Inothers, the DBA is responsible for building, installing, and configuring their own hard-ware, including servers and storage area networks (SANs) In addition, DBAs may alsoperform regular hardware troubleshooting and maintenance
HIGH AVAILABILITY
A DBA needs to ensure that the databases are available to users when they need access
to data You can help ensure high availability in many different ways, including use of
Trang 9324 C 24 What does it mean to be a DBA?
log shipping, clustering, database mirroring, and other technologies Because of thespecialized knowledge required for high availability techniques, many DBAs choosethis as their main area of focus
INSTALLING, CONFIGURING, AND UPGRADING SQL SERVER SOFTWAREOne of the most time-consuming of all database tasks is installing, configuring, patch-ing, and upgrading SQL Server instances Although it might sound like an easy task, itusually isn’t One of the difficulties is finding a good time to perform such work, espe-cially in 24/7 shops In addition, each time SQL Server is patched or upgraded, there
is the risk that after the patch or upgrade the applications that access the database, orthe databases themselves, might not work properly On top of this, DBAs often have tobattle third-party vendors who are unwilling to certify that their application will workafter you have made the changes This requires the completion of planning, testing,and backout preparation before implementing major changes
LOAD BALANCINGOver time, the load put on individual databases changes DBAs are responsible formonitoring workloads and figuring out how to maximize hardware resources to getthe best SQL Server performance This may involve moving a database from a heavilyloaded server to a server with a lighter load SQL Server virtualization, and how it canbenefit load balancing, is becoming a hot topic for many DBAs For more information
on SQL Server virtualization, see chapter 39, “Running SQL Server on Hyper-V,” byJohn Paul Cook
MAINTAINING DOCUMENTATIONWriting and maintaining documentation is probably the most boring and loathed taskthat a DBA will encounter However boring, it is a critical part of the DBA’s job If youdon’t document, then there is no easy way to rebuild the current infrastructureshould major problems arise
MANAGING PEOPLEMany DBAs find themselves in management positions, such as a senior DBA in charge
of junior DBAs Some DBAs at large organizations do this full time, whereas otherscombine people management with other DBA duties On the other hand, when someDBAs get a taste of management, they give it up to get back to more technical work.Managing people is not for everyone
MANAGING SQL SERVER–BASED APPLICATIONS
A surprise for many new DBAs is the realization that they are responsible not only formanaging SQL Server and its databases, but in many organizations, they are alsoresponsible for managing any applications that access the database In some organiza-tions, the DBA spends more time managing applications than SQL Server itself.MANAGING TEST ENVIRONMENTS
In many organizations, DBAs manage test environments that not only include test SQLServers and test databases, but also test applications The purpose of this is to allowapplications (both in-house and third-party) to be tested before new versions of eitherthe application or SQL Server are rolled out into production
Trang 10Typical DBA tasks: A to Z
MENTORINGOftentimes, DBAs have to share their knowledge with other DBAs, developers, or endusers This might be informal one-on-one tutoring, or it might include classroomtraining
MONITORINGThis is a wide-ranging task that includes multiple subtasks, such as performance mon-itoring, monitoring server disk space, viewing logs, ensuring jobs have run successfully,and scrutinizing for errors Although a variety of third-party tools are available to per-form these tasks, DBAs commonly spend a lot of time performing monitoring manuallybecause they don’t have a budget for such tools, or they are not familiar with them.NEEDS AND REQUIREMENTS ANALYSIS
Whether DBAs are involved in development, or just supporting third-party tions, they often get involved in needs and requirements analysis This can includetalking to users, finding out their needs and requirements, and determining the bestway to meet them This often includes researching available third-party solutions anddetermining if it’s best to develop the application in-house, or to invest in a third-partyapplication
applica-NEGOTIATING SERVICE LEVEL AGREEMENTS
In many organizations, DBAs become involved in negotiating service level agreements(SLAs) An SLA is an agreement between parties in which one is the customer and theother is the service provider The customer (the owner of the business applicationaccessing SQL Server databases) and the DBA (the service provider), must agree onacceptable levels of service, such as defining what is an acceptable response time for aspecific type of transaction Part of the negotiating process often requires the DBA toset expectations and educate the customer on what is feasible given the resource con-straints of the organization
OPERATING SYSTEM SETUP, CONFIGURATION, AND ADMINISTRATIONJust as many DBAs manage their own hardware, many DBAs also manage the operatingsystem on their SQL Server instances Not only must SQL Server be configured opti-mally, the operating system it is running on must also be configured optimally, and beproperly maintained
PERFORMANCE TUNINGEveryone wants their data right now It is the job of the DBA to monitor performanceand to determine ways to optimize database performance This can be complex, andmany DBAs specialize in this area
PROJECT MANAGEMENTOftentimes, DBAs find themselves in charge of a large project involving many otherpeople This could entail writing a new in-house application, or managing the migra-tion of a data center from one location to another DBAs with good project manage-ment skills are in high demand
Trang 11326 C 24 What does it mean to be a DBA?
REPLICATIONData is often moved from one server to another, and one of the most popular ways toperform this task is to use SQL Server replication DBAs often research various waysdata can be replicated from server to server, decide on the most appropriate method,implement replication, and then manage it after it is up and running
REPORT WRITINGWith the advent of SQL Server Reporting Services, many DBAs find themselves writingreports against databases This might include writing the T-SQL code to extract thedata, or it could include the creation and formatting of physical reports This is a newand growing area, and some DBAs are specializing in it
RUNNING JOBSVirtually every SQL Server has jobs that run periodically They might include backups,data imports or exports, index rebuild jobs, and data integrity checks DBAs are respon-sible for determining what jobs are needed, creating the jobs, and scheduling them.SCRIPTING
DBAs often write their own T-SQL scripts to perform a wide range of tasks, includingmonitoring and maintenance With the advent of PowerShell, many DBAs are writingPowerShell scripts to enhance their productivity
SECURITYDBAs control who can access data and what they can do with it This has many aspects,including creating SQL Server logins and users, assigning permissions, moving secu-rity between servers, and implementing data encryption
SSIS AND ETLDBAs often move data in and out of databases, and at the same time, perform transfor-mations on the data as it is moved This is often done for data warehouses and applica-tion integration This process is often referred to as extract, transform, and load(ETL), and in SQL Server this is commonly performed using SQL Server IntegrationServices (SSIS)
TESTINGDBAs frequently perform all sorts of testing This can include testing of the following:databases, applications, management tools, and disaster recovery plans DBAs testbecause they want to ensure the high availability and integrity of their data
TROUBLESHOOTINGVirtually every day, DBAs troubleshoot one problem or another Often when a prob-lem occurs, the DBA is expected to drop everything and focus on resolving the prob-lem at hand This can result in long hours and high levels of stress As with manytechnical positions, effective DBAs are good problem solvers
WORKING WITH TEAMMATESDBAs rarely work alone In most cases, DBAs interact with many people, includingother DBAs, developers, end users, product-knowledge specialists, vendors, accoun-tants, hardware experts, and networking experts Because of this, DBAs need goodpeople skills
Trang 12DBA specialtiesDBA specialties
As you can see, DBAs perform many different tasks and take on a wide variety of roles.Usually, DBAs are generalists because they need to know a little about many differentareas On the other hand, you seldom find a DBA who is a master of all the previouslydescribed tasks This is for two reasons First, most people don’t have the time to mas-ter every DBA-related subject Second, there is the added burden of having to keep upwith rapidly changing technology For most people, it’s impossible to carry out allaspects of the DBA role To become a successful DBA, you don’t have to knoweverything there is to know about SQL Server In fact, you have a much better chance
of becoming a successful DBA if you narrow your focus and specialize in a handful ofSQL Server subjects
In this section, we take a look at some of the common areas in which DBAs specialize.DBA SYSTEM ADMINISTRATOR
The DBA system administrator is a generalist who knows a little about many differentsubjects Also known as a production DBA, the DBA system administrator is generally
in charge of setting up, configuring, and maintaining test and production SQL Serverinstances This can include such routine tasks as monitoring, performance tuning,backups and restores, security, creating jobs, and so on In medical terms, think of theDBA system administrator as the general practitioner All of the other DBA specialistsare more like medical specialists
DBA DATABASE ARCHITECTThink of a DBA database architect as the employee who sees the big picture of datastorage and access in an organization, and whose job it is to research the organiza-tion’s data needs, research the available options, and then recommend policies theorganization should implement In many organizations, the title of database architect
is another name for the lead DBA, DBA manager, or DBA project manager
DBA DATABASE DESIGNERDBA database designers focus on creating new database schemas They define userneeds and requirements, develop logical database designs, create physical databases,and so on In most cases, the DBA database designer works with DBA developers, orother developers, to develop and maintain applications
DBA DEVELOPERThe DBA developer writes code, be it T-SQL scripts, stored procedures, functions,Common Language Runtime (CLR) objects, or any other kind of code that is used toaccess SQL Server data Often, the DBA developer works with DBA system administra-tors, DBA database designers, project managers, and other developers to develop andmaintain applications
DBA HIGH AVAILABILITY AND DISASTER RECOVERY SPECIALISTFor many of today’s online businesses, it is more critical than ever that SQL Server isavailable around the clock Therefore, DBAs often need to specialize in high availabil-ity Their job is to determine what high availability methods are best for their environ-ment, and then to implement and maintain them, helping to prevent the loss of data
Trang 13328 C 24 What does it mean to be a DBA?
in the first place Other DBAs specialize in disaster recovery, after the fact In otherwords, they are brought in to try to recover data from corrupted databases becauseexisting high availability and disaster recovery procedures failed
DBA BUSINESS INTELLIGENCE SPECIALISTDBA BI (business intelligence) specialists design, create, and maintain data ware-houses and online analytical processing (OLAP) cubes, so that data can more easily beretrieved and analyzed by organizations This often involves developing BI-basedapplications written using Multidimensional Expressions (MDX) queries In mostcases, they are also heavily involved in extract, transform, and load (ETL) and design-ing and implementing SSIS packages
DBA REPORT WRITER
In the past, the DBA report writer has often been lumped in with the business gence specialist SQL Server Reporting Services has evolved to a point that many DBAsare now specializing in designing and creating reports to extract data from databases
intelli-in meanintelli-ingful ways
Summary
Given that the DBA job description is so varied and constantly changing, it is hard tolist all the possible DBA specialties on which you might want to focus, so don’t con-sider the list in this chapter to be anything more than an informal guide
You may find that you want to develop your own specialty, one that is even morefocused than the broad specializations I’ve listed For example, you might want to focus
on performance tuning, clustering, SSIS, or replication only Nothing prevents youfrom specializing as much as you like, other than the fact that the more narrow yourspecialty, the fewer jobs available
As we have seen, being a DBA means many different things It is not a single job titlewith a single skill set Instead, the job title of DBA encompasses a wide range of job tasksand roles that are tied together with a single common denominator—DBAs are theguardians of the organization’s data As DBAs, it is our job not only to protect an orga-nization’s data, but also to make it available to everyone in the organization who needs
it to perform their jobs effectively How well we fulfill this responsibility determineshow successful we are as DBAs
Trang 14SummaryAbout the author
Brad M McGehee is an MCSE+I, MCSD, and MCT (former) with
a bachelor's degree in Economics and a master's in BusinessAdministration Involved in the industry since 1982, Brad is cur-rently the Director of DBA Education for Red Gate Software,and is an accomplished Microsoft SQL Server MVP with over 14years of experience with SQL Server and over 6 years of trainingexperience Brad is a frequent speaker at SQLPASS, EuropeanPASS, SQL Connections, SQLTeach, SQLBits, SQL Saturdays,TechFests, Code Camps, SQL Server user groups, and otherindustry seminars He blogs at www.bradmcgehee.com
Trang 15maintenance plans Tibor Karaszi
Just like a car or a house, you want to maintain your databases so that they runsmoothly and safely over time You probably have actions you want to perform thatare specific to your application and data, but some actions are common to mostdatabases, like backups and defragmentation This is why Microsoft created mainte-nance plans that make the implementation of standard actions easy We specifywhich of these standard actions we want to perform, for which databases, and atwhat intervals—no T-SQL coding required Of course, some DBAs want more con-trol over the actions than the maintenance plans allow for, but for those who arenot full-time DBAs, maintenance plans are a good solution
What is a maintenance plan, and how do I create one?
The implementation of maintenance plans (MPs) has changed over time FromSQL Server 6.5 to 2000, an MP was executed by sqlmaint.exe through a SQL ServerAgent (Agent) job As of SQL Server 2005, an MP is a SQL Server Integration Ser-vice (SSIS) package, executed by an Agent job
You create a plan using SQL Server Management Studio (SSMS) and clicking the Maintenance Plans folder under the Management folder You can useeither a wizard or a trimmed-down version of the SSIS package Designer, availableinside SSMS For beginners, I recommend using the wizard, and, as you get morecomfortable using MPs, you can dive into the Designer
The SSIS package is saved directly to the msdb database (not out in the filesystem
as a dtsx file) along with some metadata in the msdb database, indicating that theplan exists This metadata allows SSMS to list your plans in the Maintenance Plansfolder, where you can right-click and edit them If you choose to schedule the plan,which you typically will want to do, then one or more Agent jobs will be created
Trang 16What is a maintenance plan, and how do I create one?
Versions and service packs
If you are using SQL Server 2005, I strongly encourage you to be at least on ServicePack 2 (SP2) on both the server and the client (SSMS) SP2 added some functionality,like a separate schedule per task, and it also added the Maintenance Cleanup Task tothe wizard In fact, if you are using SQL Server 2005, you want to be at least slightlyhigher than the original SP2 release because of some bugs in that original release TIP What build number you want to be using, and how to check it, is slightlycomplicated and depends on whether you have applied a hotfix or not Isuggest you check out http://blogs.msdn.com/psssql/archive/2007/04/06/post-sql-server-2005-service-pack-2-sp2-fixes-explained.aspx and verifythat you aren’t using the original SP2
I will assume SQL Server 2008 in this section An MP in SQL Server 2005 with SP2 looksthe same and has the same functionality as in 2008 (with the addition that for SQLServer 2008 you can compress a backup if you are using Enterprise Edition)
One or several schedules per plan?
You might not be familiar with some of the terms I use here; therefore, it’s time for
some explanations A maintenance plan (plan) is what is created by the Designer or
wiz-ard It’s implemented as an SSIS package, which is saved directly to the msdb database.
An SSIS package consists of several SSIS tasks, where each task is of a certain type (backup database, check integrity, and so on) You decide whether to schedule the plan (typically you will want to do this), which will create one or several Agent jobs, where each job has one Agent schedule.
As of SP2, you can decide whether you want to have one schedule per task or oneschedule for the entire plan (the latter was the only option prior to SQL Server 2005SP2) Having several schedules will result in several Agent jobs—one per schedule.
There are advantages with both alternatives; therefore, think a few minutes about howyou want to do this As an example, say you want to perform these tasks:
Weekly defragmentation and removal of backup history
Daily database backup, removal of old backup files, and checking of databaseintegrity
Transaction log backup every 15 minutes
If you have one schedule per task, you can have only one plan, but you will end up
with six Agent jobs (called subplans), each scheduled separately This means you have
to decide for each job when it is to be executed If you don’t want the jobs to overlapeach other, you’ll have to plan out the timing
On the other hand, if you want only one schedule for the plan, you will end upwith several plans—three plans in the preceding example You would have one planfor the weekly tasks, another for the daily tasks, and yet another for the log backuptask For each plan, you can decide in what order the tasks are to be performed
Trang 17332 C 25 Working with maintenance plans
Regardless of how you do the scheduling, you need to specify what databases to
operate on for each task (for the task types that operate at the database level) This
dif-fers from MPs in SQL Server 2000 and earlier, where you specified the databases at theplan level
The dialog boxes will look slightly different depending on whether you are usingthe wizard or the Designer, on how you want to schedule the plan, and on what ver-sion and service pack you are using, but, in the end, the tasks you perform inside theplan are the same The screenshots that follow in this chapter are from SQL Server
2008, and have one schedule for the whole plan, using the wizard You will find thatyour dialog boxes will look very similar even if some of these attributes differ
Wizard dialogs
If you create your plan using the wizard, you will be presented with a number of dialogboxes that are specific to the wizard It is pretty obvious what they do, so I will onlymention them briefly here:
Select Plan Properties page—Here you specify the name of the plan, an optional
description, and whether you want to have one schedule for the entire plan orone schedule per task If you want one schedule for the entire plan, you canenter the scheduling page from here
Select Maintenance Tasks page—Here you select what tasks you want to include in
the plan
Select Maintenance Task Order page—This page allows you to specify in what order
each task is to be performed
Task types
In the following sections, I will describe the task types that are available in an MP Youwill see that I also mention which T-SQL command or stored procedure is executed foreach task Whenever you feel you want to dive deeper and learn about the options foreach command, don’t hesitate to read about the command in the SQL Server BooksOnline Each command is documented with all its options, and you will also learnabout options that are not exposed in an MP, which can be valuable and help youdecide whether or not to replace that task with your own T-SQL command
Sometimes the most difficult thing is to decide what tasks to include, and in whatorder, so let’s start with some advice on that I typically include the following tasks in
my MPs:
Database check integrity
Reorganize index or rebuild index (not both)
Trang 18What is a maintenance plan, and how do I create one?
The one thing I strongly discourage you from including is the shrink database task.See the following section, “Shrink database task,” for details
As for the order in which tasks are performed, it doesn’t matter much as long as youfollow best practices (for example, don’t shrink and don’t update index statistics if youalso rebuild your indexes) One could argue that you want to check integrity before abackup (and don’t do a backup if the integrity check doesn’t pass), and you couldargue that the other way around is better (check integrity after the backup so that youknow the backup was clean) I don’t recommend spending too much time on this; theimportant thing is choosing which tasks to perform and following best practices
Check database integrity task
The check database integrity task executes the DBCC CHECKDB command, whichsearches for various types of corruption in the database I prefer to execute this asoften as I can (once a day if possible), because I want to know as soon as possible if Ihave a corruption problem in a database
The DBCC CHECKDB command has a lot of options, but only Include Indexes (whichtoggles the NOINDEX option) is available through maintenance plans, as shown infigure 1
Shrink database task
Don’t ever be tempted to run the shrink database task, shown in figure 2 Regularlyshrinking database files can have a huge negative performance impact, amongother things
Figure 1 Defining the check database integrity task
Trang 19334 C 25 Working with maintenance plans
For instance, shrinking fragments your indexes; therefore, it is useless to first ment your indexes and then shrink your database People often think that they canget around this by shrinking the files first, and then rebuilding the indexes, but therebuild operation uses temporary space that then becomes “free” at the completion ofthe index rebuild This often leads to confusion as to why there is free space, and to
defrag-an incorrect assertion that the shrink operation failed to reclaim this space In defrag-anycase, it’s best practice to have a fair amount of free space in your database files Still, I frequently see shrinking being scheduled, and I have an article on my websitedescribing why you want to avoid doing it Check it out at http://www.karaszi.com/SQLServer/info_dont_shrink.asp if you need more convincing
I recommend shrinking database files only in special circumstances This task cutes the DBCC SHRINKDATABASE command
exe-Reorganize index task
The reorganize index task, shown in figure 3, executes the ALTER INDEX commandusing the REORGANIZE option This is something you might want to do in order todefragment your indexes, which in turn can improve performance Note, though,that the task is pretty stupid—it will execute the command for every index in the data-base, regardless of whether the index is fragmented in the first place You can besmarter than that, and you will even find T-SQL code in Books Online that checks thefragmentation level for each index and only defragments the fragmented indexes (seethe Books Online topic for sys.dm_db_index_physical_stats)
Figure 2 Defining the shrink database task
Trang 20What is a maintenance plan, and how do I create one?
Rebuild index task
The rebuild index task, shown in figure 4, is pretty much the same as the reorganizeindex task, but it uses the REBUILD option of the ALTER INDEX command and can gen-erate more problems (in terms of data and log file growth) if misused This also oper-ates on every index in the database, regardless of the fragmentation level
Let me again point out that you shouldn’t both rebuild and reorganize—that is awaste of time and resources There’s a lot to say about index fragmentation anddefragmenting indexes, such as why you might want to do it, whether you should reor-ganize or rebuild, how each operation is implemented, and so on Such elaborationsare outside the scope of this chapter, but Paul S Randal has a section about indexfragmentation in his great TechNet article about database maintenance, titled “TopTips for Effective Database Maintenance.” I encourage you to read the article, whichyou’ll find at http://technet.microsoft.com/en-us/magazine/cc671165.aspx
Update statistics task
The update statistics task uses the UPDATE STATISTICS command, which can improveperformance for your queries by providing the optimizer with more accurate statisticsfor the data in your tables A database option is available that will cause this to be per-formed automatically, but that does not kick in until you have modified about 20percent of the data for a column The more data you sample, the more accurate thestatistics will be, but the longer the statistics collection will take A full scan, which sam-ples 100 percent of the rows, delivers the most accurate statistics, but it obviously takesthe most time
Figure 3 Defining the reorganize index task