Print ''
Print '----------------------------------------------------'
Print ' DB Maintain  : Database Optimice'
Print ' FirstRevision: V2.0.0   22.03.2006'
Print ' CurrRevision : V2.1.2   11.06.2015'
Print ' Autor        : J.Feuerstein'
Print ' '
Print ' Database Name: #DB_N#'
Print '----------------------------------------------------'
GO

USE [#DB_N#]

/*
Quelle:
http://blog.sqlauthority.com/2007/06/24/sql-server-comparison-index-fragmentation-index-de-fragmentation-index-rebuild-sql-server-2000-and-sql-server-2005/

This is a the latest version of this script as of 2008-11-12:
Script originally authored by Microsoft but had an error - It was retrieving data without prefixing database schema.

-Added a @ViewOnly variable that will allow you to run this script as a test only and review proposed actions. Simply change the value to 0 to execute the proposed actions.
-Also enhanced to perform either a reorg or rebuild, based on range of fragmentation value.
-Also included pages value from DBCC SHOWCONTIG for analysis, to support theory that defragging indexes have few pages is not productive.
~Paul DeBrino : infinityrd.com : Nov 2008

USEFUL INFO -- INSPECT INDEXES' FILL FACTOR VALUES:
============================================
use YourDBName
select * from sys.indexes order by name

USEFUL INFO -- VIEW THE DEFAULT FILL FACTOR OF YOUR SERVER:
============================================
use YourDBname
exec sp_configure 'show advanced options', 1
-- go
reconfigure
-- go
exec sp_configure 'fill factor'
-- go
*/

Print ''
PRINT '-------------------------------------------------------------------------'
PRINT 'DB Optimise Re.Org. Indecis DB:#DB_N#'


-- Declare variables:
SET NOCOUNT ON
DECLARE @tablename VARCHAR(128)
DECLARE @tablenameLast VARCHAR(128)
DECLARE @execstr VARCHAR(255)
DECLARE @objectid INT
DECLARE @indexid INT
DECLARE @frag decimal
DECLARE @maxreorg decimal
DECLARE @maxrebuild decimal
DECLARE @IdxName varchar(128)
DECLARE @pages INT
DECLARE @maxpages INT
DECLARE @ViewOnly bit
DECLARE @ReorgOptions varchar(255)
DECLARE @RebuildOptions varchar(255)


declare @DateTimeStart datetime
set @DateTimeStart = GetDate()


-- Set to 1 to view proposed actions, set to 0 to Execute proposed actions:
SET @ViewOnly=0

-- Decide on the maximum number of pages to consider index for reorg or rebuild:
-- NOTE: Set to 0 if you wish not to consider this value for analysis.
-- Reference http://sqlblog.com/blogs/kalen_delaney/archive/2008/02/28/fragmentation-revisited.aspx
SET @maxpages = 100
-- Decide on the maximum fragmentation to allow for a reorganize:
-- AVAILABLE OPTIONS: http://technet.microsoft.com/en-us/library/ms188388(SQL.90).aspx
SET @maxreorg = 20.0 -- war default
SET @maxreorg = 5.0
SET @ReorgOptions = 'LOB_COMPACTION=ON'
-- Decide on the maximum fragmentation to allow for a rebuild:
SET @maxrebuild = 30.0 -- war default
SET @maxrebuild = 5.0
-- NOTE: only specifiy FILLFACTOR=x if x is a value other than 0 (otherwise do not include the fillfactor option at all):
SET @RebuildOptions = 'PAD_INDEX=OFF, FILLFACTOR=80, SORT_IN_TEMPDB=ON, STATISTICS_NORECOMPUTE=OFF, ALLOW_ROW_LOCKS=ON, ALLOW_PAGE_LOCKS=ON'

-- Declare a cursor to process list of tables:
DECLARE tables CURSOR FOR
SELECT CAST(TABLE_SCHEMA AS VARCHAR(100))
+'.'+CAST(TABLE_NAME AS VARCHAR(100))
AS Table_Name

FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

-- Create the temporary table:
if exists (select name from tempdb.dbo.sysobjects where name like '#fraglist%')
drop table #fraglist

CREATE TABLE #fraglist (
  ObjectName CHAR(255),
  ObjectId INT,
  IndexName CHAR(255),
  IndexId INT,
  Lvl INT,
  CountPages INT,
  CountRows INT,
  MinRecSize INT,
  MaxRecSize INT,
  AvgRecSize INT,
  ForRecCount INT,
  Extents INT,
  ExtentSwitches INT,
  AvgFreeBytes INT,
  AvgPageDensity INT,
  ScanDensity decimal,
  BestCount INT,
  ActualCount INT,
  LogicalFrag decimal,
  ExtentFrag decimal)

-- Open the cursor:
OPEN tables

-- Loop through all the tables in the database:
FETCH NEXT
FROM tables
INTO @tablename

WHILE @@FETCH_STATUS = 0
BEGIN
 -- Perform showcontig on all indexes for the current table:
 INSERT INTO #fraglist
 EXEC ('DBCC SHOWCONTIG (''' + @tablename + ''')
 WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS')
 FETCH NEXT
 FROM tables
 INTO @tablename
END

-- Close and deallocate the cursor:
CLOSE tables
DEALLOCATE tables

-- Declare the cursor for the list of indexes to be defragged:
DECLARE indexes CURSOR FOR
SELECT ObjectName, ObjectId, IndexId, LogicalFrag, IndexName, CountPages
FROM #fraglist
--WHERE ((LogicalFrag >= @maxreorg) OR (LogicalFrag >= @maxrebuild))
WHERE INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') > 0

-- Open the cursor:
OPEN indexes

-- Loop through the indexes:
FETCH NEXT
FROM indexes
INTO @tablename, @objectid, @indexid, @frag, @IdxName, @pages

set @tablenameLast=''
WHILE @@FETCH_STATUS = 0
 BEGIN
 
 if not @tablenameLast=@tablename
  begin
   PRINT '-----------------------------------------------------------------------'
   PRINT 'Table:[' + RTRIM(@tablename)  + ']'
  end
 set @tablenameLast=@tablename
 
 -- Determine if index page count surpasses the defined threshold for needed maintenance:
 IF (@pages >= @maxpages)
  BEGIN
  -- Determine if fragmentation surpasses the defined threshold for rebuilding:
  IF (@frag >= @maxrebuild)
   BEGIN
    IF (@ViewOnly=1)
     BEGIN
      PRINT ' |-> Idx:[' + RTRIM(@IdxName) + '] WOULD be exec ALTER INDEX REBUILD WITH ( ' + @RebuildOptions + ' ) -- Frag.cur:' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '% and Pages were ' + RTRIM(CONVERT(VARCHAR(15),@pages))
     END
    ELSE
     BEGIN
      PRINT ' |-> Idx:[' + RTRIM(@IdxName) + '] Now exec ALTER INDEX REBUILD WITH ( ' + @RebuildOptions + ' ) -- Frag.cur:' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '% and Pages were ' + RTRIM(CONVERT(VARCHAR(15),@pages))
      SELECT @execstr = 'ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REBUILD WITH ( ' + @RebuildOptions + ' )'
      EXEC (@execstr)
     END
   END
  -- Determine if fragmentation surpasses the defined threshold for reorganizing:
  ELSE IF (@frag >= @maxreorg)
   BEGIN
    IF (@ViewOnly=1)
     BEGIN
      PRINT ' |-> Idx:[' + RTRIM(@IdxName) + '] WOULD be exec ALTER INDEX REORGANIZE WITH ( ' + @ReorgOptions + ' ) -- Frag.cur:' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '% and Pages were ' + RTRIM(CONVERT(VARCHAR(15),@pages))
     END
    ELSE
     BEGIN
      PRINT ' |-> Idx:[' + RTRIM(@IdxName) + '] Now exec ALTER INDEX REORGANIZE WITH ( ' + @ReorgOptions + ' ) -- Frag.cur:' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '% and Pages were ' + RTRIM(CONVERT(VARCHAR(15),@pages))
      SELECT @execstr = 'ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REORGANIZE WITH ( ' + @ReorgOptions + ' )'
      EXEC (@execstr)
     END
   END
  ELSE
   BEGIN
    -- PRINT ' |-> BYPASSING INDEX since Frag.cur:' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '% which is less than the Reorg and Rebuild thresholds.'
    PRINT ' |-> Idx:[' + RTRIM(@IdxName) + '] Nothing to do'
   END
  END
  ELSE
   BEGIN
    -- PRINT ' |-> BYPASSING INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' since Page Count was ' + RTRIM(CONVERT(VARCHAR(15),@pages)) + ' which is less than threshold. Frag.cur:' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '%'
    PRINT ' |-> Idx:[' + RTRIM(@IdxName) + '] Nothing to do'
   END

    -- PRINT '--------------------------------------------'
  FETCH NEXT
  FROM indexes
  INTO @tablename, @objectid, @indexid, @frag, @IdxName, @pages
 END

-- Close and deallocate the cursor:
CLOSE indexes
DEALLOCATE indexes

-- Delete the temporary table:
DROP TABLE #fraglist

PRINT '-------------------------------------------------------------------------'
print ('Update Statistic #New 11.06.2015/J.Fes')
  -- UPDATE STATISTICS [dbo].[Objects_tbl] WITH FULLSCAN, ALL;
  -- #toDo: 30.08.2019/A.Becker + J.Fes #Check Methode
  --- https://www.mssqltips.com/sqlservertip/2766/sql-server-auto-update-and-auto-create-statistics-options/
EXEC sp_updatestats @resample='resample'


PRINT '-------------------------------------------------------------------------'
Execute JF_ShowTimeDiffToNow 'Optimise DB:#DB_N#', @DateTimeStart
Print ''
Print '-------------------------------------------------------------------------'
Print ' End of Script : [#DB_N#]'
Print '-------------------------------------------------------------------------'
GO
