0

Tengo una base de datos que actualmente pesa 13Gb, se requiere reodernar los indices para que baje su tamaño y mejore el rendimiento en cuanto a las peticiones que se le realizan desde el aplicativo, hasta el momento se ocupa un Query el cual reduce un 11%,

Adicionalmente se corre la opcion que ofrece SQL para reducir el tamaño, pero al parecer, segun el resultado que se obtiene no baja mucho, pero dicen que de 13Gb puede bajar hasta un 39% es decir quedaria casi en 8Gb Mi pregunta es; Existe algun otro metodo el cual pueda mejorar mas? alguien ocupa algun script que realice este proceso?¿ Que me recomiendan?

Esta es la consulta que se ocupa para realizar el proceso mencionado.



--Initial check - You must be SysAdmin
DECLARE @isSysAdmin INT
SET @isSysAdmin=(SELECT IS_SRVROLEMEMBER ('sysadmin'));

--Initial check - You must be using SQL Server 2005 or later
DECLARE @SQLServerVersion INT
SET @SQLServerVersion=(SELECT CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(50)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(50)))-1) AS INT));


IF @isSysAdmin=1 AND @SQLServerVersion >= 9
BEGIN 

--
-- Variable/parameters Declaration
--
DECLARE @dbname NVARCHAR(128);
DECLARE @ReorganizeOrRebuildCommand NVARCHAR(MAX);
DECLARE @dbid INT;
DECLARE @indexFillFactor VARCHAR(5); 
DECLARE @fragmentationThreshold VARCHAR(10);
DECLARE @indexStatisticsScanningMode VARCHAR(20);
DECLARE @verboseMode BIT;
DECLARE @reportOnly BIT;
DECLARE @sortInTempdb VARCHAR(3);
DECLARE @isHadrEnabled BIT;
DECLARE @databaseToCheck VARCHAR(250)
DECLARE @dynamic_command NVARCHAR(1024);
DECLARE @dynamic_command_get_tables NVARCHAR(MAX);

--Initializations - Do not change
SET @databaseToCheck=NULL;
SET @dynamic_command = NULL;
SET @dynamic_command_get_tables = NULL;
SET @isHadrEnabled=0;

SET NOCOUNT ON;

---------------------------------------------------------
--Set Parameter Values: You can change these (optional) -
--Note: The script has default parameters set   -
---------------------------------------------------------
--if set to 1: it will just generate a report with the index reorganization/rebuild statements
--if set to 0: it will reorganize or rebuild the fragmented indexes
SET @reportOnly = 0;

--optional: if not set (NULL), it will scann all databases
--If name is set (i.e. 'testDB') it will just scan the given database
SET @databaseToCheck = 'DB_NAME';

--maintains only the indexes that have average fragmentation percentage equal or higher from the given value
SET @fragmentationThreshold = 15; 

--fill factor - the percentage of the data page to be filled up with index data
SET @indexFillFactor = 90; 

--sets the scanning mode for index statistics 
--available values: 'DEFAULT', NULL, 'LIMITED', 'SAMPLED', or 'DETAILED'
SET @indexStatisticsScanningMode='SAMPLED';

--if set to ON: sorts intermediate index results in TempDB 
--if set to OFF: sorts intermediate index results in user database's log file
SET @sortInTempdb='ON'; 

--if set to 0: Does not output additional information about the index reorganization/rebuild process
--if set to 0: Outputs additional information about the index reorganization/rebuild process
SET @verboseMode = 0; 
------------------------------
--End Parameter Values Setup -
------------------------------

-- check if given database exists and if compatibility level >= SQL 2005 (90)
IF @verboseMode=1
 PRINT 'Checking if database '+@databaseToCheck+' exists and if compatibility level equals or greater 2005 (90)';

 -- if given database does not exist, raise error with severity 20
 -- in order to terminate script's execution
IF @databaseToCheck IS NOT NULL
BEGIN
 DECLARE @checkResult INT
 SET @checkResult=(SELECT COUNT(*) FROM master.sys.databases WHERE [name]=RTRIM(@databaseToCheck));
 IF @checkResult<1
  RAISERROR('Error executing index reorganization/rebuild script: Database does not exist' , 20, 1) WITH LOG;

 DECLARE @checkResult2 INT
 SET @checkResult=(SELECT [compatibility_level] FROM master.sys.databases WHERE [name]=RTRIM(@databaseToCheck));
 IF @checkResult<90
  RAISERROR('Error executing index reorganization/rebuild script: Only databases with SQL Server 2005 or later compatibility level are supported' , 20, 1) WITH LOG;  
END

IF @verboseMode=1
 PRINT 'Initial checks completed with no errors.';

-- Temporary table for storing index fragmentation details
IF OBJECT_ID('tempdb..#tmpFragmentedIndexes') IS NULL
BEGIN
CREATE TABLE #tmpFragmentedIndexes
    (
      [dbName] sysname,
      [tableName] sysname,
   [schemaName] sysname,
      [indexName] sysname,
      [databaseID] SMALLINT ,
      [objectID] INT ,
      [indexID] INT ,
      [AvgFragmentationPercentage] FLOAT,
   [reorganizationOrRebuildCommand] NVARCHAR(MAX)
    );
END 

-- Initialize temporary table
DELETE FROM #tmpFragmentedIndexes;

-- Validate parameters/set defaults
IF @sortInTempdb NOT IN ('ON','OFF')
SET @sortInTempdb='ON';

-- Check if instance has AlwaysOn AGs enabled
SET @isHadrEnabled=CAST((SELECT ISNULL(SERVERPROPERTY('IsHadrEnabled'),0)) AS BIT);

-- if database not specified scan all databases
IF @databaseToCheck IS NULL
BEGIN
DECLARE dbNames_cursor CURSOR
FOR
    SELECT  s.[name] AS dbName ,
            s.database_id
    FROM    master.sys.databases s            
    WHERE   s.state_desc = 'ONLINE'
            AND s.is_read_only != 1            
            AND s.[name] NOT IN ( 'master', 'model', 'tempdb' )
   AND s.[compatibility_level]>=90
    ORDER BY s.database_id;    
END 
ELSE
-- if database specified, scan only that database
BEGIN
DECLARE dbNames_cursor CURSOR 
FOR
    SELECT  s.[name] AS dbName ,
            s.database_id
    FROM    master.sys.databases s            
    WHERE   s.state_desc = 'ONLINE'
            AND s.is_read_only != 1                        
   AND s.[name]=RTRIM(@databaseToCheck)    
END 

-- if Always On Availability Groups are enabled, check for primary databases
-- (thus exclude secondary databases)
IF @isHadrEnabled=1
BEGIN

DEALLOCATE dbNames_cursor;

-- if database not specified scan all databases
IF @databaseToCheck IS NULL
BEGIN
 DECLARE dbNames_cursor CURSOR
 FOR
  SELECT  s.[name] AS dbName ,
    s.database_id
  FROM    master.sys.databases s
    LEFT JOIN master.sys.dm_hadr_availability_replica_states r ON s.replica_id = r.replica_id
  WHERE   s.state_desc = 'ONLINE'
    AND s.is_read_only != 1
    AND UPPER(ISNULL(r.role_desc, 'NonHadrEnabled')) NOT LIKE 'SECONDARY'
    AND s.[name] NOT IN ( 'master', 'model', 'tempdb' )
    AND s.[compatibility_level]>=90 
  ORDER BY s.database_id;    
END
ELSE
-- if database specified, scan only that database
BEGIN
 DECLARE dbNames_cursor CURSOR
 FOR
  SELECT  s.[name] AS dbName ,
    s.database_id
  FROM    master.sys.databases s
    LEFT JOIN master.sys.dm_hadr_availability_replica_states r ON s.replica_id = r.replica_id
  WHERE   s.state_desc = 'ONLINE'
    AND s.is_read_only != 1
    AND UPPER(ISNULL(r.role_desc, 'NonHadrEnabled')) NOT LIKE 'SECONDARY'    
    AND s.[name]=RTRIM(@databaseToCheck);  
END 
END 


--
-- For each database included in the cursor, 
-- gather all tables that have indexes with 
-- average fragmentation percentage equal or above @fragmentationThreshold
--
OPEN dbNames_cursor;
FETCH NEXT FROM dbNames_cursor INTO @dbname, @dbid;
WHILE @@fetch_status = 0
    BEGIN   

 --If verbose mode is enabled, print logs
        IF @verboseMode = 1
            BEGIN
    PRINT ''
                PRINT 'Gathering index fragmentation statistics for database: ['+ @dbname + '] with id: ' + CAST(@dbid AS VARCHAR(10));    
            END;

        SET @dynamic_command_get_tables = N'
 USE [' + @dbname+ N'];
 INSERT INTO #tmpFragmentedIndexes (
  [dbName],
  [tableName],
  [schemaName],
  [indexName],
  [databaseID],
  [objectID],
  [indexID],
  [AvgFragmentationPercentage],
  [reorganizationOrRebuildCommand]  
  )
  SELECT
     DB_NAME() as [dbName], 
     tbl.name as [tableName],
     SCHEMA_NAME (tbl.schema_id) as schemaName, 
     idx.Name as [indexName], 
     pst.database_id as [databaseID], 
     pst.object_id as [objectID], 
     pst.index_id as [indexID], 
     pst.avg_fragmentation_in_percent as [AvgFragmentationPercentage],
     CASE WHEN pst.avg_fragmentation_in_percent > 30 THEN 
     ''ALTER INDEX [''+idx.Name+''] ON [''+DB_NAME()+''].[''+SCHEMA_NAME (tbl.schema_id)+''].[''+tbl.name+''] REBUILD WITH (FILLFACTOR = '+@indexFillFactor+', SORT_IN_TEMPDB = '+@sortInTempdb+', STATISTICS_NORECOMPUTE = OFF);''
     WHEN pst.avg_fragmentation_in_percent > 5 AND pst.avg_fragmentation_in_percent <= 30 THEN 
     ''ALTER INDEX [''+idx.Name+''] ON [''+DB_NAME()+''].[''+SCHEMA_NAME (tbl.schema_id)+''].[''+tbl.name+''] REORGANIZE;''     
     ELSE
     NULL
     END
  FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL , '''+@indexStatisticsScanningMode+''') as pst
   INNER JOIN sys.tables as tbl ON pst.object_id = tbl.object_id
   INNER JOIN sys.indexes idx ON pst.object_id = idx.object_id AND pst.index_id = idx.index_id
  WHERE pst.index_id != 0  
   AND pst.alloc_unit_type_desc IN ( N''IN_ROW_DATA'', N''ROW_OVERFLOW_DATA'')
   AND pst.avg_fragmentation_in_percent >= '+ @fragmentationThreshold + '';

  -- if verbose  mode is enabled, print logs    
  IF @verboseMode=1
   BEGIN
    PRINT 'Index fragmentation statistics script: ';    
    PRINT @dynamic_command_get_tables;
  END

  -- gather index fragmentation statistics
        EXEC (@dynamic_command_get_tables);

     -- bring next record from the cursor
        FETCH NEXT FROM dbNames_cursor INTO @dbname, @dbid;
    END;

CLOSE dbNames_cursor;
DEALLOCATE dbNames_cursor;

------------------------------------------------------------

-- if 'report only' mode is enabled
IF @reportOnly=1
BEGIN 
 SELECT  dbName ,
            tableName ,
            schemaName ,
            indexName ,            
            AvgFragmentationPercentage ,
            reorganizationOrRebuildCommand
 FROM    #tmpFragmentedIndexes
 ORDER BY AvgFragmentationPercentage DESC;
END
ELSE 
-- if 'report only' mode is disabled, then execute 
-- index reorganize/rebuild statements
BEGIN 
 DECLARE reorganizeOrRebuildCommands_cursor CURSOR
 FOR
    SELECT  reorganizationOrRebuildCommand
  FROM #tmpFragmentedIndexes
  WHERE reorganizationOrRebuildCommand IS NOT NULL
  ORDER BY AvgFragmentationPercentage DESC;

 OPEN reorganizeOrRebuildCommands_cursor;
 FETCH NEXT FROM reorganizeOrRebuildCommands_cursor INTO @ReorganizeOrRebuildCommand;
 WHILE @@fetch_status = 0
  BEGIN   

   IF @verboseMode = 1
   BEGIN
     PRINT ''
     PRINT 'Executing script:'     
     PRINT @ReorganizeOrRebuildCommand
   END

   EXEC (@ReorganizeOrRebuildCommand);          
   FETCH NEXT FROM reorganizeOrRebuildCommands_cursor INTO @ReorganizeOrRebuildCommand;
  END;

 CLOSE reorganizeOrRebuildCommands_cursor;
 DEALLOCATE reorganizeOrRebuildCommands_cursor;

 PRINT ''
 PRINT 'All fragmented indexes have been reorganized/rebuilt.'
 PRINT ''
END
END 
ELSE
BEGIN
 PRINT '';
 PRINT 'Error: You need to be SysAdmin and use SQL Server 2005 or later in order to use this script.';
 PRINT '';
END
--End of Script
1
  • Hola Soft Quick:
    – Javi fer2
    el 5 mar. 2020 a las 20:47

1 respuesta 1

0

Reducir el tamaño de la base de datos, no va a mejorar en nada el rendimiento. Cuando este bien junta, lo que hará Sql server, como necesitará espacio, es solicitarle al sistema un nuevo bloque de espacio para poder escribir, lo que producirá demoras, mientras este le es asignado. Esa no es una buena praxis, salvo cuando hubiera un crecimiento desmesurado.

  • Si se ejecuta una transacción que requiere más espacio del registro que está disponible y ha activado la opción de crecimiento automático del registro de transacciones de esa base de datos, el tiempo que tarda la transacción finalice incluirá el tiempo que tarda el registro de transacciones crecimiento en la cantidad configurada. Si el incremento de crecimiento es grande o hay algún otro factor que hace que llevar mucho tiempo, la consulta en el que abrir la transacción puede fallar debido a un error de tiempo de espera. El mismo tipo de problema puede resultar de un crecimiento automático de la parte de datos de la base de datos. Para cambiar la configuración de crecimiento automático , consulte el tema "ALTER DATABASE" en libros en pantalla de SQL Server.

  • Si ejecuta una transacción grande que requiere el registro de crecimiento, otras transacciones que requieren una escritura en el registro de transacciones también tendrá que esperar hasta que finaliza la operación de crecimiento.

  • Si se combinan las opciones de crecimiento automático y autorreducción , podría crear innecesarios sobrecarga. Asegúrese de que no hará que los umbrales que desencadenan el crecimiento y reducir las operaciones frecuentes y Bajar los cambios de tamaño. Por ejemplo, puede ejecutar una transacción que hace que el registro de transacciones crezca por 100 MB en el momento en que confía. Algún tiempo después de que la reducción automática se inicia y reduce el registro de transacciones por 100 MB. A continuación, ejecutar la misma transacción y hace que el registro de transacciones crezcan de nuevo en 100 MB. En el ejemplo, se crea innecesarios sobrecarga y potencialmente creando fragmentación del archivo de registro, que puede afectar negativamente al rendimiento.

  • Fragmentación física de cambiar el tamaño de los archivos de datos o de registro puede tener un efecto grave en el rendimiento. Esto es cierto si utiliza la configuración automática, o si usted manualmente aumentar y hundir los archivos con frecuencia.

  • Si aumentan su base de datos a intervalos pequeños, o si crecer y luego reducirlo, puede acabar con la fragmentación de disco. Fragmentación del disco puede producir problemas de rendimiento en algunas circunstancias. Un escenario de incrementos de crecimiento pequeño también puede reducir el rendimiento del sistema.

Consideraciones de crecimiento y reducción

6
  • Comprendo lo que dices analizando la respuesta tiene mucha coherencia con el funcionamiento del aplicativo en cuanto al tiempo de respuesta que se obtiene. pero me genera duda porque alguien externo a la compañia un DBA dice que el lo puede reducir hasta en un 39% , lo que no entendemos es que es lo que realiza para que ese proceso sea de esa manera, puesto que lo que hemos logrado solo es reducir un 11%.
    – BlackHat
    el 6 mar. 2020 a las 12:37
  • La respuesta que yo le daría es y que!!! Sería genial que la pudiese reducir un 39% y que fuese más rápida y no creciese, pero eso no lo va a poder hacer. Con tú script, lo que estas reindexando los idx con un nivel de fragmentación al 30% (tal como recomienda microsoft) y reordenando los que tienen un nivel de fragmentación entre el 5 y el 30 (tambien lo recomendado) No se si tiene en cuenta que tengan 1000 páginas o mas, pero es indiferente.
    – Javi fer2
    el 6 mar. 2020 a las 13:39
  • Si tu mismo script, reindexa todos los indices (todos), sin excepción, y no reorganiza. Reducirás mucho el espacio, pero eso no será beneficioso para las consultas.
    – Javi fer2
    el 6 mar. 2020 a las 13:40
  • Entiendo, según tu experiencia, que recomendaciones, o como podria hacerlo mas beneficioso? el aplicativo como tal es de punto de venta tiene como modulos Entradas, salidas, traslados, compras, facturacion POS y electronica, etc..
    – BlackHat
    el 6 mar. 2020 a las 13:58
  • Es imposible darte sugerencias por el tipo de aplicación porque a la base de datos eso no le dice nada. Olvida el tema de la reducción de espacio salvo que se dispare. Piensa en seguir las recomendaciones de reordenar reindexar a partir de 1000 páginas. Intenta tener varios archivos de log y en diferentes discos que los datos. Que la BBDD temp este en un disco muy rápido. Y trabajar las consultas obteniendo información de rendimiento de las dmvs. Las q más gasten o más veces se ejecuten
    – Javi fer2
    el 6 mar. 2020 a las 15:17

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.