SQL Server Q&A

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘sql server databases’

The results of rule checks may be logged incorrectly when you try to install or upgrade to SQL Server 2008

Symptoms
When you try to install or upgrade to Microsoft SQL Server 2008, the results of rule checks may be logged incorrectly in the System Configuration Check Report (SystemConfigurationCheck_Report.htm) file and in the Detail.txt log file. For example, the results of the Engine_UserHasNotDefinedSchemaSysCheck rule check may be logged as “Not Applicable.” This occurs even though there is a schema named “sys” in one of the SQL Server databases.
Note This rule check determines whether the user has defined a schema called ’sys’.
Resolution
This problem can occur if the rule is evaluated by using a three-state rule check in SQL Server 2008. A three-state rule check is a rule that can return a Passed, Failed, or Warning status.

FIX: SEM: Appended Backup Database with Verify Always Checks Only FILE Number = 1

Symptoms
When you use SQL Server Enterprise Manager to backup and verify the backup of a database, the verification assessment of the backup is not reliable if the backup set is appended to either a previously existing file or device.
Furthermore, if you attempt to establish a Database Maintenance Plan through the Database Maintenance Wizard and you select Verify the Backup to a tape that contains a Microsoft Windows NT file backup that is File number 1, you will see this error message:

[Microsoft SQL-DMO (ODBC SQLState: 42000)]
Error 3143: [Microsoft][ODBC SQL Server Driver][SQL Server]
The data set on device ‘\\.\Tape0′ is not a SQL Server backup set.
[Microsoft][ODBC SQL Server Driver][SQL Server]Backup or restore
operation terminating.Also, if you put a SQL Server database backup on the tape first and you then attempt to perform a Windows NT backup, a Dr. Watson error (0xc000005) occurs.
Resolution
Here are a few ways to work around this problem:Run this line of code from Query Analyzer to the backup device or file to identify the last backup set in the file:

RESTORE HEADERONLY Next, run this code:

RESTORE VERIFYONLY FROMDISK = N’c:\BACKUP\pubsbk.jnk’ WITHFILE = X ,NOUNLOAD where X is the maximum file id identified by the Position output column from RESTORE HEADERONLY. If you use the Database Maintenance Wizard, alter the previous RESTORE statement in the Schedule Task.
-or-
Consider selecting the Overwrite Existing Media option to make sure that the backed up file is always the first backup set in the file.
-or-
Consider backing up the SQL Server databases to a tape on which only SQL Server database backups exist.
-or-
Consider scripting the commands and then run the commands from a command prompt or batch file.For example:

DECLARE @DBNameVARCHAR(200),@TargetLocation VARCHAR(1000),@BackupNameVARCHAR(200),@FileNumberVARCHAR(10),@xpcmdStringVARCHAR(2000),@PrintStringVARCHAR(200)SELECT @DBName= ‘[pubs]‘,@TargetLocation = ‘c:\BACKUP\pubsbk.jnk’ ,@BackupName= ‘pubs backup’SELECT @xpcmdString = ‘BACKUP DATABASE ‘+@DBName+’ TO DISK = N’ + CHAR(39)+@TargetLocation+CHAR(39)+’ WITHNOINIT ,NOUNLOAD ,NAME = N’ + CHAR(39)+@BackupName+CHAR(39)+’,NOSKIP ,STATS = 10,NOFORMAT ‘EXEC (@xpcmdString)CREATE TABLE #TempBackupResults(BackupName nvarchar(128),BackupDescriptionnvarchar(255),BackupType smallint,ExpirationDate datetime,Compressed tinyint,Position smallint,DeviceType tinyint,UserName nvarchar(128),ServerName nvarchar(128),DatabaseName nvarchar(128),DatabaseVersionint,DatabaseCreationDatedatetime,BackupSize numeric(20,0),FirstLSN numeric(25,0),LastLSN numeric(25,0),CheckpointLSNnumeric(25,0),DatabaseBackupLSNnumeric(25,0),BackupStartDatedatetime,BackupFinishDatedatetime,SortOrder smallint, CodePage smallint,UnicodeLocaleId int,UnicodeComparisonStyle int,CompatibilityLeveltinyint,SoftwareVendorIdint,SoftwareVersionMajorint,SoftwareVersionMinorint,SoftwareVersionBuildint,MachineName nvarchar(128))SELECT @xpcmdString = ‘RESTORE HEADERONLY FROM DISK = N’ + CHAR(39)+@TargetLocation+CHAR(39)INSERT#TempBackupResults EXEC (@xpcmdString)SELECT @FileNumber = CONVERT(VARCHAR(20), MAX(Position))FROM #TempBackupResults WHERE BackupName=@BackupNameSELECT @xpcmdString = ‘RESTORE VERIFYONLY FROM DISK = N’ + CHAR(39)+@TargetLocation+CHAR(39)+’ WITHFILE = ‘ + @FileNumberSELECT @PrintString = ‘Verifying Integrity of Backup Set Number ‘ + @FileNumberPRINT @PrintStringEXEC (@xpcmdString)DROP TABLE #TempBackupResults

Description of the Microsoft application blocks for .NET topic: “Data Access Application Block Overview”

Symptoms
This article discusses the Microsoft Application Block for .NET topic: “Data Access Application Block Overview.”
The Data Access Application Block is a Microsoft .NET Framework component that contains optimized data access code that can help you do the following:Call stored procedures. Issue SQL text commands against a SQL Server database. The Data Access Application Block returns the SqlDataReader object, the DataSet object, and the XmlReader object. You can use the Data Access Application Block as a building block in your own .NET Framework-based application to reduce the quantity of custom code that you must create, test, and maintain.
Resolution
“Data Access Application Block Overview”contains the following sections: Introduction
The Data Access Application Block encapsulates performance best practices and resource management best practices for how to gain access to Microsoft SQL Server databases. You can use the Data Access Application Block as a building block in your own .NET Framework-based application. The Data Access Application Block reduces the quantity of custom code that you must create, test, and maintain. The Data Access Application Block helps you to do the following: Call stored procedures or SQL text commands.Specify parameter details.Return the SqlDataReader object, the DataSet object, and the XmlReader object.Use strongly typed datasets.What Does the Data Access Application Block Include?
The Data Access Application Block component includes the Microsoft Visual Basic .NET source code or the Microsoft Visual Basic 2005 source code and the Microsoft Visual C# .NET source code or the Microsoft Visual C# 2005 source code for the Data Access Application Block. It also includes a Quick Start Samples client application in each language that you can use to test common scenarios. The sample can help you to better understand how the Data Access Application Block works. You can also customize the source code to fit your requirements.Downloading and Installing the Data Access Application Block
This section discusses how to download and to install the Data Access Application Block. A Microsoft Windows Installer file that contains the signed Data Access Application Block assembly and the comprehensive documentation is available. The install process creates a Microsoft Application Block for .NET menu on your Programs menu. The Data Access menu that appears on the Microsoft Application Block for .NET menu includes options to start the documentation and to start the Data Access Application Block Visual Studio .NET or Visual Studio 2005 solution.Using the Data Access Application Block
This section discusses how to use the Data Access Application Block to run database commands and to manage parameters.Internal Design
This section discusses the internal design of the Data Access Application Block. The Data Access Application Block includes the full source code and a comprehensive guide to its design. This section describes the main implementation details.

Microsoft SQL Server I/O subsystem requirements for the tempdb database

Symptoms
Microsoft SQL Server requires that the I/O subsystem used to store system and user databases fully honor Write-Ahead Logging (WAL) requirements through specific I/O principals.These requirements are necessary in order to honor the ACID properties of transactions: Atomic, Consistent, Isolated, and Durable.Details about I/O subsystem compliance requirements are provided in the following references:SQL Server 2000 I/O basics
http://technet.microsoft.com/en-us/library/cc966500.aspx(http://technet.microsoft.com/en-us/library/cc966500.aspx)Note This article also applies to SQL Server 2005.SQL Server 7.0 and SQL Server 2000 logging and data storage algorithms extend data reliability
http://support.microsoft.com/default.aspx?scid=kb;en-us;230785(http://support.microsoft.com/default.aspx?scid=kb;en-us;230785)The following list is a quick summary of the requirements:Write ordering must be maintained.Dependent write consistency must be maintained.Writes must always be secured in/on stable media.Torn I/O prevention must occur.Durability maintenance remains critical for all other databases but may be relaxed for the tempdb database. The following table summarizes several of the critical I/O requirements for SQL Server databases.
Collapse this tableExpand this table
I/O requirementBrief descriptionSystem or usertempdbWrite ordering
Dependent write consistencyThe ability of the subsystem to maintain the correct order of write operations. This can be especially important for mirroring solutions, group consistency requirements, and SQL Server WAL protocol use.RequiredRecommendedRead after writeThe ability of the subsystem to service read requests with the latest data image when the read is issued after any write is successfully completed.RequiredRequiredSurvival across outageThe ability for data to remain fully intact (Durable) across an outage, such as a system restart.RequiredNot applicableTorn I/O preventionThe ability of the system to avoid splitting individual I/O requests.RequiredRecommendedSector rewriteThe sector can only be written in its entirety and cannot be rewritten because of a write request on a nearby sector.* Discouraged, only permitted if transactional* Discouraged, only permitted if transactionalHardened dataThe expectation that when a write request or a FlushFileBuffers operation is successfully completed, data has been saved to stable media.RequiredNot applicablePhysical sector alignment and sizeSQL Server interrogates the data and log file storage locations.All devices are required to support sector attributes permitting SQL Server to perform writes on physical sector-aligned boundaries and in multiples of the sector size.RequiredRequired* Transactional sector rewrites involve fully logged operations by the subsystem permitting a sector to be fully moved, replaced, or rolled back to the original image.These rewrites are typically discouraged because of the additional overhead required to perform such actions.An example of this would be a defragmentation utility that is moving the file data.The original sector in the file cannot be replaced with the new sector location until the new sector and data are completely secured.The remapping of the sector must occur in a transactional manner so that any failure, including a power failure, causes the re-establishment of the original data.Make sure that you have locking mechanisms available during this kind of process to prevent invalid data access, thereby upholding the other tenants of SQL Server I/O.
Survival across outageThe tempdb database is a scratch area for SQL Server and is rebuilt on every SQL Server startup.The initialization supersedes any need for data to survive a restart.
Transactional sector rewrite operationsTo guarantee the success of the recovery processes, such as rollback and crash recovery, the log records must be correctly stored on stable media before the data page is stored and cannot be rewritten without honoring transactional properties.This requires the subsystem and SQL Server to maintain specific attributes, such as write ordering, sector aligned and sized writes, and other such I/O safety attributes outlined in the previously-mentioned documents.For the tempdb database, the crash recovery is unnecessary because the database is always initialized during SQL Server startup. However, the tempdb database still requires rollback capabilities.Therefore, some attributes of the WAL protocol can be relaxed.
The storage location for the tempdb database must act in strict accordance with established disk drive protocols.In all ways, the device on which the tempdb database is stored must appear and act as a physical disk providing read after write capabilities.Transaction sector rewrite operations may be an additional requirement of specific implementations.For example, SQL Server does not support database modifications by using NTFS file system compression because NTFS compression can rewrite sectors of the log that have already been written and considered hardened.A failure during this type of rewrite can cause the database to be unusable, damaging data thatSQL Server already considered secure.
Note SQL Server 2005 extended support or compression to read only databases and file groups.See the SQL Server 2005 Books Online for complete details.
Transactional sector rewrite operations are pertinent to all SQL Server databases that include the tempdb database.A growing variety of extended storage technologies use devices and utilities that can rewrite data that SQL Server considers secure.For example, some of the emerging technologies perform in-memory caching or data compression.In order to avoid severe database damage, any sector rewrite must have full transactional support in such a way that if a failure occurs, the data is rolled back to the previous sector images. Thisguarantees that SQL Server is never exposed to an unexpected interruption or data damage condition.
You may be able to put the tempdb database on specialty subsystems, such as RAM disks, solid state, or other high speed implementations that cannot be used for other databases.However, the key factors presented in the “More Information” section must be considered when you evaluate these options.
Resolution
Several factors should be carefully studied when you evaluate the storage location of the tempdb database. For example, the tempdb database usage involves, but is not limited to, memory footprint, query plan, and I/O decisions.The appropriate tuning and implementation of the tempdb database can improve the scalability and responsiveness of a system.This section discusses the key factors in determining the storage needs for the tempdb database.
High speed subsystemsThere are various high speed subsystem implementations available on the market that provide SQL Server I/O subsystem protocol requirements but that do not provide durability of the media.
Important Always confirm with the product vendor to guarantee full compliance with SQL Server I/O needs.
A RAM disk is one common example of such an implementation.RAM disks install the necessary drivers andenable part of the main RAM disk to appear as and function like any disk drive that is attached to the system.All I/O subsystems should provide full compliance with the SQL Server I/O requirements. However, it is obvious that a RAM disk is not durable media.Therefore, an implementation such as a RAM disk may only be used as the location of the tempdb database and cannot be used for any other database.
Keys to consider before implementation and deploymentThere are various points to consider before deployment of the tempdb database on this kind of subsystem.This section uses a RAM disk as the basis for discussion, but similar outcomes occur in other high speed implementations. I/O safetyCompliance of read after write and transactional sector writes is a must.Never deploy SQL Server on any system that does not fully support the SQL Server I/O requirements, or you risk damage and loss of your data. Pages already cached (Double RAM cache)Temporary tables are like all other tables in a database.They are cached by the buffer pool and handled by lazy write operations.Storing temporary table pages on a RAM disk causes double RAM caching, one in the buffer pool and one on the RAM disk. This directly takes away from the buffer pool’s total possible size and generally decreases the performance of SQL Server. Giving up RAMThe RAM disk designates a part of main RAM as the name implies.There are several implementations of RAM disks and RAM-based files caches available. Some alsoenable physical I/O backing operations.The key element of the RAM-based file cache is that it directly takes away from the physical memory that can be used by SQL Server.Always have strong evidence that adding a RAM-based file cache improves the application performance and does not decrease other query or application performance. Tune firstAn application should tune to remove unnecessary and unwanted sorts and hashes that could cause the use of the tempdb database.Many times the addition of an index can remove the need for the sort or hash in the plan completely, leading to optimal performance without requiring the use of the tempdb database.Possible benefit pointsThe benefits of putting the tempdb database on a high speed system can only be determined through rigorous testing and measurements of the application workloads.The workload has to be studied carefully for the characteristics that the tempdb database may benefit from, and the I/O safety must be confirmed before deployment.
The sort and hash operations work together with the SQL Server memory managers to determine the size of the in-memory scratch area for each sort or hash operation.As soon as the sort or hash data exceeds the allocated in-memory scratch area, data may be written to the tempdb database.This algorithm has been expanded in SQL Server 2005, reducing the tempdb database usage requirements over earlier versions of SQL Server.For example, by using a pure forced sort of a table, no indexes, descending order, and the same hardware configuration, SQL Server 2005 shows noticeable improvements over SQL Server 2000.
Caution SQL Server is designed to account for memory levels and current query activities when making query plan decisions that involve the use of tempdb database operations.Therefore, the performance gains vary significantly based on workloads and application design.We strongly recommend that you complete testing with the preferred solution to determine possible gains and evaluate I/O safety requirements before such a deployment.
SQL Server uses the tempdb database to handle various activities involving sorts, hashes, the row version store, and temp tables: Temporary tables are maintained by the common buffer pool routines for data pages and generally do not exhibit performance benefits from specialty subsystem implementations.The tempdb database is used as a scratch area for hashes and sorts. Reducing I/O latency for such operations may be beneficial.However, know that adding an index to avoid a hash or a sort may provide a similar benefit.Run baselines with and without the tempdb database stored on the high speed subsystem to compare benefits.Part of the testing should include queries against the user database that do not involve sorts, hashes, or temporary tables, and then confirm that these queries are not adversely affected.When you evaluate the system, the following performance indicators can be helpful.
Collapse this tableExpand this table
IndicatorDescription/usagePage reads and writesImproving the performance of the tempdb database I/Os may change the rate of page reads and writes for the user databases because of the reduced latency associated with the tempdb database I/O. For user database pages, the overall number should not vary across the same workload.Physical read and write bytes to the tempdb databaseIf moving the tempdb database to a device, such as a RAM disk, increases the actual I/O for the tempdb database, it indicates that the memory taken away from the buffer pool is causing increased tempdb database activity to occur. This pattern is an indicator that the page life expectancy of database pages may also be affected in a negative way.Page life expectancyA decline in page life expectancy can indicate an increase in the physical I/O requirements for a user database.The rate decrease could likely indicate that the memory taken away from the buffer pool is forcing database pages to exit the buffer pool prematurely. Combine with the other indicators and test to fully understand the parameter boundaries.Overall throughput
CPU usage
Scalability
Response timeThe primary goal of a tempdb database configuration change is to increase the overall throughput.Your testing should include a mix of repeatable workloads that can be scaled out to determine how throughput is affected.
Something like a compression-based RAM disk implementation may work well with 10 users. However,with increased workload, this may push CPU levels beyond desired levels and have negative effects on response time when the workloads are high.True stress tests and future load prediction tests are strongly encouraged.Work files and work table creation actionsIf moving the tempdb database to a device, such as a RAM disk, changes the query plan by increasing the number or size of work files or work tables, it indicates that the memory taken away from the buffer pool is causing increased tempdb database activity to occur. This pattern is an indication that the page life expectancy of database pages may also be affected in a negative way.Transactional sector rewrite exampleThe following example elaborates the data security that isrequired by SQL Server databases.
Assume a RAM disk vendor uses an in-memory compression implementation.The implementation must be correctly encapsulated by providing the physical appearance of the file stream as if the sector was aligned and sized so SQL Server is unaware and correctly secured from the underlying implementation.Look at the compression example closer.
Collapse this tableExpand this table
ActionSector 1 is written to the device and is compressed to save space.Sector 2 is written to the device and is compressed with sector 1 to save space. The device may perform the following actions to help secure sector 1’s data when it is combined with sector 2’s data.
Collapse this tableExpand this table
ActionBlock all writes to sectors 1 and 2.Uncompress sector 1 into a scratch area, leaving current sector 1 storage as the active data to be retrieved.Compress sectors 1 and 2 into a new storage format.Block all reads and writes of sectors 1 and 2.Exchange old storage for sectors 1 and 2with new storage.If the exchange attempt fails (rollback):Restore the original storage forsectors 1 and 2.Remove the sectors 1 and 2 combined data from the scratch area.Fail the sector 2 write operation.Unblock reads and writes for sectors 1 and 2.The ability to provide locking mechanisms around the sector modifications and roll back the changes when the sector exchange attempt fails is considered transitionally compliant.For implementations that use physical storage for extended backing, it would include the appropriate transaction log aspects to help secure and roll back changes that were applied to the on-disk structures to maintain the integrity of the SQL Server database files.
Any device that enables the rewrite of sectors must support the rewrites in a transactional way so that SQL Server is not exposed to data loss.
Note The instance of SQL Server is restarted when online I/O and rollback failures occur in the tempdb database. Be careful when you move the tempdb databaseBe careful when you movethe tempdb database because if the tempdb database cannot be created, SQL Server will not start.If the tempdb database cannot be created, start SQL Server by using the (-f) startup parameter and move the tempdb database to a valid location.
To change the physical location of the tempdb database, follow these steps:Use the ALTER DATABASE statement and the MODIFY FILE clause to change the physical file names of each file in the tempdb database to refer to the new physical location, such as the new disk.

Alter database tempdb modify file (name = tempdev, filename = ‘C:\MyPath\tempdb.mdf’)Alter database tempdb modify file (name = templog, filename = ‘C:\MyPath\templog.ldf’)Stop and then restart SQL Server.Partner product certifications are not a guaranty of compatibility or safetyA third-party product or a particular vendor can receive a Microsoft logo certification.However, partner certification or a specific Microsoft logo does not certify compatibility or fitness for a particular purpose in SQL Server.SupportIf you use a subsystem with SQL Server that supports the I/O guarantees for transactional database use as described in this article, Microsoft will provide support for SQL Server and SQL Server-based applications. However, issues with, or caused by, the subsystem will be referred to the manufacturer.
For tempdb database-related issues, Microsoft Support Services will ask you to relocate the tempdb database.Contact your device vendor to verify that you have correctly deployed and configured the device for transactional database use.
Microsoft does not certify or validate that third-party products work correctly with SQL Server. Additionally, Microsoft does not provide any warranty, guaranty, or statement of any third-party product’s fitness for use with SQL Server.

Key factors to consider when evaluating third-party file cache systems with SQL Server

Symptoms
This article outlines some of the key factors customers should be aware of when evaluating a third-party file caching system.
Third-party file cache implementations may increase performance of Microsoft SQL Server databases when properly implemented. Specific implementations, however, and configurations of these products may leave SQL Server databases at a high risk of data loss.Customers should completely test the configuration to ensure proper data integrity.
Information in this document, including URL and other Internet Web site references, is subject to change without notice.Unless otherwise noted, the companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted in examples herein are fictitious.No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred.Complying with all applicable copyright laws is the responsibility of the user.Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document.Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.
? 2006 Microsoft Corporation. All rights reserved.
Microsoft, Windows, Windows Server, and SQL Server are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.
This article is written specifically for SQL Server but generally applies to the Jet databases used by Active Directory and Exchange Server products as well.
Resolution
This section outlines requirements and provides detailed examples that should be completely discussed with a third-party vendor before deploying any solution. Customers should also take special care to test various recovery scenarios to make sure data integrity is properly maintained.
Input/Output (I/O) requirements of SQL ServerAny SQL Server database or backup file requires storage fundamentals supporting the Write-Ahead Logging (WAL) protocol. These fundamentals are outlined in the following articles:
SQL Server 2000 I/O basics
http://technet.microsoft.com/en-us/library/cc966500.aspx(http://technet.microsoft.com/en-us/library/cc966500.aspx)Note The article also applies to SQL Server 2005.
230785?(http://support.microsoft.com/kb/230785/) SQL Server 7.0, SQL Server 2000, and SQL Server 2005 logging and data storage algorithms extend data reliabilityThe following is a list of some important requirements: Write ordering must be maintained. Dependent write consistency must be maintained.Writes must always be secured in or on stable media. Torn I/O prevention must occur.
Partner product certifications are not a guarantee of compatibility or safetyA third-party product or a particular vendor can receive a Microsoft logo certification. However, partner certification or a specific Microsoft logo does not certify compatibility or fitness for a particular purpose for SQL Server, Exchange Server, or Active Directory.
FILE_FLAG_WRITETHROUGH and FILE_FLAG_NO_BUFFERINGMicrosoft database products specifically use the write-through and no buffering flags when opening database files to prevent data loss.Any write request to these files must be secured to stable media. Otherwise, data loss can occur.Listed below are specific examples that file system caches may expose:Write combining and write reordering
To reduce physical I/O requests, the non-battery based caches often combine and reorder write operations, immediately breaking the WAL protocol requirements.Block size of I/Os
Similar to the write combining and reordering are block size I/Os. The caches will attempt to complete I/Os based on the I/O path block size. Again, this can provide a performance boost but opens up the database to damage and immediately breaks the WAL protocol requirements.
Talking points and examplesThe following section provides key examples and talking points pertaining to data integrity and safety. It uses power failure as a common point of failure and clarity, but this can often be substituted with various other problems leading to similar database integrity issues.Example 1: Data loss and physical or logical corruptionConsider the following scenario: A log record is written for page 100 in the database.A log record is held in non-battery-based cache, but the database engine is told the log write is complete “secured to stable media”. The database engine considers the LSN hardened and issues write for page 100. Page 100 is also held in non-battery based cache.Commit transaction completes without error.The database engine continues processing as if it successfully committed the writes to stable media. A power outage at this point, however, will result in immediate data loss because the changes never physically existed outside the non-battery backed cache. Crash recovery does not indicate an error because crash recovery does not know about the lost log record and will not attempt to redo the work. Multiple object modification scenarios (e.g. primary key, foreign key inserts) expand on the various types of database damage that can occur.
There are various other issues that could arise with small changes to how the cache handles the I/Os. A brief derivation assumes the transaction was rolled back, but page 100 made it to physical media. Crash recovery again does not know about the log record (never made it to stable media), so page 100 will not receive undo operations during crash recovery, leaving the database logically and possibly physically corrupted.Example 2: Suspect databaseSome vendors allow “opt out of files” and often recommend leaving the database log file (.ldf for SQL Server) opted out of the cache.The “opt out” policy is such that the administrator specifically has to mark files to be ignored by the caching software. Otherwise, the file is automatically included.
This is a poor assumption, as the following examples highlight. Microsoft recommends all database and backup files be opted out of such a cache. The log file is opted out, so writes are getting to stable media. Page 100 is modified. The database engine runs a checkpoint operation. The engine is told all database pages and log records are secure (point in time up to checkpoint considered hardened). However, the data pages are not all stored on or in stable media. The SQL Server database is in recovery mode “SIMPLE,” so checkpoint now truncates the log records. Page 100 that was just check pointed is modified again.This situation has exposed the database to data loss and generally results in a suspect database. Again, if a power outage takes place, crash recovery has no log records because they no longer exist due to truncation.The database engine has no information indicating that database pages are missing data that should have been secured during the checkpoint. Crash recovery attempts to analyze the second modification on page 100 but fails because page 100 was not properly secured to stable media at the time of the checkpoint.
Crash recovery uses the LSN value stored in the page header to determine recovery needs. If the LSN on the page is equal to or newer than that of the log record, recovery does no further work on the page because the page is already consistent with the log record based on LSN comparison.If the LSN on the page is older than that of the log record, recovery needs to perform the proper operations to return the page to the proper state. Recovery fails if recovery has uncovered a missing data condition and cannot properly return the page to its rightful state.From the example, the previous LSN stored in the log record for the second modification of page 100 does not exist in the page header, and there is no prior log record present to redo the page. Therefore, the database is marked as suspect, as recovery cannot safely continue. Example 3: Backups are not valid – Silent backup chain breakExample 2 is just a fraction of these types of problems that could be experienced. For this example, instead of recovery mode “SIMPLE,” let us put the database in “FULL RECOVERY” mode but take regular backups of the log and database. At first, it appears that this would be better because you have an intact log chain and could just execute a restore sequence to correct the problem.
This might not be a valid assumption, as some cache implementations use the “opt out” policy so the backup file or portions of it can be unexpectedly cached.When SQL Server flushes the backup file, SQL Server requires that all writes to the backup media are properly stored on or in stable media using the Win32 API FlushFileBuffers function.Thus, if the cache vendor does not ensure all writes are properly flushed, during the FlushFileBuffers function call, to stable media before the operation successfully completes, the database engine can truncate the log without a secured backup.Again, a power failure at this point results in a condition where the proper log records are missing and can cause crash recovery to fail.What is more important is that crash recovery may not be able to detect this because of the missing log records in the database and the backup chain may be silently damaged. Only when a restore of the backup is attempted will the database engine be able to indicate the backup has been damaged.Example 4: Invalid database statesDatabase files contain dependencies among each other requiring strict write-through and ordering compliance to apply to all of them as a group.Checkpoint, file size changes, differential backups, non-logged operations, and the BULK LOGGED recovery model are among a few of the key database activities that require write through to occur on data files, making policies like opting out only the log file an invalid assumption.Example 5: Snapshot database data loss – May be silentSQL Server 2005 introduces snapshot databases for point in time queries. This uses copy-on-write database technology to help secure a copy of a data page in the snapshot data database before a new modification is made to the data page in the base database. This process requires that the page be secured in the snapshot database before the transaction can continue. If the page is not secured on or in stable media, data integrity problems will persist. The snapshot database does not contain a transaction log, so the write of the page is critical. If something like a power outage occurred, it may be possible that the main database page has been changed but the snapshot does not reflect the previous image because the cached write was lost.
How to configureHow to configure a product providing file cache from something like non-battery backed cache is specific to the vendor implementation.A few rules, however, can be applied: All writes must be completed in or on stable media before the cache indicates to the operating system that the I/O is finished. Data can be cached as long as a read request serviced from the cache returns the same image as located in or on stable media.These rules essentially mean that the non-battery backed cache may be effective for read operations but should not be used for write requests. With the proper configuration, this may provide a performance gain for the database engine. This should, however, be tested carefully, because setting aside something like RAM that could be used by SQL Server may degrade overall performance. SQL Server may be able to use the extra memory with more precision than a generic cache mechanism.
Read-only databasesRead-only databases may be a good example where these types of products excel.If the database was first created and stored on or in stable media to ensure data integrity, the ALTER DATABASE statement used to mark the database READ ONLY, and the database subsequently assigned to the caching mechanism, performance gains may be encountered.Some implementations keep compressed images of the database pages in the cache, allowing more physical data to be retrieved from the cache and reducing physical I/O.
CautionThe database should never be made READ WRITE when assigned to a cache that does not uphold the WAL protocol.
SecurityIntroducing a cache, such as the RAM-based file system cache, introduces another “in-memory” location for data. Products such as a database engine may assume critical data has been stored in or on stable media and properly retain access control list (ACL) protections. The RAM-based cache could expose the data to a set of security issues that are unique compared with stable media. For example, if the application is designed to use something like the SecureZeroMemory function every time that it has finished using critical information, the application has an expectation that the data no longer exists in RAM.However, if a form of the data can remain cached when the application expected it to be in or on stable media, it could alter the security considerations.
Data integrity checksMicrosoft always recommends a strong and clear data integrity strategy. This should include, but is not limited to, restoring backups and regular DBCC CHECKDB operations on both the production and the restored database.
Microsoft also recommends increasing the frequency of these safety tests when evaluating and implementing changes to the environment or if any concerns arise pertaining to the stability of the environment.
For more information about how to use the SQLIOStress utility, click the following article number to view the article in the Microsoft Knowledge Base:
231619?(http://support.microsoft.com/kb/231619/) How to use the SQLIOStress utility to stress a disk subsystem such as SQL Server
The TEMPDB databaseIt is possible to locate the TEMPDB database on certain caching systems.Several factors should be carefully considered and tested when evaluating the storage location of the TEMPDB database in this configuration.The following Microsoft Knowledge Base article outlines the I/O requirements, associated support boundaries, and possible performance gains.
917047?(http://support.microsoft.com/kb/917047/) Microsoft SQL Server I/O sub-system requirements for the TEMPDB database
SupportMicrosoft SQL Server Support will assist customers, using standard data recovery techniques. If products installed on the computer draw data integrity into question, Microsoft SQL Server, Active Directory and Exchange Support may ask that the product be uninstalled and will not engage in root cause analysis until such time the problem can be reproduced without said product.
Microsoft does not certify or validate that third-party products work correctly with SQL Server. Additionally, Microsoft does not provide any warranty, guarantee, or statement of any third-party product’s fitness for use with SQL Server.