Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
DBCC SHRINKFILE (Transact-SQL)

Shrinks the size of the specified data or log file for the current database, or empties a file by moving the data from the specified file to other files in the same filegroup, allowing the file to be removed from the database. You can shrink a file to a size that is less than the size specified when it was created. This resets the minimum file size to the new value.

Topic link icon Transact-SQL Syntax Conventions

DBCC SHRINKFILE 
(
    { file_name | file_id } 
    { [ , EMPTYFILE ] 
    | [ [ , target_size ] [ , { NOTRUNCATE | TRUNCATEONLY } ] ]
    }
)
[ WITH NO_INFOMSGS ]
file_name

Is the logical name of the file to be shrunk.

file_id

Is the identification (ID) number of the file to be shrunk. To obtain a file ID, use the FILE_IDEX system function or query the sys.database_files catalog view in the current database.

target_size

Is the size for the file in megabytes, expressed as an integer. If not specified, DBCC SHRINKFILE reduces the size to the default file size. The default size is the size specified when the file was created.

NoteNote

You can reduce the default size of an empty file by using DBCC SHRINKFILE target_size. For example, if you create a 5-MB file and then shrink the file to 3 MB while the file is still empty, the default file size is set to 3 MB. This applies only to empty files that have never contained data.

This option is not supported for FILESTREAM filegroup containers.

If target_size is specified, DBCC SHRINKFILE tries to shrink the file to the specified size. Used pages in the part of the file to be freed are relocated to available free space in the part of the file retained. For example, if there is a 10-MB data file, a DBCC SHRINKFILE operations with a target_size of 8 causes all used pages in the last 2 MB of the file to be reallocated into any unallocated pages in the first 8 MB of the file. DBCC SHRINKFILE does not shrink a file past the size needed to store the data in the file. For example, if 7 MB of a 10-MB data file is used, a DBCC SHRINKFILE statement with a target_size of 6 shrinks the file to only 7 MB, not 6 MB.

EMPTYFILE

Migrates all data from the specified file to other files in the same filegroup. Because the Database Engine no longer allows data to be placed in the empty file, the file can be removed by using the ALTER DATABASE statement.

For FILESTREAM filegroup containers, the file cannot be removed using ALTER DATABASE until the FILESTREAM Garbage Collector has run and deleted all the unnecessary filegroup container files that EMPTYFILE has copied to another container. For more information, see sp_filestream_force_garbage_collection (Transact-SQL)

NoteNote

For information on removing a FILESTREAM container, see the corresponding section in ALTER DATABASE File and Filegroup Options (Transact-SQL)

NOTRUNCATE

Moves allocated pages from the end of a data file to unallocated pages in the front of the file with or without specifying target_percent. The free space at the end of the file is not returned to the operating system, and the physical size of the file does not change. Therefore, when NOTRUNCATE is specified, the file appears not to shrink.

NOTRUNCATE is applicable only to data files. The log files are not affected.

This option is not supported for FILESTREAM filegroup containers.

TRUNCATEONLY

Releases all free space at the end of the file to the operating system but does not perform any page movement inside the file. The data file is shrunk only to the last allocated extent.

target_size is ignored if specified with TRUNCATEONLY.

TRUNCATEONLY is applicable only to data files. This option is not supported for FILESTREAM filegroup containers.

WITH NO_INFOMSGS

Suppresses all informational messages.

The following table describes the columns in the result set.

Column name

Description

DbId

Database identification number of the file the Database Engine tried to shrink.

FileId

The file identification number of the file the Database Engine tried to shrink.

CurrentSize

Number of 8-KB pages the file currently occupies.

MinimumSize

Number of 8-KB pages the file could occupy, at minimum. This corresponds to the minimum size or originally created size of a file.

UsedPages

Number of 8-KB pages currently used by the file.

EstimatedPages

Number of 8-KB pages that the Database Engine estimates the file could be shrunk down to.

DBCC SHRINKFILE applies to the files in the current database. For more information about how to change the current database, see USE (Transact-SQL).

DBCC SHRINKFILE operations can be stopped at any point in the process, and any completed work is retained.

When a DBCC SHRINKFILE operation fails, an error is raised.

The database being shrunk does not have to be in single-user mode; other users can be working in the database when the file is shrunk. You do not have to run the instance of SQL Server in single-user mode to shrink the system databases.

Shrinking a Log File

For log files, the Database Engine uses target_size to calculate the target size for the whole log; therefore, target_size is the amount of free space in the log after the shrink operation. Target size for the whole log is then translated to target size for each log file. DBCC SHRINKFILE tries to shrink each physical log file to its target size immediately. However, if part of the logical log resides in the virtual logs beyond the target size, the Database Engine frees as much space as possible, and then issues an informational message. The message describes what actions are required to move the logical log out of the virtual logs at the end of the file. After the actions are performed, DBCC SHRINKFILE can be used to free the remaining space.

Because a log file can only be shrunk to a virtual log file boundary, shrinking a log file to a size smaller than the size of a virtual log file might not be possible, even if it is not being used. The size of the virtual log file is chosen dynamically by the Database Engine when log files are created or extended.

Best Practices

Consider the following information when you plan to shrink a file:

  • A shrink operation is most effective after an operation that creates lots of unused space, such as a truncate table or a drop table operation.

  • Most databases require some free space to be available for regular day-to-day operations. If you shrink a database repeatedly and notice that the database size grows again, this indicates that the space that was shrunk is required for regular operations. In these cases, repeatedly shrinking the database is a wasted operation.

  • A shrink operation does not preserve the fragmentation state of indexes in the database, and generally increases fragmentation to a degree. This is another reason not to repeatedly shrink the database.

Troubleshooting

This section describes how to diagnose and correct issues that can occur when running the DBCC SHRINKFILE command.

The File Does Not Shrink

If the shrink operation runs without error, but the file does not appear to have changed in size, verify that the file has adequate free space to remove by performing one of the following operations:

  • Run the following query.

    SELECT name ,size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS int)/128.0 AS AvailableSpaceInMB
    FROM sys.database_files;
  • Run the DBCC SQLPERF command to return the space used in the transaction log.

If insufficient free space is available, the shrink operation cannot reduce the file size any further.

Typically it is the log file that appears not to shrink. This is usually the result of a log file that has not been truncated. You can truncate the log by setting the database recovery model to SIMPLE, or by backing up the log and then running the DBCC SHRINKFILE operation again.

The Shrink Operation Is Blocked

It is possible for shrink operations to be blocked by a transaction that is running under a row versioning-based isolation level. For example, if a large delete operation running under a row versioning-based isolation level is in progress when a DBCC SHRINK DATABASE operation is executed, the shrink operation will wait for the delete operation to complete before shrinking the files. When this happens, DBCC SHRINKFILE and DBCC SHRINKDATABASE operations print out an informational message (5202 for SHRINKDATABASE and 5203 for SHRINKFILE) to the SQL Server error log every five minutes in the first hour and then every hour after that. For example, if the error log contains the following error message then the following error will occur:

DBCC SHRINKFILE for file ID 1 is waiting for the snapshot 
transaction with timestamp 15 and other snapshot transactions linked to 
timestamp 15 or with timestamps older than 109 to finish.

This means that the shrink operation is blocked by snapshot transactions that have timestamps older than 109, which is the last transaction that the shrink operation completed. It also indicates that the transaction_sequence_num, or first_snapshot_sequence_num columns in the sys.dm_tran_active_snapshot_database_transactions dynamic management view contains a value of 15. If either the transaction_sequence_num, or first_snapshot_sequence_num columns in the view contains a number that is less than the last transaction completed by a shrink operation (109), the shrink operation will wait for those transactions to finish.

To resolve the issue, you can do one of the following tasks:

  • Terminate the transaction that is blocking the shrink operation.

  • Terminate the shrink operation. If the shrink operation is terminated, any completed work is retained.

  • Do nothing and allow the shrink operation to wait until the blocking transaction completes.

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

A.Shrinking a data file to a specified target size

The following example shrinks the size of a data file named DataFile1 in the UserDB user database to 7 MB.

Transact-SQL
USE UserDB;
GO
DBCC SHRINKFILE (DataFile1, 7);
GO

B.Shrinking a log file to a specified target size

The following example shrinks the log file in the AdventureWorks database to 1 MB. To allow the DBCC SHRINKFILE command to shrink the file, the file is first truncated by setting the database recovery model to SIMPLE.

Transact-SQL
USE AdventureWorks2012;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE AdventureWorks2012
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks2012_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE AdventureWorks2012
SET RECOVERY FULL;
GO

C.Truncating a data file

The following example truncates the primary data file in the AdventureWorks database. The sys.database_files catalog view is queried to obtain the file_id of the data file.

Transact-SQL
USE AdventureWorks2012;
GO
SELECT file_id, name
FROM sys.database_files;
GO
DBCC SHRINKFILE (1, TRUNCATEONLY);

D.Emptying a file

The following example demonstrates the procedure for emptying a file so that it can be removed from the database. For the purposes of this example, a data file is first created and it is assumed that the file contains data.

Transact-SQL
USE AdventureWorks2012;
GO
-- Create a data file and assume it contains data.
ALTER DATABASE AdventureWorks2012 
ADD FILE (
    NAME = Test1data,
    FILENAME = 'C:\t1data.ndf',
    SIZE = 5MB
    );
GO
-- Empty the data file.
DBCC SHRINKFILE (Test1data, EMPTYFILE);
GO
-- Remove the data file from the database.
ALTER DATABASE AdventureWorks2012
REMOVE FILE Test1data;
GO
DBCC SHRINKFILE (Transact-SQL)

Reduce el tamaño del archivo de datos o de registro para la base de datos actual, o vacía un archivo moviendo los datos del archivo especificado a otros archivos del mismo grupo, lo que permite quitar el archivo de la base de datos. Puede reducir un archivo a un tamaño menor que el tamaño especificado cuando se creó. Así se restablece el tamaño mínimo de archivo al valor nuevo.

Icono de vínculo a temas Convenciones de sintaxis de Transact-SQL

DBCC SHRINKFILE 
(
    { file_name | file_id } 
    { [ , EMPTYFILE ] 
    | [ [ , target_size ] [ , { NOTRUNCATE | TRUNCATEONLY } ] ]
    }
)
[ WITH NO_INFOMSGS ]
file_name

Es el nombre lógico del archivo que se va a reducir.

file_id

Es el número de identificación (Id.) del archivo que se va a reducir. Para obtener un Id. de archivo, use la función del sistema FILE_IDEX o consulte la vista de catálogo sys.database_files en la base de datos actual.

target_size

Es el tamaño para el archivo, en megabytes, expresado como un número entero. Si no se especifica, DBCC SHRINKFILE reduce el tamaño al predeterminado del archivo. El tamaño predeterminado es que se especificó cuando se creó el archivo.

NotaNota

Puede reducir el tamaño predeterminado de un archivo vacío utilizando DBCC SHRINKFILE target_size. Por ejemplo, si crea un archivo de 5 MB y, a continuación, reduce el archivo a 3 MB mientras el archivo todavía está vacío, el tamaño de archivo predeterminado se establece en 3 MB. Esto solo se aplica para vaciar archivos que nunca han contenido datos.

Esta opción no se admite para los contenedores del grupo de archivos FILESTREAM.

Si se especifica target_size, DBCC SHRINKFILE intenta reducir el archivo al tamaño especificado. Las páginas utilizadas de la parte del archivo que se va a liberar se vuelven a ubicar en el espacio disponible de la parte del archivo que se va a mantener. Por ejemplo, si hay un archivo de datos de 10 MB, una operación DBCC SHRINKFILE con el parámetro target_size establecido en 8 hace que todas las páginas usadas de los últimos 2 MB del archivo se asignen de nuevo a cualquiera de las páginas no asignadas disponibles en los primeros 8 MB del archivo. DBCC SHRINKFILE no reduce un archivo a un tamaño menor que el que se necesita para almacenar los datos en el archivo. Por ejemplo, si se utilizan 7 MB de un archivo de datos de 10 MB, una instrucción DBCC SHRINKFILE con un parámetro target_size de 6 reduce el archivo a 7 MB, no 6 MB.

EMPTYFILE

Migra todos los datos del archivo especificado a otros archivos del mismo grupo de archivos. Como Motor de base de datos ya no permite colocar datos en el archivo vacío, se puede quitar el archivo mediante la instrucción ALTER DATABASE.

Para los contenedores del grupo de archivos FILESTREAM, no se puede quitar el archivo mediante ALTER DATABASE hasta que el recopilador de elementos no utilizados de FILESTREAM haya ejecutado y eliminado todos los archivos innecesarios del contenedor del grupo de archivos que EMPTYFILE ha copiado en otro contenedor. Para obtener más información, vea sp_filestream_force_garbage_collection (Transact-SQL)

NotaNota

Para obtener información sobre cómo quitar un contenedor de FILESTREAM, vea la sección correspondiente en Opciones File y Filegroup de ALTER DATABASE (Transact-SQL)

NOTRUNCATE

Mueve las páginas asignadas del final de un archivo de datos a páginas no asignadas del principio del archivo especificando o sin especificar target_percent. El espacio disponible del final del archivo no se devuelve al sistema operativo y el tamaño físico del archivo no cambia. Por tanto, si se especifica NOTRUNCATE, parecerá que el archivo no se reduce.

NOTRUNCATE solo es aplicable a archivos de datos. No afecta a los archivos de registro.

Esta opción no se admite para los contenedores del grupo de archivos FILESTREAM.

TRUNCATEONLY

Devuelve al sistema operativo todo el espacio disponible del final del archivo, pero no realiza ningún movimiento de página dentro del archivo. El archivo de datos solo se reduce hasta el último tamaño asignado.

target_size se omite si se especifica con TRUNCATEONLY.

TRUNCATEONLY solo es aplicable a archivos de datos. Esta opción no se admite para los contenedores del grupo de archivos FILESTREAM.

WITH NO_INFOMSGS

Suprime todos los mensajes de información.

En la tabla siguiente se describen las columnas del conjunto de resultados.

Nombre de columna

Descripción

DbId

Número de identificación de la base de datos del archivo que el Motor de base de datos intentó reducir.

FileId

Número de identificación del archivo que el Motor de base de datos intentó reducir.

CurrentSize

El número de páginas de 8 KB que el archivo ocupa actualmente.

MinimumSize

El número de páginas de 8 KB que el archivo podría ocupar, como mínimo. Esto corresponde al tamaño mínimo o tamaño de creación original de un archivo.

UsedPages

El número de páginas de 8 KB que utiliza actualmente el archivo.

EstimatedPages

El número de páginas de 8 KB al que el Motor de base de datos estima que se puede reducir el archivo.

DBCC SHRINKFILE se aplica a los archivos de la base de datos actual. Para obtener más información acerca de cómo cambiar la base de datos actual, vea USE (Transact-SQL).

Las operaciones DBCC SHRINKFILE pueden detenerse en cualquier momento del proceso y se mantiene el trabajo completado.

Cuando una operación DBCC SHRINKFILE no es correcta, se genera un error.

La base de datos que se está reduciendo no tiene por qué estar en modo de usuario único; otros usuarios pueden estar trabajando en la base de datos cuando el archivo se está reduciendo. No es necesario ejecutar SQL Server en modo de usuario único para reducir las bases de datos del sistema.

Reducir un archivo de registro

En los archivos de registro, el Motor de base de datos utiliza el parámetro target_size para calcular el tamaño final de todo el registro, de forma que target_size sea la cantidad de espacio disponible del registro después de la operación de reducción. El tamaño final del registro entero se traduce, entonces, en el tamaño final de cada archivo de registro. DBCC SHRINKFILE intenta reducir cualquier archivo de registro físico a su tamaño final de forma inmediata. Sin embargo, si parte del registro lógico está en los registros virtuales más allá del tamaño final, el Motor de base de datos libera tanto espacio como sea posible y a continuación emite un mensaje informativo. El mensaje indica las acciones que se deben llevar a cabo para mover el registro lógico de los registros virtuales al final del archivo. Una vez realizadas estas acciones, se puede usar DBCC SHRINKFILE para liberar el espacio restante.

Como un archivo de registro solo puede reducirse al límite de un archivo de registro virtual, puede que no sea posible reducirlo a un tamaño menor que el de un archivo de registro virtual, aunque no esté siendo utilizado. Motor de base de datos elige dinámicamente el tamaño del archivo de registro virtual cuando se crean o se extienden archivos de registro.

Procedimientos recomendados

Tenga en cuenta la siguiente información cuando vaya a reducir un archivo:

  • La reducción es más efectiva después de una operación que cree mucho espacio inutilizado, como por ejemplo una operación para truncar o eliminar tablas.

  • La mayoría de las bases de datos requieren que haya espacio disponible para realizar las operaciones diarias normales. Si se reduce una base de datos en forma reiterada y su tamaño vuelve a aumentar, esto indica que el espacio que se redujo es necesario para las operaciones normales. En estos casos, no sirve reducir la base de datos reiteradamente.

  • La reducción no mantiene el estado de fragmentación de los índices de la base de datos y generalmente aumenta la fragmentación hasta cierto punto. Esta es otra razón para no reducir la base de datos reiteradamente.

Solucionar problemas

En esta sección se describe el modo de diagnosticar y corregir los problemas que pueden ocurrir al ejecutar el comando DBCC SHRINKFILE:

El archivo no se reduce

Si la operación de reducción se ejecuta sin errores, pero parece que el archivo no ha cambiado de tamaño, compruebe que el archivo tiene espacio disponible para quitar realizando una de las siguientes operaciones:

  • Ejecute la siguiente consulta.

    SELECT name ,size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS int)/128.0 AS AvailableSpaceInMB
    FROM sys.database_files;
  • Ejecute el comando DBCC SQLPERF para devolver el espacio ocupado en el registro de transacciones.

Si no hay suficiente espacio disponible, la operación de reducción no puede reducir más el tamaño del archivo.

Normalmente es el archivo de registro el que parece no reducirse. Esto suele deberse a que dicho archivo no se ha truncado. Puede truncar el registro estableciendo el modelo de recuperación de la base de datos en SIMPLE o realizando una copia de seguridad del registro y ejecutando a continuación la operación DBCC SHRINKFILE nuevamente.

La operación de reducción está bloqueada

Es posible bloquear las operaciones de reducción mediante una transacción que se ejecuta con un nivel de aislamiento basado en versiones de fila. Por ejemplo, si se está ejecutando una operación de eliminación grande con un nivel de aislamiento basado en versiones de fila cuando se ejecuta una operación DBCC SHRINK DATABASE, la operación de reducción esperará a que la operación de eliminación se haya completado antes de reducir los archivos. Cuando esto sucede, las operaciones DBCC SHRINKFILE y DBCC SHRINKDATABASE imprimen un mensaje informativo (5202 en el caso de SHRINKDATABASE y 5203 para SHRINKFILE) en el registro de errores de SQL Server cada cinco minutos durante la primera hora, y cada hora sucesivamente.  Por ejemplo, si el registro de errores contiene el siguiente mensaje de error, se producirá el siguiente error:

DBCC SHRINKFILE for file ID 1 is waiting for the snapshot 
transaction with timestamp 15 and other snapshot transactions linked to 
timestamp 15 or with timestamps older than 109 to finish.

Esto significa que la operación de reducción está bloqueada por transacciones de instantánea que tienen marcas de tiempo anteriores a 109, que es la última transacción que ha completado la operación de reducción. También indica que las columnas transaction_sequence_num o first_snapshot_sequence_num de la vista de administración dinámica sys.dm_tran_active_snapshot_database_transactions contienen el valor 15. Si la columna transaction_sequence_num o first_snapshot_sequence_num contiene un número inferior al de la última transacción completada mediante una operación de reducción (109), la operación de reducción esperará a que las transacciones finalicen.

Para resolver el problema, puede llevar a cabo una de las tareas siguientes:

  • Finalizar la transacción que está bloqueando la operación de reducción.

  • Finalizar la operación de reducción. Si finaliza la operación de reducción, se conservará todo el trabajo completado.

  • No hacer nada y permitir que la operación de reducción espere a que finalice la transacción que la está bloqueando.

Debe pertenecer al rol fijo de servidor sysadmin o al rol fijo de base de datos db_owner.

A.Reducir un archivo de datos a un tamaño final especificado

En el siguiente ejemplo se reduce el tamaño de un archivo de datos denominado DataFile1 de la base de datos de usuario UserDB a 7 MB.

Transact-SQL
USE UserDB;
GO
DBCC SHRINKFILE (DataFile1, 7);
GO

B.Reducir un archivo de registro a un tamaño final especificado

En el ejemplo siguiente se reduce el archivo de registro de la base de datos AdventureWorks a 1 MB. Para permitir que el comando DBCC SHRINKFILE reduzca el archivo, primero hay que truncar el archivo estableciendo el modelo de recuperación de la base de datos en SIMPLE.

Transact-SQL
USE AdventureWorks2012;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE AdventureWorks2012
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks2012_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE AdventureWorks2012
SET RECOVERY FULL;
GO

C.Truncar un archivo de datos

En el ejemplo siguiente se trunca el archivo de datos principal en la base de datos AdventureWorks. Se consulta la vista de catálogo sys.database_files para obtener el valor de file_id del archivo de datos.

Transact-SQL
USE AdventureWorks2012;
GO
SELECT file_id, name
FROM sys.database_files;
GO
DBCC SHRINKFILE (1, TRUNCATEONLY);

D.Vaciar un archivo

En el ejemplo siguiente se ilustra el procedimiento para vaciar un archivo de forma que se pueda quitar de la base de datos. Para los fines de este ejemplo, se crea primero un archivo de datos y se supone que el archivo contiene datos.

Transact-SQL
USE AdventureWorks2012;
GO
-- Create a data file and assume it contains data.
ALTER DATABASE AdventureWorks2012 
ADD FILE (
    NAME = Test1data,
    FILENAME = 'C:\t1data.ndf',
    SIZE = 5MB
    );
GO
-- Empty the data file.
DBCC SHRINKFILE (Test1data, EMPTYFILE);
GO
-- Remove the data file from the database.
ALTER DATABASE AdventureWorks2012
REMOVE FILE Test1data;
GO
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Condiciones de Uso | Marcas registradas | Declaración de privacidad
Page view tracker