Меню

Как проверить таблицу sql на ошибки

Программа mysqlcheck используется для проверки целостности (-c, -m, -C), восстановления (-r), анализа (-a) или оптимизации (-o) таблиц базы данных MySQL. Некоторые опции (например -e и -q) могут использоваться одновременно.

Не все опции поддерживаются различными движками MySQL. Опции -c, -r, -a и -o взаимоисключаемые, что означает, что будет применена последняя указанная опция.

Если не указано ничего, то будет применена опция -c. Альтернативами (синонимами) являются:

mysqlrepair: опция по умолчанию -r
mysqlanalyze: опция по умолчанию -a
mysqloptimize: опция по умолчанию -o

Использование:

mysqlcheck [OPTIONS] database [tables]

или:

 mysqlcheck [OPTIONS] --databases DB1 [DB2 DB3...]

или

mysqlcheck -uлогин -pпароль [--auto-repair] [--check] [--optimize] [--all-databases] [имя_базы_данных]

Опции:

-A, --all-databases

Проверить все базы данных. Аналогична опции —databases, если указать все базы данных.

-1, --all-in-1

Вместо выполнения запросов для каждой таблицы в отдельности выполнить все запросы в одном отдельно для каждой таблицы. Имена таблиц будут представлены в виде списка имен, разделенных запятой.

-a, --analyze

Анализировать данные таблицы.

--auto-repair

Если проверенная таблица повреждена, автоматически восстановить ее. Исправления будут произведены после проверки всех таблиц, если были обнаружены повреждения.

-#, --debug=...

Выводит информацию журнала отладки. Часто используется следующий набор параметров: ‘d:t:o,filename’

--character-sets-dir=...

Директория, где находятся установки символов.

-c, --check

Проверить таблицу на наличие ошибок.

-C, --check-only-changed

Проверить только таблицы, измененные со времени последней проверки или некорректно закрытые.

--compress

Использовать сжатие данных в протоколе сервер/клиент.

-?, --help

Вывести данную вспомогательную информацию и выйти из программы.

-B, --databases

Проверить несколько баз данных. Обратите внимание на разницу в использовании: в этом случае таблицы не указываются. Все имена аргументов рассматриваются как имена баз данных.

--default-character-set=...

Установить набор символов по умолчанию.

-F, --fast

Проверить только базы данных, которые не были закрыты должным образом.

-f, --force

Продолжать даже при получении ошибки SQL.

-e, --extended

При использовании данного параметра совместно с CHECK TABLE можно быть уверенным в целостности таблицы. Если же использовать этот параметр с REPAIR TABLE, запустится расширенное восстановление таблицы.

-h, --host=...

Хост базы данных.

-m, --medium-check

Быстрее, чем —extended-check, но находит только 99,99 процентов всех ошибок.

-o, --optimize

Оптимизировать таблицу.

-p, --password[=...]

Используемый пароль при подключении к серверу. Если пароль не указан, у пользователя запрашивается пароль с терминала.

-P, --port=...

Номер порта, используемого для подключения по TCP/IP.

--protocol=(TCP | SOCKET | PIPE | MEMORY)

Для указания протокола соединения, который надлежит использовать.

-q, --quick

При использовании данной опции совместно с CHECK TABLE предотвращается сканирование строк для корректировки неправильных связей. Это наиболее быстрый метод проверки. Если же использовать этот параметр с REPAIR TABLE, программа попытается восстановить только систему индексов. Это наиболее быстрый метод восстановления таблицы.

-r, --repair

Может исправить почти все, за исключением уникальных ключей, имеющих дубликаты.

-s, --silent

Выводить только сообщения об ошибках.

-S, --socket=...

Файл сокета, используемый для подсоединения.

--tables

Перекрывает опцию —databases (-B).

-u, --user=#

Имя пользователя MySQL, если этот пользователь в данное время не является активным.

-v, --verbose

Вывести информацию о различных этапах.

-V, --version

Вывести информацию о версии и выйти из программы.

Free download Stellar Repair for MS SQL

DBCC CHECKTABLE is a database console command (dbcc) statement that can perform integrity checks on table structure and pages. Before discussing how to use the DBCC CHECKTABLE command, let’s have a brief overview of it.

A Brief Overview of DBCC CHECKTABLE

As a SQL user or database administrator, you must have used the DBCC CHECKDB command to check for database integrity and repair corrupted databases.

Quick Solution: While DBCC CHECKTABLE can help repair specific tables, it cannot recover deleted data. Use SQL Repair Software to avoid the risk of losing deleted table records from the SQL database. The software also helps recover all the objects from SQL database MDF and NDF files, maintaining data integrity. Try the demo version of the software to ascertain its functionality.

DBCC CHECKTABLE has almost the same syntax and performs the same operations as DBCC CHECKDB.

DBCC Checktable Syntax

DBCC CHECKTABLE ( ‘table_name’ | ‘view_name’
        [ , NOINDEX
            | index_id
            | { REPAIR_ALLOW_DATA_LOSS | REPAIR_FAST | REPAIR_REBUILD }
        ]
    ) [ WITH { [ ALL_ERRORMSGS | NO_INFOMSGS ]
                    [ , [ TABLOCK ] ]
                    [ , [ ESTIMATEONLY ] ]
                    [ , [ PHYSICAL_ONLY ] ]
                }
        ]

The CheckTable command checks the integrity of one table at a time. The DBCC CHECKDB command, on the other hand, helps check the integrity of all the objects in a database.

DBCC CHECKDB vs DBCC CHECKTABLE

Note: You need to run DBCC Checkdb to perform DBCC CHECKTABLE on all tables in a database.

Further, the CheckTable command, unlike DBCC CHECKDB, follows a more drilled-down approach to test the specified table for the following:

  • Index and data pages are linked correctly.
  • The sort order of indexes is correct.
  • There is consistency in Pointers.
  • Validate the data on each page is reasonable.
  • Every row in the db table has a similar row in each non-clustered index.
  • A partitioned table or index contains a row that is in the correct partition.
  • There should be link-level consistency between the file system and table when storing varbinary(max) data in the file system.

Before proceeding further, let’s find out if the database table is corrupted. If you’re lucky enough, you may receive an error indicating SQL Server table corruption. If not, check the next section to know how to check for table corruption.

How to Check for SQL Table Corruption?

You can check for corruption in a SQL table by checking for bad pages in suspect_pages table. The suspect_pages table is stored in the msdb db.

Execute the following query to look for bad pages:

SELECT * From msdb.dbo.suspect pages

Note: The above query might not always result in correct results as it includes pages that are marked corrupted, and only the corrupted pages that have been accessed are classified as marked. And so, you must include the DBCC CHECKDB command to detect the undetected issues thoroughly. The checkdb command helps find out the logical and physical integrity of all the database objects. If the query returns zero rows, it means that there are no corrupt pages.

Using DBCC CHECKTABLE Command on SQL Server Database Table

There are different uses of DBCC CHECKTABLE. Let’s examine its primary uses one by one.

Using DBCC CHECKTABLE to Perform Consistency Checks

Note: In the following queries, we will be using ‘Table1’ named table in the Testdbdb database. Make sure to replace ‘Table1’ with the name of your table. Also, change the Testdb database with your db name.

  1. Check for Data Page Integrity

The following query helps check data page integrity of an individual table:

USE Testdb
GO
DBCC CHECKTABLE (‘Table1’)

  1. Performing Logical Consistency Checks on Indexes

Unless NOINDEX is included, the DBCC CHECKTABLE command helps check both the physical and logical consistency of a single table and its non-clustered indexes. However, the checktable command only performs physical consistency checks on the indexed view, XML index, and spatial indexes. But, using the following command can help you Testdb the logical consistency for indexed view, XML, and spatial indexes:

USE Testdb
GO
DBCC CHECKTABLE (‘Table1’) WITH EXTENDED_LOGICAL_CHECKS,NO_INFOMSGS, ALL_ERRORMSGS;

  1. Performing Physical Consistency Check

Running the DBCC CHECKTABLE command with the ‘PHYSICAL_ONLY’ option checks the table’s physical consistency and won’t perform any logical checks. Using this option helps reduce run-time and resource usage of DBCC CHECKTABLE.

Essentially, the PHYSICAL_ONLY option reads and checks the integrity of every page. It also helps detect torn pages, checksum failures, and common hardware failures.

Use the following query when you want to bypass all the logical checks (and limit performing check on page structure):

Note: You cannot run DBCC CHECKTABLE to perform any REPAIR operation when using the PHYSICAL_ONLY command.

USE Testdb
GO
DBCC CHECKTABLE (‘Table1’) WITH PHYSICAL_ONLY;

  1. Consistency Check With NOINDEX:
    The query below helps detect errors in a database table but skips performing intensive checks of non-clustered indexes:

    USE Testdb
    GO
    DBCC CHECKTABLE (‘Table1’,NOINDEX)

    1. Consistency Check With Lock

    Use the following command to place a shared table lock on the table instead of using the internal database snapshot:

    USE Testdb
    GO
    DBCC CHECKTABLE (‘Table1’) WITH TABLOCK,NO_INFOMSGS, ALL_ERRORMSGS;

    1. Checking Consistency of a Specific Index

    The following command can be used to run DBCC CHECKTABLE command for a specific index:

    USE Testdb
    GO
    DECLARE @IndexId int;
    SET @IndexId = (SELECT index_id
                  FROM sys.indexes
                  WHERE object_id = OBJECT_ID(‘Table1’)
                        AND name = ‘Index_Table1’);
    DBCC CHECKTABLE (‘Table1’,@IndexId);

    Using DBCC CHECKTABLE to Fix Table Errors

    If DBCC CHECKTABLE reports any consistency errors in a table, you must first try to restore the data from a known good backup. However, if the backup is not up to date or corrupted, you will need to run DBCC CHECKTABLE with Repair.

    Read this: How to Recover SQL Server Database from a Corrupt Backup File?

    Note: If you must use Repair, run the DBCC CHECKTABLE command without a repair option to find which repair level you should use. If you choose to use the Repair_Allow_Data_Loss option, make sure to back up your db first.

    1. Fix Table Errors using Repair Options
    • Repair Table using DBCC CHECKTABLE with REPAIR_REBUILD

    You can use the DBCC CHECKTABLE command to fix errors in the non-clustered indexes in a SQL table by using the below command:

    Note: The REPAIR_REBUILD operation does not correct any errors containing filestream data.

    USE Testdb
    GO
    ALTER DATABASE Testdb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
    GO
    DBCC CHECKTABLE (‘Table1,REPAIR_REBUILD) WITH NO_INFOMSGS, ALL_ERRORMSGS;
    GO
    ALTER DATABASE Testdb SET MULTI_USER;

    • Repair Table using DBCC CHECKTABLE with REPAIR_ALLOW_DATA_LOSS

    You can run the DBCC CHECKTABLE command to fix corruption in the table by using the following command.

    Note: The REPAIR_ALLOW_DATA_LOSS option, as the name implies, can lead to data loss.

    USE Testdb
    GO
    ALTER DATABASE [Testdb] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
    GO
    DBCC CHECKTABLE (‘Table1’, REPAIR_ALLOW_DATA_LOSS) WITH NO_INFOMSGS, ALL_ERRORMSGS;
    GO
    ALTER DATABASE [Testdb] SET MULTI_USER;

    Note: After running DBCC CHECKTABLE with the repair options ‘REPAIR_REBUILD’ or ‘REPAIR_ALLOW_DATA_LOSS’, it is recommended that you must run the DBCC CHECKCONSTRAINTS command. This is because the repair options do not consider any constraints on or between SQL database tables.

    End Note

    If you cannot restore corrupted table data by using the DBCC CHECKTABLE command, or need to recover deleted table records, using a specialized SQL Recovery tool such as Stellar Repair for MS SQL may help. The software helps retrieve all the SQL database components, including table, deleted table records, indexes, views, etc. in a few simple steps. It can be used to recover table data on both Windows and Linux systems, preserving the original table structure and formatting.

title description author ms.author ms.date ms.service ms.subservice ms.topic f1_keywords helpviewer_keywords dev_langs

DBCC CHECKDB (Transact-SQL)

DBCC CHECKDB checks the logical and physical integrity of all the objects in the specified database.

rwestMSFT

randolphwest

12/05/2022

sql

t-sql

language-reference

CHECKDB_TSQL

DBCC_CHECKDB_TSQL

DBCC CHECKDB

CHECKDB

CHECKDB [DBCC statement]

database objects [SQL Server], checking

counting pages

per-index row counts

per-table row counts

DBCC CHECKDB statement

per-table page counts

allocation checks

integrity [SQL Server], database objects

per-index page counts

counting rows

table integrity checks [SQL Server]

row count accuracy [SQL Server]

negative counts

checking database objects

page count accuracy [SQL Server]

TSQL

[!INCLUDE SQL Server SQL Database Azure SQL Managed Instance]

Checks the logical and physical integrity of all the objects in the specified database by performing the following operations:

  • Runs DBCC CHECKALLOC on the database.
  • Runs DBCC CHECKTABLE on every table and view in the database.
  • Runs DBCC CHECKCATALOG on the database.
  • Validates the contents of every indexed view in the database.
  • Validates link-level consistency between table metadata and file system directories and files when storing varbinary(max) data in the file system using FILESTREAM.
  • Validates the [!INCLUDEssSB] data in the database.

This means that the DBCC CHECKALLOC, DBCC CHECKTABLE, or DBCC CHECKCATALOG commands don’t have to be run separately from DBCC CHECKDB. For more detailed information about the checks that these commands perform, see the descriptions of these commands.

DBCC CHECKDB is supported on databases that contain memory-optimized tables but validation only occurs on disk-based tables. However, as part of database backup and recovery, a CHECKSUM validation is done for files in memory-optimized filegroups.

Since DBCC repair options aren’t available for memory-optimized tables, you must back up your databases regularly and test the backups. If data integrity issues occur in a memory-optimized table, you must restore from the last known good backup.

:::image type=»icon» source=»../../includes/media/topic-link-icon.svg» border=»false»::: Transact-SQL syntax conventions

Syntax

DBCC CHECKDB
    [ ( database_name | database_id | 0
        [ , NOINDEX
        | , { REPAIR_ALLOW_DATA_LOSS | REPAIR_FAST | REPAIR_REBUILD } ]
    ) ]
    [ WITH
        {
            [ ALL_ERRORMSGS ]
            [ , EXTENDED_LOGICAL_CHECKS ]
            [ , NO_INFOMSGS ]
            [ , TABLOCK ]
            [ , ESTIMATEONLY ]
            [ , { PHYSICAL_ONLY | DATA_PURITY } ]
            [ , MAXDOP = number_of_processors ]
        }
    ]
]

[!INCLUDEsql-server-tsql-previous-offline-documentation]

Arguments

database_name | database_id | 0

The name or ID of the database for which to run integrity checks. If not specified, or if 0 is specified, the current database is used. Database names must comply with the rules for identifiers.

NOINDEX

Specifies that intensive checks of nonclustered indexes for user tables won’t be performed. This choice decreases the overall execution time. NOINDEX doesn’t affect system tables because integrity checks are always performed on system table indexes.

REPAIR_ALLOW_DATA_LOSS | REPAIR_FAST | REPAIR_REBUILD

Specifies that DBCC CHECKDB repairs the errors found. Use the REPAIR options only as a last resort. The specified database must be in single-user mode to use one of the following repair options.

  • REPAIR_ALLOW_DATA_LOSS

    Tries to repair all reported errors. These repairs can cause some data loss.

    [!WARNING]
    The REPAIR_ALLOW_DATA_LOSS option is a supported feature but it may not always be the best option for bringing a database to a physically consistent state. If successful, the REPAIR_ALLOW_DATA_LOSS option may result in some data loss. In fact, it may result in more data lost than if a user were to restore the database from the last known good backup.

    [!INCLUDEmsCoName] always recommends a user restore from the last known good backup as the primary method to recover from errors reported by DBCC CHECKDB. The REPAIR_ALLOW_DATA_LOSS option isn’t an alternative for restoring from a known good backup. It is an emergency last resort option recommended for use only if restoring from a backup isn’t possible.

    Certain errors, that can only be repaired using the REPAIR_ALLOW_DATA_LOSS option, may involve deallocating a row, page, or series of pages to clear the errors. Any deallocated data is no longer accessible or recoverable for the user, and the exact contents of the deallocated data cannot be determined. Therefore, referential integrity may not be accurate after any rows or pages are deallocated because foreign key constraints are not checked or maintained as part of this repair operation. The user must inspect the referential integrity of their database (using DBCC CHECKCONSTRAINTS) after using the REPAIR_ALLOW_DATA_LOSS option.

    Before performing the repair, you must create physical copies of the files that belong to this database. This includes the primary data file (.mdf), any secondary data files (.ndf), all transaction log files (.ldf), and other containers that form the database including full text catalogs, file stream folders, memory optimized data, and so on.

    Before performing the repair, consider changing the state of the database to EMERGENCY mode and trying to extract as much information possible from the critical tables and save that data.

  • REPAIR_FAST

    Maintains syntax for backward compatibility only. No repair actions are performed.

  • REPAIR_REBUILD

    Performs repairs that have no possibility of data loss. This option may include quick repairs, such as repairing missing rows in nonclustered indexes, and more time-consuming repairs, such as rebuilding an index.

    This argument doesn’t repair errors involving FILESTREAM data.

[!IMPORTANT]
Since DBCC CHECKDB with any of the REPAIR options are completely logged and recoverable, [!INCLUDEmsCoName] always recommends a user use DBCC CHECKDB with any REPAIR options within a transaction (execute BEGIN TRANSACTION before running the command) so that the user can confirm that they want to accept the results of the operation. Then the user can execute COMMIT TRANSACTION to commit all work done by the repair operation. If the user does not want to accept the results of the operation, they can execute a ROLLBACK TRANSACTION to undo the effects of the repair operations.

To repair errors, we recommend restoring from a backup. Repair operations do not consider any of the constraints that may exist on or between tables. If the specified table is involved in one or more constraints, we recommend running DBCC CHECKCONSTRAINTS after a repair operation. If you must use REPAIR, run DBCC CHECKDB without a repair option to find the repair level to use. If you use the REPAIR_ALLOW_DATA_LOSS level, we recommend that you back up the database before you run DBCC CHECKDB with this option.

ALL_ERRORMSGS

Displays all reported errors per object. All error messages are displayed by default. Specifying or omitting this option has no effect. Error messages are sorted by object ID, except for those messages generated from tempdb database.

EXTENDED_LOGICAL_CHECKS

If the compatibility level is 100, introduced in [!INCLUDEsql2008-md], this option performs logical consistency checks on an indexed view, XML indexes, and spatial indexes, where present.

For more information, see Perform logical consistency checks on indexes later in this article.

NO_INFOMSGS

Suppresses all informational messages.

TABLOCK

Causes DBCC CHECKDB to obtain locks instead of using an internal database snapshot. This includes a short-term exclusive (X) lock on the database. TABLOCK will cause DBCC CHECKDB to run faster on a database under heavy load, but will decrease the concurrency available on the database while DBCC CHECKDB is running.

[!IMPORTANT]
TABLOCK limits the checks that are performed; DBCC CHECKCATALOG is not run on the database, and [!INCLUDEssSB] data is not validated.

ESTIMATEONLY

Displays the estimated amount of tempdb space that is required to run DBCC CHECKDB with all the other specified options. The actual database check isn’t performed.

PHYSICAL_ONLY

Limits the checking to the integrity of the physical structure of the page and record headers and the allocation consistency of the database. This check is designed to provide a small overhead check of the physical consistency of the database, but it can also detect torn pages, checksum failures, and common hardware failures that can compromise a user’s data.

A full run of DBCC CHECKDB may take considerably longer to complete than earlier versions. This behavior occurs because:

  • The logical checks are more comprehensive.
  • Some of the underlying structures to be checked are more complex.
  • Many new checks have been introduced to include the new features.

Therefore, using the PHYSICAL_ONLY option may cause a much shorter run-time for DBCC CHECKDB on large databases and is recommended for frequent use on production systems. We still recommend that a full run of DBCC CHECKDB be performed periodically. The frequency of these runs depends on factors specific to individual businesses and production environments.

This argument always implies NO_INFOMSGS and isn’t allowed with any one of the repair options.

[!WARNING]
Specifying PHYSICAL_ONLY causes DBCC CHECKDB to skip all checks of FILESTREAM data.

DATA_PURITY

Causes DBCC CHECKDB to check the database for column values that aren’t valid or out-of-range. For example, DBCC CHECKDB detects columns with date and time values that are larger than or less than the acceptable range for the datetime data type; or decimal or approximate-numeric data type columns with scale or precision values that aren’t valid.

Column-value integrity checks are enabled by default and don’t require the DATA_PURITY option. For databases upgraded from earlier versions of [!INCLUDEssNoVersion], column-value checks aren’t enabled by default until DBCC CHECKDB WITH DATA_PURITY has been run error free on the database. After this, DBCC CHECKDB checks column-value integrity by default. For more information about how CHECKDB might be affected by upgrading database from earlier versions of [!INCLUDEssNoVersion], see the Remarks section later in this article.

[!WARNING]
If PHYSICAL_ONLY is specified, column-integrity checks are not performed.

Validation errors reported by this option can’t be fixed by using DBCC repair options. For information about manually correcting these errors, see Knowledge Base article 923247: Troubleshooting DBCC error 2570 in SQL Server 2005 and later versions.

MAXDOP

Applies to: [!INCLUDEssSQL14] Service Pack 2 and later versions

Overrides the max degree of parallelism configuration option of sp_configure for the statement. The MAXDOP can exceed the value configured with sp_configure. If MAXDOP exceeds the value configured with Resource Governor, the [!INCLUDEssDEnoversion] uses the Resource Governor MAXDOP value, described in ALTER WORKLOAD GROUP. All semantic rules used with the max degree of parallelism configuration option are applicable when you use the MAXDOP query hint. For more information, see Configure the max degree of parallelism Server Configuration Option.

[!WARNING]
If MAXDOP is set to zero then [!INCLUDE ssnoversion-md] chooses the max degree of parallelism to use.

Remarks

DBCC CHECKDB doesn’t examine disabled indexes. For more information about disabled indexes, see Disable Indexes and Constraints.

If a user-defined type is marked as being byte ordered, there must only be one serialization of the user-defined type. Not having a consistent serialization of byte-ordered user-defined types causes error 2537 when DBCC CHECKDB is run. For more information, see User-Defined Type Requirements.

Because the Resource database is modifiable only in single-user mode, the DBCC CHECKDB command can’t be run on it directly. However, when DBCC CHECKDB is executed against the master database, a second CHECKDB is also run internally on the Resource database. This means that DBCC CHECKDB can return extra results. The command returns extra result sets when no options are set, or when either the PHYSICAL_ONLY or ESTIMATEONLY option is set.

Starting with [!INCLUDEssVersion2005] Service Pack 2, executing DBCC CHECKDB no longer clears the plan cache for the instance of [!INCLUDEssNoVersion]. Before [!INCLUDEssVersion2005] Service Pack 2, executing DBCC CHECKDB clears the plan cache. Clearing the plan cache causes recompilation of all later execution plans and may cause a sudden, temporary decrease in query performance.

Perform logical consistency checks on indexes

Logical consistency checking on indexes varies according to the compatibility level of the database, as follows:

  • If the compatibility level is at least 100 (introduced in [!INCLUDEsql2008-md]):
  • Unless NOINDEX is specified, DBCC CHECKDB performs both physical and logical consistency checks on a single table and on all its nonclustered indexes. However, on XML indexes, spatial indexes, and indexed views only physical consistency checks are performed by default.
  • If WITH EXTENDED_LOGICAL_CHECKS is specified, logical checks are performed on an indexed view, XML indexes, and spatial indexes, where present. By default, physical consistency checks are performed before the logical consistency checks. If NOINDEX is also specified, only the logical checks are performed.

These logical consistency checks cross check the internal index table of the index object with the user table that it is referencing. To find outlying rows, an internal query is constructed to perform a full intersection of the internal and user tables. Running this query can have a significant effect on performance, and its progress can’t be tracked. Therefore, we recommend that you specify WITH EXTENDED_LOGICAL_CHECKS only if you suspect index issues that are unrelated to physical corruption, or if page-level checksums have been turned off and you suspect column-level hardware corruption.

  • If the index is a filtered index, DBCC CHECKDB performs consistency checks to verify that the index entries satisfy the filter predicate.
  • If the compatibility level is 90 or less, unless NOINDEX is specified, DBCC CHECKDB performs both physical and logical consistency checks on a single table or indexed view and on all its nonclustered and XML indexes. Spatial indexes aren’t supported.
  • Starting with [!INCLUDE sssql16-md], additional checks on persisted computed columns, UDT columns, and filtered indexes won’t run by default to avoid the expensive expression evaluations. This change greatly reduces the duration of CHECKDB against databases containing these objects. However, the physical consistency check of these objects is always completed. Only when EXTENDED_LOGICAL_CHECKS option is specified, are the expression evaluations performed, in addition to the logical checks that are already present as part of the EXTENDED_LOGICAL_CHECKS option (indexed view, XML indexes, and spatial indexes).

To learn the compatibility level of a database

  • View or change the compatibility level of a database

Internal database snapshot

DBCC CHECKDB uses an internal database snapshot for the transactional consistency needed to perform these checks. This prevents blocking and concurrency problems when these commands are executed. For more information, see View the Size of the Sparse File of a Database Snapshot (Transact-SQL) and the DBCC Internal Database Snapshot Usage section in DBCC (Transact-SQL). If a snapshot can’t be created, or TABLOCK is specified, DBCC CHECKDB acquires locks to obtain the required consistency. In this case, an exclusive database lock is required to perform the allocation checks, and shared table locks are required to perform the table checks.

DBCC CHECKDB fails when run against the master database if an internal database snapshot can’t be created.

Running DBCC CHECKDB against tempdb doesn’t perform any allocation or catalog checks and must acquire shared table locks to perform table checks. This is because, for performance reasons, database snapshots aren’t available on tempdb. This means that the required transactional consistency can’t be obtained.

How DBCC CHECKDB creates an internal snapshot database beginning with SQL Server 2014

  1. DBCC CHECKDB creates an internal snapshot database.

  2. The internal snapshot database is created by using physical files. For example, for a database with database_id = 10 that has three files E:Datamy_DB.mdf, E:Datamy_DB.ndf, and E:Datamy_DB.ldf, the internal snapshot database will be created using E:Datamy_DB.mdf_MSSQL_DBCC11 and E:Datamy_DB.ndf_MSSQL_DBCC11 files. The database_id of the snapshot is database_id + 1. Also note that the new files are created in the same folder using the naming convention <filename.extension>_MSSQL_DBCC<database_id_of_snapshot>. No sparse file is created for the transaction log.

  3. The new files are marked as sparse files at the file system level. The Size on Disk used by the new files will increase based on how much data is updated in the source database during the DBCC CHECKDB command. The Size of the new files will be the same file as the .mdf or .ndf file.

  4. The new files are deleted at the end of DBCC CHECKDB processing. These sparse files that are created by DBCC CHECKDB have the «Delete on Close» attributes set.

[!WARNING]
If the operating system encounters an unexpected shutdown while the DBCC CHECKDB command is in progress, then these files will not be cleaned up. They will take up space, and can potentially cause failures on future DBCC CHECKDB executions. In that case, you can delete these new files after you confirm that there is no DBCC CHECKDB command currently being executed.

The new files are visible by using ordinary file utilities such as Windows Explorer.

[!NOTE]
Prior to [!INCLUDE sssql14-md], named file streams were used instead to create the internal snapshot files. Named file streams are not visible by using ordinary file utilities such as Windows Explorer. Therefore, in [!INCLUDE sssql11-md] and earlier versions, you may encounter error messages 7926 and 5030 when you run the DBCC CHECKDB command for database files located on an ReFS-formatted volume. This is because file streams cannot be created on Resilient File System (RefS). For more information, see Knowledge Base article 2974455: DBCC CHECKDB behavior when the SQL Server database is located on an ReFS volume..

Check and repair FILESTREAM data

When FILESTREAM is enabled for a database and table, you can optionally store varbinary(max) binary large objects (BLOBs) in the file system. When using DBCC CHECKDB on a database that stores BLOBs in the file system, DBCC checks link-level consistency between the file system and database.

For example, if a table contains a varbinary(max) column that uses the FILESTREAM attribute, DBCC CHECKDB will check that there is a one-to-one mapping between file system directories and files and table rows, columns, and column values. DBCC CHECKDB can repair corruption if you specify the REPAIR_ALLOW_DATA_LOSS option. To repair FILESTREAM corruption, DBCC will delete any table rows that are missing file system data.

Best practices

We recommend that you use the PHYSICAL_ONLY option for frequent use on production systems. Using PHYSICAL_ONLY can greatly shorten run-time for DBCC CHECKDB on large databases. We also recommend that you periodically run DBCC CHECKDB with no options. How frequently you should perform these runs depends on individual businesses and their production environments.

Check objects in parallel

By default, DBCC CHECKDB performs parallel checking of objects. The degree of parallelism is automatically determined by the query processor. The maximum degree of parallelism is configured just like parallel queries. To restrict the maximum number of processors available for DBCC checking, use sp_configure. For more information, see Configure the max degree of parallelism Server Configuration Option. Parallel checking can be disabled by using Trace Flag 2528. For more information, see Trace Flags (Transact-SQL).

[!NOTE]
This feature is not available in every edition of [!INCLUDEssNoVersion]. For more information, see parallel consistency check in the RDBMS manageability section of Editions and supported features of SQL Server 2022.

Understand DBCC error messages

After the DBCC CHECKDB command finishes, a message is written to the [!INCLUDEssNoVersion] error log. If the DBCC command successfully executes, the message indicates success and the amount of time that the command ran. If the DBCC command stops before completing the check because of an error, the message indicates that the command was terminated, a state value, and the amount of time the command ran. The following table lists and describes the state values that can be included in the message.

State Description
0 Error number 8930 was raised. This indicates a corruption in metadata that terminated the DBCC command.
1 Error number 8967 was raised. There was an internal DBCC error.
2 A failure occurred during emergency mode database repair.
3 This indicates a corruption in metadata that terminated the DBCC command.
4 An assert or access violation was detected.
5 An unknown error occurred that terminated the DBCC command.

[!NOTE]
[!INCLUDEssNoVersion] records the date and time when a consistency check was run for a database with no errors (or «clean» consistency check). This is known as the last known clean check. When a database is first started, this date is written to the EventLog (EventID-17573) and error log in the following format:

CHECKDB for database '<database>' finished without errors on 2022-05-05 18:08:22.803 (local time). This is an informational message only; no user action is required.

Error reporting

A dump file (SQLDUMP<nnnn>.txt) is created in the [!INCLUDEssNoVersion] LOG directory whenever DBCC CHECKDB detects a corruption error. When the Feature Usage data collection and Error Reporting features are enabled for the instance of [!INCLUDEssNoVersion], the file is automatically forwarded to [!INCLUDEmsCoName]. The collected data is used to improve [!INCLUDEssNoVersion] functionality.
The dump file contains the results of the DBCC CHECKDB command and additional diagnostic output. Access is limited to the [!INCLUDEssNoVersion] service account and members of the sysadmin role. By default, the sysadmin role contains all members of the Windows BUILTINAdministrators group and the local administrator’s group. The DBCC command doesn’t fail if the data collection process fails.

Resolve errors

If any errors are reported by DBCC CHECKDB, we recommend restoring the database from the database backup instead of running REPAIR with one of the REPAIR options. If no backup exists, running repair corrects the errors reported. The repair option to use is specified at the end of the list of reported errors. However, correcting the errors by using the REPAIR_ALLOW_DATA_LOSS option might require deleting some pages, and therefore some data.

Under some circumstances, values might be entered into the database that aren’t valid or out-of-range based on the data type of the column. DBCC CHECKDB can detect column values that aren’t valid for all column data types. Therefore, running DBCC CHECKDB with the DATA_PURITY option on databases that have been upgraded from earlier versions of [!INCLUDEssNoVersion] might reveal preexisting column-value errors. Because [!INCLUDEssNoVersion] can’t automatically repair these errors, the column value must be manually updated. If CHECKDB detects such an error, CHECKDB returns a warning, the error number 2570, and information to identify the affected row and manually correct the error.

The repair can be performed under a user transaction to let the user roll back the changes that were made. If repairs are rolled back, the database will still contain errors and must be restored from a backup. After repairs are completed, back up the database.

Resolve errors in database emergency mode

When a database has been set to emergency mode by using the ALTER DATABASE statement, DBCC CHECKDB can perform some special repairs on the database if the REPAIR_ALLOW_DATA_LOSS option is specified. These repairs may allow for ordinarily unrecoverable databases to be brought back online in a physically consistent state. These repairs should be used as a last resort and only when you can’t restore the database from a backup. When the database is set to emergency mode, the database is marked READ_ONLY, logging is disabled, and access is limited to members of the sysadmin fixed server role.

[!NOTE]
You cannot run the DBCC CHECKDB command in emergency mode inside a user transaction and roll back the transaction after execution.

When the database is in emergency mode and DBCC CHECKDB with the REPAIR_ALLOW_DATA_LOSS clause is run, the following actions are taken:

  • DBCC CHECKDB uses pages that have been marked inaccessible because of I/O or checksum errors, as if the errors haven’t occurred. Doing this increases the chances for data recovery from the database.
  • DBCC CHECKDB attempts to recover the database using regular log-based recovery techniques.
  • If database recovery is unsuccessful because of transaction log corruption, the transaction log is rebuilt. Rebuilding the transaction log may result in the loss of transactional consistency.

[!WARNING]
The REPAIR_ALLOW_DATA_LOSS option is a supported feature of [!INCLUDEssNoVersion]. However, it may not always be the best option for bringing a database to a physically consistent state. If successful, the REPAIR_ALLOW_DATA_LOSS option may result in some data loss.
In fact, it may result in more data lost than if a user were to restore the database from the last known good backup. [!INCLUDEmsCoName] always recommends a user restore from the last known good backup as the primary method to recover from errors reported by DBCC CHECKDB.
The REPAIR_ALLOW_DATA_LOSS option is not an alternative for restoring from a known good backup. It is an emergency last resort option recommended for use only if restoring from a backup is not possible.

After rebuilding the log, there is no full ACID guarantee.

After rebuilding the log, DBCC CHECKDB will be automatically performed and will both report and correct physical consistency issues.

Logical data consistency and business logic enforced constraints must be validated manually.

The transaction log size will be left to its default size and must be manually adjusted back to its recent size.

If the DBCC CHECKDB command succeeds, the database is in a physically consistent state, and the database status is set to ONLINE. However, the database may contain one or more transactional inconsistencies. We recommend that you run DBCC CHECKCONSTRAINTS to identify any business logic flaws and immediately back up the database.
If the DBCC CHECKDB command fails, the database can’t be repaired.

Run DBCC CHECKDB with REPAIR_ALLOW_DATA_LOSS in replicated databases

Running the DBCC CHECKDB command with the REPAIR_ALLOW_DATA_LOSS option can affect user databases (publication and subscription databases) and the distribution database used by replication. Publication and subscription databases include published tables and replication metadata tables. Be aware of the following potential issues in these databases:

  • Published tables. Actions performed by the CHECKDB process to repair corrupt user data might not be replicated:
  • Merge replication uses triggers to track changes to published tables. If rows are inserted, updated, or deleted by the CHECKDB process, triggers don’t fire; therefore, the change isn’t replicated.
  • Transactional replication uses the transaction log to track changes to published tables. The Log Reader Agent then moves these changes to the distribution database. Some DBCC repairs, although logged, can’t be replicated by the Log Reader Agent. For example, if a data page is deallocated by the CHECKDB process, the Log Reader Agent doesn’t translate this deallocation to a DELETE statement; therefore, the change isn’t replicated.
  • Replication metadata tables. Actions performed by the CHECKDB process to repair corrupt replication metadata tables require removing and reconfiguring replication.

If you have to run the DBCC CHECKDB command with the REPAIR_ALLOW_DATA_LOSS option on a user database or distribution database:

  1. Quiesce the system: Stop activity on the database and at all other databases in the replication topology, and then try to synchronize all nodes. For more information, see Quiesce a Replication Topology (Replication Transact-SQL Programming).
  2. Execute DBCC CHECKDB.
  3. If the DBCC CHECKDB report includes repairs for any tables in the distribution database or any replication metadata tables in a user database, remove and reconfigure replication. For more information, see Disable Publishing and Distribution.
  4. If the DBCC CHECKDB report includes repairs for any replicated tables, perform data validation to determine whether there are differences between the data in the publication and subscription databases.

Result sets

DBCC CHECKDB returns the following result set. The values might vary except when the ESTIMATEONLY, PHYSICAL_ONLY, or NO_INFOMSGS options are specified:

 DBCC results for 'model'.
    
 Service Broker Msg 9675, Level 10, State 1: Message Types analyzed: 13.
    
 Service Broker Msg 9676, Level 10, State 1: Service Contracts analyzed: 5.
    
 Service Broker Msg 9667, Level 10, State 1: Services analyzed: 3.
    
 Service Broker Msg 9668, Level 10, State 1: Service Queues analyzed: 3.
    
 Service Broker Msg 9669, Level 10, State 1: Conversation Endpoints analyzed: 0.
    
 Service Broker Msg 9674, Level 10, State 1: Conversation Groups analyzed: 0.
    
 Service Broker Msg 9670, Level 10, State 1: Remote Service Bindings analyzed: 0.
    
 DBCC results for 'sys.sysrowsetcolumns'.
    
 There are 630 rows in 7 pages for object 'sys.sysrowsetcolumns'.
    
 DBCC results for 'sys.sysrowsets'.
    
 There are 97 rows in 1 pages for object 'sys.sysrowsets'.
    
 DBCC results for 'sysallocunits'.
    
 There are 195 rows in 3 pages for object 'sysallocunits'.
    
 There are 0 rows in 0 pages for object "sys.sysasymkeys".
    
 DBCC results for 'sys.syssqlguides'.
    
 There are 0 rows in 0 pages for object "sys.syssqlguides".
    
 DBCC results for 'sys.queue_messages_1977058079'.
    
 There are 0 rows in 0 pages for object "sys.queue_messages_1977058079".
    
 DBCC results for 'sys.queue_messages_2009058193'.
    
 There are 0 rows in 0 pages for object "sys.queue_messages_2009058193".
    
 DBCC results for 'sys.queue_messages_2041058307'.
    
 There are 0 rows in 0 pages for object "sys.queue_messages_2041058307".
    
 CHECKDB found 0 allocation errors and 0 consistency errors in database 'model'.
    
 DBCC execution completed. If DBCC printed error messages, contact your system administrator.

DBCC CHECKDB returns the following result set (message) when NO_INFOMSGS is specified:

 The command(s) completed successfully.

DBCC CHECKDB returns the following result set when PHYSICAL_ONLY is specified:

 DBCC results for 'model'.
    
 CHECKDB found 0 allocation errors and 0 consistency errors in database 'master'.
    
 DBCC execution completed. If DBCC printed error messages, contact your system administrator.

DBCC CHECKDB returns the following result set when ESTIMATEONLY is specified.

 Estimated TEMPDB space needed for CHECKALLOC (KB)
    
 -------------------------------------------------
    
 13
    
 (1 row(s) affected)
    
 Estimated TEMPDB space needed for CHECKTABLES (KB)
    
 --------------------------------------------------
    
 57
    
 (1 row(s) affected)
    
 DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

Requires membership in the sysadmin fixed server role or the db_owner fixed database role.

Examples

A. Check both the current and another database

The following example executes DBCC CHECKDB for the current database and for the [!INCLUDEssSampleDBobject] database.

-- Check the current database.
DBCC CHECKDB;
GO
-- Check the AdventureWorks2019 database without nonclustered indexes.
DBCC CHECKDB (AdventureWorks2019, NOINDEX);
GO

B. Check the current database, suppressing informational messages

The following example checks the current database and suppresses all informational messages.

DBCC CHECKDB WITH NO_INFOMSGS;
GO

See also

  • DBCC (Transact-SQL)
  • View the Size of the Sparse File of a Database Snapshot (Transact-SQL)
  • sp_helpdb (Transact-SQL)
  • System Tables (Transact-SQL)

MyISAM — основная, вернее, одна из главных (наряду с InnoDB) систем хранения данных в СУБД MySQL. При этом MyISAM таблицы повреждаются очень просто — с этим проблем нет никаких. Сложнее все повреждения ликвидировать, хотя это тоже можно сделать довольно быстро. В этом материале объясняется, как можно решить проблему с использованием myisamchk для идентификации проблемы с MyISAM и ее исправления.

Общеизвестно, что при создании таблицы в MySQL, создаются три различных файла: *.frm — формат таблицы, *.MYD (MyData) — хранение данных, *.MYI (MyIndex) — индекс. Для крупных баз данных стоит использовать InnoDB, поскольку здесь есть некоторая схожесть с Oracle и соответствующая функциональность.

В качестве примера демонстрации ошибки будем использовать вот это:

undef error - DBD::mysql::db selectrow_array failed: Table 'attach_data' is
marked as crashed and should be repaired [for Statement "SELECT LENGTH(thedata)
FROM attach_data WHERE id = ?"] at Bugzilla/Attachment.pm line 344
Bugzilla::Attachment::datasize('Bugzilla::Attachment=HASH(0x9df119c)') called

Понятно, что таблица attach_data повреждена, и ее нужно исправить. Таблицу будем исправлять с использованием myisamchk.

1. Определяем все поврежденные таблицы, используя myisamchk

# myisamchk /var/lib/mysql/bugs/*.MYI >> /tmp/myisamchk_log.txt
 
myisamchk: error: Wrong bytesec: 0-0-0 at linkstart: 18361936
MyISAM-table 'attach_data.MYI' is corrupted
Fix it using switch "-r" or "-o"
myisamchk: warning: 1 client is using or hasn't closed the table properly
MyISAM-table 'groups.MYI' is usable but should be fixed
myisamchk: warning: 1 client is using or hasn't closed the table properly
MyISAM-table 'profiles.MYI' is usable but should be fixed

Если указать вывод myisamchk во временный файл, на дисплее будут показаны только имена поврежденных таблиц. А вот в файле /tmp/myisamchk_log.txt будет указано гораздо больше данных включая имена неповрежденных таблиц:

Checking MyISAM file: user_group_map.MYI
Data records:     182   Deleted blocks:       0
- check file-size
- check record delete-chain
- check key delete-chain
- check index reference
- check data record references index: 1

2. Исправляем поврежденные таблицы, используя myisamchk

Для этого используем myisamchk, с опцией -r, как и показано ниже:

# myisamchk -r profiles.MYI
 
- recovering (with sort) MyISAM-table 'profiles.MYI'
Data records: 80
- Fixing index 1
- Fixing index 2

Здесь может появиться сообщение об ошибке: clients are using or haven’t closed the table properly, в случае, если таблицы до сих пор используются каким-либо приложением или другими таблицами. Для того, чтобы избежать появления этой ошибки, стоит завершить mysqld, прежде, чем начать исправление таблиц. Здесь можно использовать FLUSH TABLES.

3. Запускаем проверку и исправлением для всей БД MySQL

# myisamchk --silent --force --fast --update-state /var/lib/mysql/bugs/*.MYI
 
myisamchk: MyISAM file /var/lib/mysql/bugs/groups.MYI
myisamchk: warning: 1 client is using or hasn't closed the table properly
myisamchk: MyISAM file /var/lib/mysql/bugs/profiles.MYI
myisamchk: warning: 1 client is using or hasn't closed the table properly

-s: выводим только ошибки. Можно использовать двойной -s -s, чтобы сделать режим максимально «тихим»;
-f: автоматический перезапуск myisamchk с опцией -r, есть обнаружены ошибки;
-F: проверка только таблиц, которые не были закрыты в нормальном режиме;
-U: отмечаем таблицы, как поврежденные, если обнаружены ошибки.

4. Использование дополнительной памяти для больших БД MySQL

В случае работы с большими БД восстановление может занять несколько часов. Если есть дополнительные ресурсы, их можно использовать для ускорения процесса:

# myisamchk --silent --force --fast --update-state 
--key_buffer_size=512M --sort_buffer_size=512M 
--read_buffer_size=4M --write_buffer_size=4M 
/var/lib/mysql/bugs/*.MYI

5. Использование myisamchk для получения данных о таблице

При необходимости можно получить довольно много данных.

# myisamchk -dvv profiles.MYI
 
MyISAM file:         profiles.MYI
Record format:       Packed
Character set:       latin1_swedish_ci (8)
File-version:        1
Creation time:       2007-08-16 18:46:59
Status:              open,changed,analyzed,optimized keys,sorted index pages
Auto increment key:              1  Last value:                    88
Data records:                   88  Deleted blocks:                 0
Datafile parts:                118  Deleted data:                   0
Datafile pointer (bytes):        4  Keyfile pointer (bytes):        4
Datafile length:              6292  Keyfile length:              6144
Max datafile length:    4294967294  Max keyfile length: 4398046510079
Recordlength:                 2124
 
table description:
Key Start Len Index   Type                     Rec/key         Root  Blocksize
1   2     3   unique  int24                          1         1024       1024
2   5     765 unique  char packed stripped           1         2048       4096
 
Field Start Length Nullpos Nullbit Type
1     1     1
2     2     3                      no zeros
3     5     765                    no endspace

6. Все опции myisamchk

Для того чтобы получить дополнительную информацию по команде, стоит использовать помощь:

# myisamchk —help

Общие опции:

-s: только вывод ошибок;
-v: вывод большего количества информации;
-V: вывод версии и выход;
-w: ждать, если таблица заблокирована.

Опции проверки:

-c: проверка таблиц на ошибки;
-е: очень «грубая» проверка. Стоит использовать только в крайнем случае, если в обычном режиме ошибки не обнаруживаются;
-F: быстрая проверка, проверяются только таблицы, которые не закрывались правильно;
-С: проверка только таблиц, которые изменились со времени последней поверки;
-f: автоматический перезапуск myisamchk с опцией -r, есть обнаружены ошибки;
-i: вывод статистики по проверенным таблицам;
-m: облегченный режим проверки, быстрее, чем обычный, находится 99,99% ошибок;
-U: обновление статуса: пометка таблиц как поврежденных, если обнаруживаются любые ошибки;
-T: не помечать таблицы как проверенные.

Опции исправления:

-B: бэкап файла .MYD, «filename-time.BAK»;
—correct-checksum;
-е: попытка исправления максимального числа строк в файле данных. Кроме того, эта команда находит «мусорные» строки. Не стоит использовать эту команду, если ситуация не безнадежна;
-f: перезапись старых временных файлов;
-r: исправляет почти все, кроме уникальных ключей, которые на самом деле не уникальны;
-n: принудительная сортировка, даже, если временный файл получается очень большим;
-о: использование старого метода восстановления;
-q: быстрое исправление без модификации файла данных;
-u: распаковка файла, запакованного myisampack.

DBCC CHECKTABLE is used to test the consistency of a table or indexed view. The DBCC CHECKTABLE command performs the same operations as the DBCC CHECKDB command for a table in the database.

You may want to read my article “DBCC CHECKDB Command On SQL Server“.

DBCC CHECKTABLE has several different uses. Let’s examine them all one by one:

Consistency Check:

The following command detects logical and physical errors in the TestTable table in the Test database.

USE Test

GO

DBCC CHECKTABLE (‘TestTable’)

Consistency Check With NOINDEX:

The following query detects errors other than non-clustered indexes in the TestTable table.

USE Test

GO

DBCC CHECKTABLE (N‘TestTable’,NOINDEX)

Correct Errors With REPAIR_REBUILD:

You can run the DBCC CHECKTABLE command to correct errors in the non-clustereded indexes in the table by using the following command without any loss of data.

The REPAIR_REBUILD operation does not fix any errors that contain filestream data.

USE Test

GO

ALTER DATABASE Test SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

GO

DBCC CHECKTABLE (N‘TestTable’,REPAIR_REBUILD) WITH NO_INFOMSGS, ALL_ERRORMSGS;

GO

ALTER DATABASE Test SET MULTI_USER;

Correct Errors With REPAIR_ALLOW_DATA_LOSS:

You can run the DBCC CHECKTABLE command to correct all errors in the table with the risk of data loss by using the following command.

USE Test

GO

ALTER DATABASE [Test] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

GO

DBCC CHECKTABLE (N‘TestTable’, REPAIR_ALLOW_DATA_LOSS) WITH NO_INFOMSGS, ALL_ERRORMSGS;

GO

ALTER DATABASE [Test] SET MULTI_USER;

Even if you don’t write ALL_ERRORMSGS at the end of the script, this is the default value. It means to show all errors received for each object.

NO_INFOMSGS at the end of the script means that it does not display informational messages.

NOTE1: After you make sure that the database is suspect, the first thing we need to do before we start the attempt to recover is to get a backup of the suspect database !!!

NOTE2: After running DBCC CHECKTABLE with REPAIR_REBUILD or REPAIR_ALLOW_DATA_LOSS, I recommend that you run the DBCC CHECKCONSTRAINTS command. You can find information about this command in my article “DBCC CHECKCONSTRAINTS Command On SQL Server“.

Logical Consistency Check For Indexed view, XML index, and Spatial Indexes:

By default, the DBCC CHECKTABLE command only tests the physical consistency for indexed view, XML index, and spatial indexes.

You can also use the following command to check the logical consistency for indexed view, XML index, and spatial indexes in tables in the databases with compatibility level SQL Server 2008 and later. You may want to read my article “What is SQL Server Database Compatibility Level and How To Change Database Compatibility Level“.

USE Test

GO

DBCC CHECKTABLE (N‘TestTable’) WITH EXTENDED_LOGICAL_CHECKS,NO_INFOMSGS, ALL_ERRORMSGS;

The DBCC CHECKTABLE command uses internal database snapshot. This means that there is no blocking when you run this command.

You may want to read the article named “What is Database Snapshot On SQL Server”

Consistency Check With Lock:

If you run using the following command, this command puts the shared table lock on the table instead of using the internal database snapshot. You may want to read my article “SQL Server Lock Types“.

USE Test

GO

DBCC CHECKTABLE (N‘TestTable’) WITH TABLOCK,NO_INFOMSGS, ALL_ERRORMSGS;

Calculate Necessary Space For Consistency Check:

If you use the following command, no consistency check is performed. Only the amount of space required in tempdb is calculated so that a consistency test can be performed, and it produces an output as follows.

USE Test

GO

DBCC CHECKTABLE (N‘TestTable’) WITH ESTIMATEONLY,NO_INFOMSGS, ALL_ERRORMSGS;

Estimated TEMPDB space (in KB) needed for CHECKTABLE on database Test = 1.

Only PHYSICAL Consistency Check:

When you run it using the command below, only physical consistency check is performed. It is not done logically.

If you ask me, it doesn’t make sense to run it using this command. Because it doesn’t control its logical consistency. Of course, they offered us such an option to be used in special cases.

With the PHYSICAL_ONLY command, you cannot perform any REPAIR operation.

USE Test

GO

DBCC CHECKTABLE (N‘TestTable’) WITH PHYSICAL_ONLY,NO_INFOMSGS, ALL_ERRORMSGS;

DATA_PURITY Option:

When you run it using the command below, it is checked whether the values of the columns in the tables in the database are compatible with the data type of the column. If your database is SQL Server 2005 or higher, the column values are checked automatically and no DATA_PURITY option is required.

USE Test

GO

DBCC CHECKTABLE (N‘TestTable’) WITH DATA_PURITY,NO_INFOMSGS, ALL_ERRORMSGS;

For faster completion of DBCC CHECKTABLE, you can increase maxdop (max degree of paralellism) from server configurations before running DBCC CHECKTABLE. If your system is an oltp system and consists entirely of small transactions, increasing the maxdop may slow the performance of the running system. Therefore, after increasing the maxdop, you should inspect the system and undo the change in any performance problem. To correctly set the maxdop value, you can use the article “sp_configure (Server-Level Configurations in SQL Server)“.

DBCC CHECKTABLE For an Index:

If you want, you can run the DBCC CHECKTABLE command for just one index. In the script below, we test the clustered index called PK_TestTable in the TestTable table.

USE Test

GO

DECLARE @IndexId int;   

SET @IndexId = (SELECT index_id    

FROM sys.indexes   

WHERE object_id = OBJECT_ID(‘TestTable’)   

AND name = ‘PK_TestTable’);   

DBCC CHECKTABLE (‘TestTable’,@IndexId);

Download PDF

Being day seven of the DBCC Command month at SteveStedman.com, today’s featured DBCC Command is DBCC CHECKTABLE.

Description:

DBCC CheckTable is used to check the structure of a table to verify the integrity of every data page associated with that table, and all of the indexes associated with that table. If you have used DBCC CheckDB, and a problem has been shown with a table, you can use DBCC CheckTable to attempt to correct the problem.

DBCC CHECKTABLE Syntax:

dbcc checktable
(
    { 'table_name' | 'view_name' }
    [ , NOINDEX
    | index_id
    | { REPAIR_ALLOW_DATA_LOSS
    | REPAIR_FAST
    | REPAIR_REBUILD
    } ]
)
    [ WITH
        {
            [ ALL_ERRORMSGS ]
            [ , [ NO_INFOMSGS ] ]
            [ , [ TABLOCK ] ]
            [ , [ ESTIMATEONLY ] ]
            [ , [ PHYSICAL_ONLY ] ]
            [ , [ EXTENDED_LOGICAL_CHECKS  ] ]
        }
    ]

Parameters:

The REPAIR_FAST parameter is only there for reverse compatibility and does nothing.  This was removed in SQL Server 2005.

Example:

The following example….

DBCC CheckTable(Departments);

Which produces the following output indicating success with removal of the corruption.

DBCC results for 'Departments'.
There are 4 rows in 1 pages for object "Departments".
DBCC execution completed. If DBCC printed error messages, contact your 
system administrator.

That is the best case scenario, everything worked fine.   Now we will take a look at what to do if there is corruption.

Example with Corruption:

DBCC CheckTable(Departments);

Produces the following erorr:

Msg 8951, Level 16, State 1, Line 1
Table error: table 'Departments' (ID 245575913). Data row does not 
have a matching index row in the index 'DepartmentsNonClustered' (ID 2). 
Possible missing or invalid keys for the index row matching:

Msg 8955, Level 16, State 1, Line 1
Data row (1:231:0) identified by (id = 1) with index values 'department = 
'aaaping' and parent = NULL and archived = 0 and id = 1'.

Msg 8952, Level 16, State 1, Line 1
Table error: table 'Departments' (ID 245575913). Index row in index 
'DepartmentsNonClustered' (ID 2) does not match any data row. Possible 
extra or invalid keys for:

Msg 8956, Level 16, State 1, Line 1
Index row (1:273:0) with values (department = 'Camping' and parent = NULL
 and archived = 0 and id = 1) pointing to the data row identified by 
(id = 1).
DBCC results for 'Departments'.

There are 4 rows in 1 pages for object "Departments".
CHECKTABLE found 0 allocation errors and 2 consistency errors in table
 'Departments' (object ID 245575913).
repair_rebuild is the minimum repair level for the errors found by DBCC
 CHECKTABLE (dbcc_corruption.dbo.Departments).
DBCC execution completed. If DBCC printed error messages, contact your
 system administrator.

Indicating that the an index, the DepartmentsNonClustered is corrupt.

However when we query the table, all of the data looks fine.

DBCC CheckTable looks good

So to fix the corrupt index, the best option is probably to just drop the index and recreate it. Lets give that a try:

DROP INDEX [DepartmentsNonClustered] ON [dbo].[Departments];
CREATE NONCLUSTERED INDEX [DepartmentsNonClustered] ON [dbo].[Departments]
(
 [department] ASC,
 [parent] ASC,
 [archived] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF,
       DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON,
       ALLOW_PAGE_LOCKS = ON) ON [PRIMARY];
GO

DBCC CheckTable(Departments);

Which produces the following output indicating success with removal of the corruption.

DBCC results for 'Departments'.
There are 4 rows in 1 pages for object "Departments".
DBCC execution completed. If DBCC printed error messages, contact your 
system administrator.

In this case we were lucky, the table itself wasn’t corrupt, it was just an index which was easy enough to drop and recreate. Had the table structure itself, or the clustered index been corrupt that may have required more drastic steps, either restoring from backup, or saving the data we could as shown in my DBCC CheckDB blog article from a few days ago.

Notes:

DBCC CheckAlloc along with DBCC CheckTable for every object in the database are called when DBCC CheckDB is run. Running DBCC CheckAlloc or DBCC CheckTable would be redundant after running DBCC CheckDB.

The REPAIR_FAST parameter is only there for reverse compatibility and does nothing.  This was removed in SQL Server 2005.

For more information see TSQL Wiki DBCC checktable.

DBCC Command month at SteveStedman.com is almost as much fun as building Robotic Dinosaurs.

For more details on DBCC CheckTable see the Database Corruption Challenge

SteveStedman5

Steve and the team at Stedman Solutions are here for all your SQL Server needs.

Contact us today for your free 30 minute consultation..

We are ready to help!

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Как просканировать компьютер на наличие ошибок через командную строку
  • Как проверить стих на ошибки