1. Trang chủ
  2. » Công Nghệ Thông Tin

Hướng dẫn học Microsoft SQL Server 2008 part 103 ppsx

10 284 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 1,04 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Nielsen c42.tex V4 - 07/21/2009 2:25pm Page 985Maintaining the Database IN THIS CHAPTER Using SQL Server’s Database Console Commands DBCC Creating database maintenance plans The previous

Trang 1

Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 982

The Contents button can be used to check the disk device for specific backups If several backup

instances are in the backup device, the Contents dialog can be used to select the correct backup It then

fills in the file number in the restore form

Before restoring the msdb database, stop SQL Server Agent This ensures that the msdb

database is not being accessed by the SQL Server Agent and allows the restore to complete.

Performing a Complete Recovery

If the server has completely failed and all the backups must be restored onto a new server, this is the

process to follow:

1 Build the Windows server and restore the domain logins to support Windows authentication.

2 Install SQL Server and any service-pack, cumulative updates, security upgrades, or hotfixes.

3 Start SQL Server in single-user mode and restore themasterdatabase

4 Verify that SQL Server Agent is stopped Restore themsdbdatabase

5 If themodeldatabase was modified, restore it

6 Restore the user databases.

Best Practice

Performing a flawless recovery is a ‘‘bet your career’’ skill I recommend taking the time to work through

a complete recovery of the production data to a backup server The confidence it builds will serve you

well as a SQL Server DBA

Summary

The recovery cycle begins with the backup of the databases The ability to survive hardware failure or

human error is crucial to the ACID properties of a database Without the transaction’s durability, the

database can’t be fully trusted Because of this, recovery planning and the transaction log provide

dura-bility to committed transactions The recovery cycle transfers data from the past to the present

They key points from this chapter include the following:

■ Invest the time to create a solid backup and recovery plan

■ Just performing regular backups is not enough Because the only way to know that the backups are good is by restoring them, regularly restore the backups on a test server This

is a boring task but well worth it when a disaster occurs and you need to recover from the backups

Trang 2

Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 983

■ I recommend that a senior SQL DBA create the backup and recovery plan to ensure that all

aspects are taken care of Once the plan is ready, ascertain that the junior DBA can understand

it and perform all the steps in the plan, as it is more than likely that this is the person who

will be recovering from the backups in the middle of the night when a disaster occurs

■ Perform a complete recovery to simulate a server and disk subsystem failure at least every six

months and update your backup/recovery plan as required

In the next chapter, you’ll learn how to maintain the database

Trang 3

Nielsen c41.tex V4 - 07/23/2009 2:46pm Page 984

Trang 4

Nielsen c42.tex V4 - 07/21/2009 2:25pm Page 985

Maintaining the

Database

IN THIS CHAPTER

Using SQL Server’s Database Console Commands (DBCC) Creating database maintenance plans

The previous chapter covered database recovery planning This chapter

explores various database maintenance tasks that need to be performed

regularly, such as database backups, database integrity checks, and index

maintenance It also discusses database maintenance using Transact-SQL Database

Console Commands (DBCC) and Maintenance Plans

DBCC Commands

Microsoft SQL Server Database Console Commands (DBCC) are used for

check-ing database integrity, performcheck-ing maintenance operations on databases, tables,

indexes, and filegroups, and collecting and displaying information during

trou-bleshooting issues

The first DBCC command to become familiar with is theDBCC HELPcommand,

which returns the syntax and all the options for any DBCC command The

following command returns the syntax forDBCC CHECKDB:

DBCC HELP (’CHECKDB’);

Result:

dbcc CHECKDB

(

{ ‘database_name’ | database_id | 0 }

[ , NOINDEX

| { REPAIR_ALLOW_DATA_LOSS

| REPAIR_FAST

| REPAIR_REBUILD

} ]

)

Trang 5

Nielsen c42.tex V4 - 07/21/2009 2:25pm Page 986

[ WITH { [ ALL_ERRORMSGS ] [ , [ NO_INFOMSGS ] ] [ , [ TABLOCK ] ] [ , [ ESTIMATEONLY ] ] [ , [ PHYSICAL_ONLY ] ] [ , [ DATA_PURITY ] ] [ , [ EXTENDED_LOGICAL_CHECKS ] ] }

] DBCC execution completed If DBCC printed error messages, contact your system administrator

What’s New in SQL Server Database Maintenance?

In earlier versions of SQL Server, DBCC stood for ‘‘Database Consistency Checker’’ — now it is renamed

‘‘Database Console Commands.’’ The following deprecated DBCC commands are still in SQL Server

2008, but they will be removed in the next version It is recommended to stop using the deprecated DBCC

commands for new development work and plan to change existing applications using these commands:

■ DBCC DBREINDEX

■ DBCC INDEXDEFRAG

■ DBCC SHOWCONTIG

■ DBCC PINTABLE

■ DBCC UNPINTABLE

While the DBCC PINTABLE and DBCC UNPINTABLE commands are still in SQL Server 2008, they have no

effect on SQL Server Note also that DBCC CONCURRENCYVIOLATION has been discontinued in SQL Server

2008

You can find a complete list of deprecated (outdated or no longer accessible) DBCC commands in Chapter 1,

‘‘The World of SQL Server,’’ in Books Online, and at http://msdn2.microsoft.com/en-US/library/

ms144262.aspx

The following command returns all DBCC commands for which help is available:

DBCC HELP (’?’);

Result:

checkalloc checkcatalog

Trang 6

Nielsen c42.tex V4 - 07/21/2009 2:25pm Page 987

checkconstraints

checkdb

checkfilegroup

checkident

checktable

cleantable

dbreindex

dropcleanbuffers

free

freeproccache

freesessioncache

freesystemcache

help

indexdefrag

inputbuffer

opentran

outputbuffer

pintable

proccache

show_statistics

showcontig

shrinkdatabase

shrinkfile

sqlperf

Trang 7

Nielsen c42.tex V4 - 07/21/2009 2:25pm Page 988

traceoff

traceon tracestatus

unpintable updateusage useroptions DBCC execution completed If DBCC printed error messages, contact your system administrator

All DBCC commands report their activity or errors found, and then conclude with the standard ‘‘DBCC

execution completed’’ statement, including any action that might be needed

Database integrity

DBCC CHECKDBperforms several operations to check the logical and physical integrity of the database

It’s critical for the health of the database that the physical structure is correct.DBCC CHECKDBchecks

things such as index pointers, data-page offsets, the linking between data pages and index pages, and

the structural content of the data and index pages If a hardware hiccup has left a data page half-written,

thenDBCC CHECKDBis the best means of detecting the problem The following command executes

DBCC CHECKDBon theAdventureWorks2008sample database:

DBCC CHECKDB (’AdventureWorks2008’);

Result (abridged):

DBCC results for ‘AdventureWorks2008’

Service Broker Msg 9675, State 1: Message Types analyzed: 14

Service Broker Msg 9676, State 1: Service Contracts analyzed: 6

Service Broker Msg 9667, State 1: Services analyzed: 3

Service Broker Msg 9668, State 1: Service Queues analyzed: 3

.

DBCC results for ‘sys.sysrscols’

There are 1406 rows in 14 pages for object "sys.sysrscols"

DBCC results for ‘sys.sysrowsets’

There are 263 rows in 3 pages for object "sys.sysrowsets"

DBCC results for ‘sys.sysallocunits’

.

DBCC results for ‘Production.ProductModelProductDescriptionCulture’

There are 762 rows in 4 pages for object

"Production.ProductModelProductDescriptionCulture"

DBCC results for ‘Sales.Store’

There are 701 rows in 101 pages for object "Sales.Store"

DBCC results for ‘Production.ProductPhoto’

There are 101 rows in 50 pages for object "Production.ProductPhoto"

Trang 8

Nielsen c42.tex V4 - 07/21/2009 2:25pm Page 989

Maintaining the Database 42

CHECKDB found 0 allocation errors and 0 consistency errors in database

‘AdventureWorks2008’

DBCC execution completed If DBCC printed error messages, contact your

system administrator

The results you see could vary from those displayed here depending on your SQL Server

configuration and any changes you have made to the database.

Two options simply determine which messages are reported, without altering the functionality of the

integrity check:ALL_ERRORMSGSandNO_INFOMSGS.ALL_ERRORMSGSdisplays all the error

mes-sages; when it is not used, the default displays 200 errors per object TheNO_INFOMSGSoption can be

used to suppress all informational messages

TheESTIMATE_ONLYoption returns the estimated size of thetempdbrequired byDBCC CHECKDB

without actually runningDBCC CHECKDBagainst the database

If the database is large, then the NOINDEXoption can be used to skip checking the integrity of all

user-table non-clustered indexes For additional time savings, thePHYSICAL_ONLYoption performs only the

most critical checks on the physical structure of the pages Use these options only when time prevents a

completeDBCC CHECKDBor when the indexes are about to be rebuilt

If you want to perform logical consistency checks on indexed views, XML indexes, and spatial indexes,

then use the new optionEXTENDED_LOGICAL_CHECKS This option increases the performance impact

on the SQL Server, and currently its progress cannot be tracked It is recommended that you first run

this on a similar database on a similar test SQL Server to get an estimate of the time it takes to run

DBCC CHECKDBwith this option and the performance impact on the SQL Server

For databases upgraded from SQL Server 2000 or earlier, it is recommended to runDBCC CHECKDB

withDATA_PURITYas a post-upgrade step to enable the column-value integrity checks, as they are

dis-abled by default on SQL Server 2000 and earlier After successful completion, column-value integrity

checks are enabled for the database, and you do not need to use theDATA_PURITYoption for future

DBCC CHECKDBexecutions Column-value integrity checks are enabled by default beginning with SQL

Server 2005

To reduce blocking and concurrency problems when integrity checks are done,DBCC CHECKDBuses

an internal database snapshot to perform the checks If a snapshot cannot be created or you use the

TABLOCKoption, thenDBCC CHECKDBuses locks, which include a short-term exclusive lock on the

database TheTABLOCKoption can reduce the time it takes forDBCC CHECKDBto run during peak

usage, but it reduces the concurrency on the database If theTABLOCKoption is used, thenDBCC

CHECKCATALOGis skipped, and Service Broker data is not checked

Review the percent_complete and command columns of the sys.dm_exec_requests

cata-log view to display the progress and current phase of DBCC CHECKDB

Repairing the database

When an error is found andDBCC CHECKDBcan fix it,DBCC CHECKDBindicates the repair level that

is needed to repair the error(s) When an error is reported byDBCC CHECKDB, it is recommended to

restore the database from a known good backup Use the repair option withDBCC CHECKDBonly when

there is no known good backup Repairing the database is a separate operation from the normalDBCC

Trang 9

Nielsen c42.tex V4 - 07/21/2009 2:25pm Page 990

CHECKDBcommand because the database needs to be placed in single-user mode with theALTER

DATABASEcommand before aDBCC CHECKDBcan be executed with theREPAIRoption The following

command places theAdventureWorks2008sample database in single-user mode:

ALTER DATABASE AdventureWorks2008 SET SINGLE_USER;

More on Single-User Mode

The preceding command will wait indefinitely if there is a lock on the database or users are connected

to the database You can use a termination clause, WITH ROLLBACK AFTER integer [SECONDS] or

WITH ROLLBACK IMMEDIATE, to indicate that SQL Server should either roll back incomplete transactions

after the specified number of seconds or roll back immediately and close any active connections to the

database The following command places the AdventureWorks2008 sample database in single-user mode

and specifies that SQL Server should roll back all incomplete transactions immediately and close any active

connections to the database:

ALTER DATABASE AdventureWorks2008 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

If the AUTO_UPDATE_STATISTICS_AYSNC option for the database is set to ON, you will be unable to

place the database in single-user mode, as the background thread that is used to update the statistics takes a

connection against the database You can query the is_auto_update_stats_async_on column in the

sys.databasescatalog view to check if the AUTO_UPDATE_STATISTICS_ASYNC option is set to ON If

so, then first set it to OFF using the ALTER DATABASE command

DBCC offers two repair modes:

■ REPAIR_REBUILD: This mode performs a repair that does not lead to any data loss

■ REPAIR_ALLOW_DATA_LOSS: This mode performs the repairs and fixes corrupted database structures As the name suggests, this mode can result in data loss

Earlier versions of SQL Server included a third repair mode called REPAIR_FAST This mode still exists in SQL Server 2008 but it does not perform any activity and is kept only for backward compatibility.

The following example places theAdventureWorks2008sample database in single-user mode and

runsDBCC CHECKDBwith theREPAIR_ALLOW_DATA_LOSSoption It then sets the database back to

multi-user mode:

ALTER DATABASE AdventureWorks2008 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

BEGIN TRANSACTION;

DBCC CheckDB (’AdventureWorks2008’, REPAIR_ALLOW_DATA_LOSS);

Check for any data loss ROLLBACK TRANSACTION if data loss is not acceptable else COMMIT TRANSACTION;

ALTER DATABASE AdventureWorks2008 SET MULTI_USER;

Trang 10

Nielsen c42.tex V4 - 07/21/2009 2:25pm Page 991

Maintaining the Database 42

Result (abridged):

DBCC results for ‘AdventureWorks2008’

Service Broker Msg 9675, State 1: Message Types analyzed: 14

Service Broker Msg 9676, State 1: Service Contracts analyzed: 6

Service Broker Msg 9667, State 1: Services analyzed: 3

.

DBCC results for ‘sys.sysrowsets’

There are 291 rows in 3 pages for object "sys.sysrowsets"

.

DBCC results for ‘Production.TransactionHistoryArchive’

There are 89253 rows in 620 pages for object

"Production.TransactionHistoryArchive"

CHECKDB found 0 allocation errors and 0 consistency errors in database

‘AdventureWorks2008’

DBCC execution completed If DBCC printed error messages, contact your

system administrator

Best Practice

Since SQL Server 7.0, the Storage Engine’s quality has significantly improved, reducing the need to run

DBCC CHECKDBfrequently However, a foolproof recovery plan will include a full restore and a DBCC

CHECKDBto ensure that all portions of the recovery plan are working The frequency with which you run

DBCC CHECKDBdepends on your comfort level, your environment, and the importance of your data I would

never say that DBCC CHECKDB is not needed; it is recommended to run it now and then, as well as to restore

from backups It is also recommended to run DBCC CHECKDB after any hardware malfunction If an error is

detected, then restore from a known good database backup As mentioned, use the repair option only as the

last option

If DBCC CHECKDB asks you to use REPAIR_ALLOW_DATA_LOSS, then take a full database backup first and

then run DBCC CHECKDB with the repair option in a user transaction That way, you can verify the data

loss after the command is executed and roll back the transaction if the data loss is not acceptable After

successfully repairing the database, take a full database backup

Because DBCC CHECKDB is a resource-intensive operation, run it during low peak hours

Multi-user concerns

DBCC CHECKDBwithout any repair option can be executed while users are in the database However,

DBCC CHECKDBis very processor- and disk-intensive, so run it when the database has the fewest users

By default,DBCC CHECKDBcan check objects in parallel across all CPUs in the box, which can boost

the performance ofDBCC CHECKDBand reduce the run times The degree of parallelism is determined

by the SQL Server query processor, and the algorithm used is similar to running parallel queries

Because runningDBCC CHECKDBin parallel is processor intensive, you may have environments or

situa-tions when you want to disable parallel checking of objects byDBCC CHECKDB SQL Server enables you

to do that using the trace flag 2528

Ngày đăng: 04/07/2014, 09:20

TỪ KHÓA LIÊN QUAN