usp_AdaptiveIndexDefrag.sql 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104
  1. -- If you are using AdaptiveIndexDefrag together with the maintenance plans in http://blogs.msdn.com/b/blogdoezequiel/archive/2012/09/18/about-maintenance-plans-grooming-sql-server.aspx
  2. -- please note that the job that runs AdaptiveIndexDefrag is expecting msdb. As such, change the database context accordingly.
  3. USE msdb
  4. GO
  5. SET NOCOUNT ON;
  6. DECLARE @deploymode bit
  7. SET @deploymode = 0 /* 0 = Upgrade from immediately previous version, preserving all historic data;
  8. 1 = Rewrite all objects, disregarding historic data */
  9. /* Scroll down to line 429 to the see notes, disclaimers, and licensing information */
  10. RAISERROR('Droping existing objects', 0, 42) WITH NOWAIT;
  11. IF EXISTS(SELECT [object_id] FROM sys.views WHERE [name] = 'vw_CurrentExecStats')
  12. DROP VIEW vw_CurrentExecStats
  13. IF EXISTS(SELECT [object_id] FROM sys.views WHERE [name] = 'vw_ErrLst30Days')
  14. DROP VIEW vw_ErrLst30Days
  15. IF EXISTS(SELECT [object_id] FROM sys.views WHERE [name] = 'vw_LastRun_Log')
  16. DROP VIEW vw_LastRun_Log
  17. IF EXISTS(SELECT [object_id] FROM sys.views WHERE [name] = 'vw_ErrLst24Hrs')
  18. DROP VIEW vw_ErrLst24Hrs
  19. IF EXISTS(SELECT [object_id] FROM sys.views WHERE [name] = 'vw_AvgTimeLst30Days ')
  20. DROP VIEW vw_AvgTimeLst30Days
  21. IF EXISTS(SELECT [object_id] FROM sys.views WHERE [name] = 'vw_AvgFragLst30Days')
  22. DROP VIEW vw_AvgFragLst30Days
  23. IF EXISTS(SELECT [object_id] FROM sys.views WHERE [name] = 'vw_AvgLargestLst30Days')
  24. DROP VIEW vw_AvgLargestLst30Days
  25. IF EXISTS(SELECT [object_id] FROM sys.views WHERE [name] = 'vw_AvgMostUsedLst30Days')
  26. DROP VIEW vw_AvgMostUsedLst30Days
  27. IF @deploymode = 0
  28. BEGIN
  29. RAISERROR('Preserving historic data', 0, 42) WITH NOWAIT;
  30. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_log') AND NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_log_old')
  31. BEGIN
  32. EXEC sp_rename 'tbl_AdaptiveIndexDefrag_log', 'tbl_AdaptiveIndexDefrag_log_old';
  33. EXEC sp_rename N'tbl_AdaptiveIndexDefrag_log_old.PK_AdaptiveIndexDefrag_log', N'PK_AdaptiveIndexDefrag_log_old', N'INDEX';
  34. END;
  35. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_log') AND NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_log_old')
  36. BEGIN
  37. EXEC sp_rename 'tbl_AdaptiveIndexDefrag_Stats_log', 'tbl_AdaptiveIndexDefrag_Stats_log_old';
  38. EXEC sp_rename N'tbl_AdaptiveIndexDefrag_Stats_log_old.PK_AdaptiveIndexDefrag_Stats_log', N'PK_AdaptiveIndexDefrag_Stats_log_old', N'INDEX';
  39. END;
  40. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Exceptions') AND NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Exceptions_old')
  41. BEGIN
  42. EXEC sp_rename 'tbl_AdaptiveIndexDefrag_Exceptions', 'tbl_AdaptiveIndexDefrag_Exceptions_old';
  43. EXEC sp_rename N'tbl_AdaptiveIndexDefrag_Exceptions_old.PK_AdaptiveIndexDefrag_Exceptions', N'PK_AdaptiveIndexDefrag_Exceptions_old', N'INDEX';
  44. END;
  45. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Working') AND NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Working_old')
  46. BEGIN
  47. EXEC sp_rename 'tbl_AdaptiveIndexDefrag_Working', 'tbl_AdaptiveIndexDefrag_Working_old';
  48. EXEC sp_rename N'tbl_AdaptiveIndexDefrag_Working_old.PK_AdaptiveIndexDefrag_Working', N'PK_AdaptiveIndexDefrag_Working_old', N'INDEX';
  49. END;
  50. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_Working') AND NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_Working_old')
  51. BEGIN
  52. EXEC sp_rename 'tbl_AdaptiveIndexDefrag_Stats_Working', 'tbl_AdaptiveIndexDefrag_Stats_Working_old';
  53. EXEC sp_rename N'tbl_AdaptiveIndexDefrag_Stats_Working_old.PK_AdaptiveIndexDefrag_Stats_Working', N'PK_AdaptiveIndexDefrag_Stats_Working_old', N'INDEX';
  54. END;
  55. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_IxDisableStatus') AND NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_IxDisableStatus_old')
  56. BEGIN
  57. EXEC sp_rename 'tbl_AdaptiveIndexDefrag_IxDisableStatus', 'tbl_AdaptiveIndexDefrag_IxDisableStatus_old';
  58. EXEC sp_rename N'tbl_AdaptiveIndexDefrag_IxDisableStatus_old.PK_AdaptiveIndexDefrag_IxDisableStatus', N'PK_AdaptiveIndexDefrag_IxDisableStatus_old', N'INDEX';
  59. END;
  60. END
  61. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_log')
  62. DROP TABLE tbl_AdaptiveIndexDefrag_log;
  63. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_log')
  64. DROP TABLE tbl_AdaptiveIndexDefrag_Stats_log;
  65. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Exceptions')
  66. DROP TABLE tbl_AdaptiveIndexDefrag_Exceptions;
  67. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Working')
  68. DROP TABLE tbl_AdaptiveIndexDefrag_Working;
  69. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_Working')
  70. DROP TABLE tbl_AdaptiveIndexDefrag_Stats_Working;
  71. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_IxDisableStatus')
  72. DROP TABLE tbl_AdaptiveIndexDefrag_IxDisableStatus;
  73. IF OBJECTPROPERTY(OBJECT_ID('dbo.usp_AdaptiveIndexDefrag_PurgeLogs'), N'IsProcedure') = 1
  74. DROP PROCEDURE dbo.usp_AdaptiveIndexDefrag_PurgeLogs;
  75. IF OBJECTPROPERTY(OBJECT_ID('dbo.usp_AdaptiveIndexDefrag_Exceptions'), N'IsProcedure') = 1
  76. DROP PROCEDURE dbo.usp_AdaptiveIndexDefrag_Exceptions;
  77. IF OBJECTPROPERTY(OBJECT_ID('dbo.usp_AdaptiveIndexDefrag_Exclusions'), N'IsProcedure') = 1
  78. DROP PROCEDURE dbo.usp_AdaptiveIndexDefrag_Exclusions;
  79. IF OBJECTPROPERTY(OBJECT_ID('dbo.usp_CurrentExecStats'), N'IsProcedure') = 1
  80. DROP PROCEDURE dbo.usp_CurrentExecStats;
  81. IF OBJECTPROPERTY(OBJECT_ID('dbo.usp_AdaptiveIndexDefrag_CurrentExecStats'), N'IsProcedure') = 1
  82. DROP PROCEDURE dbo.usp_AdaptiveIndexDefrag_CurrentExecStats;
  83. IF NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_log')
  84. CREATE TABLE dbo.tbl_AdaptiveIndexDefrag_log
  85. (indexDefrag_id int identity(1,1) NOT NULL
  86. , dbID int NOT NULL
  87. , dbName NVARCHAR(128) NOT NULL
  88. , objectID int NOT NULL
  89. , objectName NVARCHAR(256) NULL
  90. , indexID int NOT NULL
  91. , indexName NVARCHAR(256) NULL
  92. , partitionNumber smallint
  93. , fragmentation float NOT NULL
  94. , page_count bigint NOT NULL
  95. , range_scan_count bigint NULL
  96. , fill_factor int NULL
  97. , dateTimeStart DATETIME NOT NULL
  98. , dateTimeEnd DATETIME NULL
  99. , durationSeconds int NULL
  100. , sqlStatement VARCHAR(4000) NULL
  101. , errorMessage VARCHAR(1000) NULL
  102. CONSTRAINT PK_AdaptiveIndexDefrag_log PRIMARY KEY CLUSTERED (indexDefrag_id));
  103. CREATE INDEX IX_tbl_AdaptiveIndexDefrag_log ON [dbo].[tbl_AdaptiveIndexDefrag_log] ([dbID], [objectID], [indexName], [dateTimeEnd]);
  104. RAISERROR('tbl_AdaptiveIndexDefrag_log table created', 0, 42) WITH NOWAIT;
  105. IF NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Exceptions')
  106. CREATE TABLE dbo.tbl_AdaptiveIndexDefrag_Exceptions
  107. (dbID int NOT NULL
  108. , objectID int NOT NULL
  109. , indexID int NOT NULL
  110. , dbName NVARCHAR(128) NOT NULL
  111. , objectName NVARCHAR(256) NOT NULL
  112. , indexName NVARCHAR(256) NOT NULL
  113. , exclusionMask int NOT NULL
  114. /* Same as in msdb.dbo.sysschedules:
  115. 1=Sunday, 2=Monday, 4=Tuesday, 8=Wednesday, 16=Thursday, 32=Friday, 64=Saturday, 0=AllWeek, -1=Never
  116. For multiple days, sum the corresponding values*/
  117. CONSTRAINT PK_AdaptiveIndexDefrag_Exceptions PRIMARY KEY CLUSTERED (dbID, objectID, indexID));
  118. RAISERROR('tbl_AdaptiveIndexDefrag_Exceptions table created', 0, 42) WITH NOWAIT;
  119. IF NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Working')
  120. CREATE TABLE dbo.tbl_AdaptiveIndexDefrag_Working
  121. (dbID int
  122. , objectID int
  123. , indexID int
  124. , partitionNumber smallint
  125. , dbName NVARCHAR(128)
  126. , schemaName NVARCHAR(128) NULL
  127. , objectName NVARCHAR(256) NULL
  128. , indexName NVARCHAR(256) NULL
  129. , fragmentation float
  130. , page_count int
  131. , is_primary_key bit
  132. , fill_factor int
  133. , is_disabled bit
  134. , is_padded bit
  135. , is_hypothetical bit
  136. , has_filter bit
  137. , allow_page_locks bit
  138. , range_scan_count bigint NULL
  139. , record_count bigint
  140. , [type] tinyint -- 0 = Heap; 1 = Clustered; 2 = Nonclustered; 3 = XML; 4 = Spatial; 5 = Clustered columnstore; 6 = Nonclustered columnstore; 7 = Nonclustered hash
  141. , scanDate DATETIME
  142. , defragDate DATETIME NULL
  143. , printStatus bit DEFAULT(0) -- Used for loop control when printing the SQL commands.
  144. , exclusionMask int DEFAULT(0)
  145. CONSTRAINT PK_AdaptiveIndexDefrag_Working PRIMARY KEY CLUSTERED(dbID, objectID, indexID, partitionNumber));
  146. RAISERROR('tbl_AdaptiveIndexDefrag_Working table created', 0, 42) WITH NOWAIT;
  147. IF NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_Working')
  148. CREATE TABLE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  149. (dbID int
  150. , objectID int
  151. , statsID int
  152. , partitionNumber smallint
  153. , dbName NVARCHAR(128)
  154. , schemaName NVARCHAR(128) NULL
  155. , objectName NVARCHAR(256) NULL
  156. , statsName NVARCHAR(256)
  157. , [no_recompute] bit
  158. , [is_incremental] bit
  159. , scanDate DATETIME
  160. , updateDate DATETIME NULL
  161. , printStatus bit DEFAULT(0) -- Used for loop control when printing the SQL commands.
  162. CONSTRAINT PK_AdaptiveIndexDefrag_Stats_Working PRIMARY KEY CLUSTERED(dbID, objectID, statsID, partitionNumber));
  163. RAISERROR('tbl_AdaptiveIndexDefrag_Stats_Working table created', 0, 42) WITH NOWAIT;
  164. IF NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_log')
  165. CREATE TABLE dbo.tbl_AdaptiveIndexDefrag_Stats_log
  166. (statsUpdate_id int identity(1,1) NOT NULL
  167. , dbID int NOT NULL
  168. , dbName NVARCHAR(128) NULL
  169. , objectID int NOT NULL
  170. , objectName NVARCHAR(256) NULL
  171. , statsID int NOT NULL
  172. , statsName NVARCHAR(256) NULL
  173. , partitionNumber smallint
  174. , [rows] bigint
  175. , rows_sampled bigint
  176. , modification_counter bigint
  177. , [no_recompute] bit
  178. , dateTimeStart DATETIME NOT NULL
  179. , dateTimeEnd DATETIME NULL
  180. , durationSeconds int NULL
  181. , sqlStatement VARCHAR(4000) NULL
  182. , errorMessage VARCHAR(1000) NULL
  183. CONSTRAINT PK_AdaptiveIndexDefrag_Stats_log PRIMARY KEY CLUSTERED (statsUpdate_id));
  184. CREATE INDEX IX_tbl_AdaptiveIndexDefrag_Stats_log ON [dbo].[tbl_AdaptiveIndexDefrag_Stats_log] ([dbID], [objectID], [statsName], [dateTimeEnd]);
  185. RAISERROR('tbl_AdaptiveIndexDefrag_Stats_log table created', 0, 42) WITH NOWAIT;
  186. IF NOT EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_IxDisableStatus')
  187. CREATE TABLE dbo.tbl_AdaptiveIndexDefrag_IxDisableStatus
  188. (disable_id int identity(1,1) NOT NULL
  189. , dbID int NOT NULL
  190. , objectID int NOT NULL
  191. , indexID int NOT NULL
  192. , [is_disabled] bit
  193. , dateTimeChange DATETIME NOT NULL
  194. CONSTRAINT PK_AdaptiveIndexDefrag_IxDisableStatus PRIMARY KEY CLUSTERED (disable_id));
  195. RAISERROR('tbl_AdaptiveIndexDefrag_IxDisableStatus table created', 0, 42) WITH NOWAIT;
  196. IF @deploymode = 0
  197. BEGIN
  198. RAISERROR('Copying old data...', 0, 42) WITH NOWAIT;
  199. BEGIN TRY
  200. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_log') AND EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_log_old')
  201. INSERT INTO tbl_AdaptiveIndexDefrag_log ([dbID],[dbName],[objectID],[objectName]
  202. ,[indexID],[indexName],[partitionNumber],[fragmentation],[page_count]
  203. ,[range_scan_count],[fill_factor],[dateTimeStart],[dateTimeEnd]
  204. ,[durationSeconds],[sqlStatement],[errorMessage])
  205. SELECT [dbID],[dbName],[objectID],[objectName],[indexID]
  206. ,[indexName],[partitionNumber],[fragmentation],[page_count]
  207. ,[range_scan_count],[fill_factor],[dateTimeStart],[dateTimeEnd]
  208. ,[durationSeconds],[sqlStatement],[errorMessage]
  209. FROM tbl_AdaptiveIndexDefrag_log_old;
  210. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_log') AND EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_log_old')
  211. BEGIN
  212. IF EXISTS (SELECT sc.column_id FROM sys.tables st INNER JOIN sys.columns sc ON st.[object_id] = sc.[object_id] WHERE sc.[name] = 'partitionNumber' AND sc.[name] = 'rows' AND sc.[name] = 'rows_sampled' AND sc.[name] = 'modification_counter' AND st.[name] = 'tbl_AdaptiveIndexDefrag_Stats_log_old')
  213. BEGIN
  214. EXEC ('INSERT INTO tbl_AdaptiveIndexDefrag_Stats_log ([dbID],[dbName],[objectID],[objectName],[statsID],[statsName],[partitionNumber],[rows],rows_sampled,modification_counter,[no_recompute],[dateTimeStart],[dateTimeEnd],[durationSeconds],[sqlStatement],[errorMessage])
  215. SELECT [dbID],[dbName],[objectID],[objectName],[statsID],[statsName],[partitionNumber],[rows],rows_sampled,modification_counter,[no_recompute],[dateTimeStart],[dateTimeEnd],[durationSeconds],[sqlStatement],[errorMessage]
  216. FROM tbl_AdaptiveIndexDefrag_Stats_log_old;')
  217. END
  218. ELSE IF EXISTS (SELECT sc.column_id FROM sys.tables st INNER JOIN sys.columns sc ON st.[object_id] = sc.[object_id] WHERE sc.[name] = 'partitionNumber' AND st.[name] = 'tbl_AdaptiveIndexDefrag_Stats_log_old')
  219. BEGIN
  220. EXEC ('INSERT INTO tbl_AdaptiveIndexDefrag_Stats_log ([dbID],[dbName],[objectID],[objectName],[statsID],[statsName],[partitionNumber],[rows],rows_sampled,modification_counter,[no_recompute],[dateTimeStart],[dateTimeEnd],[durationSeconds],[sqlStatement],[errorMessage])
  221. SELECT [dbID],[dbName],[objectID],[objectName],[statsID],[statsName],[partitionNumber],-1,-1,-1,[no_recompute],[dateTimeStart],[dateTimeEnd],[durationSeconds],[sqlStatement],[errorMessage]
  222. FROM tbl_AdaptiveIndexDefrag_Stats_log_old;')
  223. END
  224. ELSE
  225. BEGIN
  226. EXEC ('INSERT INTO tbl_AdaptiveIndexDefrag_Stats_log ([dbID],[dbName],[objectID],[objectName],[statsID],[statsName],[partitionNumber],[rows],rows_sampled,modification_counter,[no_recompute],[dateTimeStart],[dateTimeEnd],[durationSeconds],[sqlStatement],[errorMessage])
  227. SELECT [dbID],[dbName],[objectID],[objectName],[statsID],[statsName],1,-1,-1,-1,[no_recompute],[dateTimeStart],[dateTimeEnd],[durationSeconds],[sqlStatement],[errorMessage]
  228. FROM tbl_AdaptiveIndexDefrag_Stats_log_old;')
  229. END
  230. END
  231. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Exceptions') AND EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Exceptions_old')
  232. INSERT INTO tbl_AdaptiveIndexDefrag_Exceptions ([dbID],[objectID],[indexID],[dbName]
  233. ,[objectName],[indexName],[exclusionMask])
  234. SELECT [dbID],[objectID],[indexID],[dbName]
  235. ,[objectName],[indexName],[exclusionMask]
  236. FROM tbl_AdaptiveIndexDefrag_Exceptions_old;
  237. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Working') AND EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Working_old')
  238. INSERT INTO tbl_AdaptiveIndexDefrag_Working ([dbID],[objectID],[indexID],[partitionNumber]
  239. ,[dbName],[schemaName],[objectName],[indexName],[fragmentation]
  240. ,[page_count],[fill_factor],[is_disabled],[is_padded],[is_hypothetical]
  241. ,[has_filter],[allow_page_locks],[range_scan_count],[record_count]
  242. ,[type],[scanDate],[defragDate],[printStatus],[exclusionMask])
  243. SELECT [dbID],[objectID],[indexID],[partitionNumber],[dbName]
  244. ,[schemaName],[objectName],[indexName],[fragmentation],[page_count]
  245. ,[fill_factor],[is_disabled],[is_padded],[is_hypothetical],[has_filter]
  246. ,[allow_page_locks],[range_scan_count],[record_count],[type],[scanDate]
  247. ,[defragDate],[printStatus],[exclusionMask]
  248. FROM tbl_AdaptiveIndexDefrag_Working_old;
  249. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_Working') AND EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_Working_old')
  250. BEGIN
  251. IF EXISTS (SELECT sc.column_id FROM sys.tables st INNER JOIN sys.columns sc ON st.[object_id] = sc.[object_id] WHERE (sc.[name] = 'partitionNumber' OR sc.[name] = 'is_incremental') AND st.[name] = 'tbl_AdaptiveIndexDefrag_Stats_Working_old')
  252. BEGIN
  253. EXEC ('INSERT INTO tbl_AdaptiveIndexDefrag_Stats_Working ([dbID],[objectID],[statsID],[dbName],[schemaName],[objectName],[statsName],[partitionNumber],[no_recompute],[is_incremental],[scanDate],[updateDate],[printStatus])
  254. SELECT [dbID],[objectID],[statsID],[dbName],[schemaName],[objectName],[statsName],[partitionNumber],[no_recompute],[is_incremental],[scanDate],[updateDate],[printStatus]
  255. FROM tbl_AdaptiveIndexDefrag_Stats_Working_old;')
  256. END
  257. ELSE
  258. BEGIN
  259. EXEC ('INSERT INTO tbl_AdaptiveIndexDefrag_Stats_Working ([dbID],[objectID],[statsID],[dbName],[schemaName],[objectName],[statsName],[partitionNumber],[no_recompute],[is_incremental],[scanDate],[updateDate],[printStatus])
  260. SELECT [dbID],[objectID],[statsID],[dbName],[schemaName],[objectName],[statsName],1,[no_recompute],0,[scanDate],[updateDate],[printStatus]
  261. FROM tbl_AdaptiveIndexDefrag_Stats_Working_old;')
  262. END
  263. END
  264. IF EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_IxDisableStatus') AND EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_IxDisableStatus_old')
  265. INSERT INTO tbl_AdaptiveIndexDefrag_IxDisableStatus ([dbID],[objectID],[indexID],[is_disabled],dateTimeChange)
  266. SELECT [dbID],[objectID],[indexID],[is_disabled],dateTimeChange
  267. FROM tbl_AdaptiveIndexDefrag_IxDisableStatus_old;
  268. END TRY
  269. BEGIN CATCH
  270. RAISERROR('Could not copy old data back. Check for any previous errors.', 15, 42) WITH NOWAIT;
  271. RETURN
  272. END CATCH
  273. RAISERROR('Done copying old data...', 0, 42) WITH NOWAIT;
  274. IF EXISTS (SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_log_old')
  275. BEGIN
  276. IF (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_log_old) = (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_log)
  277. DROP TABLE tbl_AdaptiveIndexDefrag_log_old
  278. END;
  279. IF EXISTS (SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_log_old')
  280. BEGIN
  281. IF (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Stats_log_old) = (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Stats_log)
  282. DROP TABLE tbl_AdaptiveIndexDefrag_Stats_log_old
  283. END;
  284. IF EXISTS (SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Exceptions_old')
  285. BEGIN
  286. IF (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Exceptions_old) = (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Exceptions)
  287. DROP TABLE tbl_AdaptiveIndexDefrag_Exceptions_old
  288. END;
  289. IF EXISTS (SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Working_old')
  290. BEGIN
  291. IF (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Working_old) = (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Working)
  292. DROP TABLE tbl_AdaptiveIndexDefrag_Working_old
  293. END;
  294. IF EXISTS (SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_Working_old')
  295. BEGIN
  296. IF (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Stats_Working_old) = (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Stats_Working)
  297. DROP TABLE tbl_AdaptiveIndexDefrag_Stats_Working_old
  298. END;
  299. IF EXISTS (SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_IxDisableStatus_old')
  300. BEGIN
  301. IF (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_IxDisableStatus_old) = (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_IxDisableStatus)
  302. DROP TABLE tbl_AdaptiveIndexDefrag_IxDisableStatus_old
  303. END;
  304. IF EXISTS (SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_Working_old')
  305. OR EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_log_old')
  306. OR EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Stats_log_old')
  307. OR EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Exceptions_old')
  308. OR EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_Working_old')
  309. OR EXISTS(SELECT [object_id] FROM sys.tables WHERE [name] = 'tbl_AdaptiveIndexDefrag_IxDisableStatus_old')
  310. BEGIN
  311. RAISERROR('Data mismatch. Keeping some or all old tables as <tablename_old>.', 0, 42) WITH NOWAIT;
  312. END
  313. ELSE
  314. BEGIN
  315. RAISERROR('Removed old tables...', 0, 42) WITH NOWAIT;
  316. END
  317. END;
  318. GO
  319. ------------------------------------------------------------------------------------------------------------------------------
  320. IF OBJECTPROPERTY(OBJECT_ID('dbo.usp_AdaptiveIndexDefrag'), N'IsProcedure') = 1
  321. BEGIN
  322. DROP PROCEDURE dbo.usp_AdaptiveIndexDefrag;
  323. PRINT 'Procedure usp_AdaptiveIndexDefrag dropped';
  324. END;
  325. GO
  326. CREATE PROCEDURE dbo.usp_AdaptiveIndexDefrag
  327. @Exec_Print bit = 1
  328. /* 1 = execute commands; 0 = print commands only */
  329. , @printCmds bit = 0
  330. /* 1 = print commands; 0 = do not print commands */
  331. , @outputResults bit = 0
  332. /* 1 = output fragmentation information;
  333. 0 = do not output */
  334. , @debugMode bit = 0
  335. /* display some useful comments to help determine if/where issues occur
  336. 1 = display debug comments;
  337. 0 = do not display debug comments*/
  338. , @timeLimit int = 480 /* defaults to 8 hours */
  339. /* Optional time limitation; expressed in minutes */
  340. , @dbScope NVARCHAR(256) = NULL
  341. /* Option to specify a database name; NULL will return all */
  342. , @tblName NVARCHAR(1000) = NULL -- schema.table_name
  343. /* Option to specify a table name; NULL will return all */
  344. , @defragOrderColumn NVARCHAR(20) = 'range_scan_count'
  345. /* Valid options are: range_scan_count, fragmentation, page_count */
  346. , @defragSortOrder NVARCHAR(4) = 'DESC'
  347. /* Valid options are: ASC, DESC */
  348. , @forceRescan bit = 0
  349. /* Whether to force a rescan of indexes into the tbl_AdaptiveIndexDefrag_Working table or not;
  350. 1 = force, 0 = use existing scan when available, used to continue where previous run left off */
  351. , @defragDelay CHAR(8) = '00:00:05'
  352. /* time to wait between defrag commands */
  353. , @ixtypeOption bit = NULL
  354. /* NULL = all indexes will be defragmented; 1 = only Clustered indexes will be defragmented; 0 = only Non-Clustered indexes will be defragmented (includes XML and Spatial); */
  355. , @minFragmentation float = 5.0
  356. /* in percent, will not defrag if fragmentation is less than specified */
  357. , @rebuildThreshold float = 30.0
  358. /* in percent, greater than @rebuildThreshold will result in rebuild instead of reorg */
  359. , @rebuildThreshold_cs float = 10.0
  360. /* in percent, greater than @rebuildThreshold_cs will result in rebuild the columnstore index */
  361. , @minPageCount int = 8
  362. /* Recommended is defrag when index is at least > 1 extent (8 pages) */
  363. , @maxPageCount int = NULL
  364. /* NULL = no limit */
  365. , @fillfactor bit = 1
  366. /* 1 = original from when the index was created or last defraged;
  367. 0 = default fillfactor */
  368. , @scanMode VARCHAR(10) = N'LIMITED'
  369. /* Options are LIMITED, SAMPLED, and DETAILED */
  370. , @onlineRebuild bit = 0
  371. /* 1 = online rebuild; 0 = offline rebuild; only in Enterprise Edition */
  372. , @sortInTempDB bit = 0
  373. /* 1 = perform sort operation in TempDB; 0 = perform sort operation in the indexes database */
  374. , @maxDopRestriction tinyint = NULL
  375. /* Option to restrict the number of processors for the operation; only in Enterprise Edition */
  376. , @updateStats bit = 1
  377. /* 1 = updates stats when reorganizing; 0 = does not update stats when reorganizing */
  378. , @updateStatsWhere bit = 0
  379. /* 1 = updates only index related stats; 0 = updates all stats in table */
  380. , @statsSample NCHAR(8) = NULL
  381. /* Valid options are: NULL, FULLSCAN, and RESAMPLE */
  382. , @ix_statsnorecompute bit = 0
  383. /* 1 = STATISTICS_NORECOMPUTE on; 0 = default which is with STATISTICS_NORECOMPUTE off */
  384. , @statsIncremental bit = NULL
  385. /* NULL = Keep server setting; 1 = Enable auto create statistics with Incremental; 0 = Disable auto create statistics with Incremental */
  386. , @dealMaxPartition bit = 0
  387. /* 0 = only right-most partition; 1 = exclude right-most populated partition; NULL = do not exclude; see notes for caveats; only in Enterprise Edition */
  388. , @dealLOB bit = 0
  389. /* 0 = compact LOBs when reorganizing (default behavior); 1 = does not compact LOBs when reorganizing */
  390. , @ignoreDropObj bit = 0
  391. /* 0 = includes errors about objects that have been dropped since the defrag cycle began (default behavior);
  392. 1 = for error reporting purposes, ignores the fact that objects have been dropped since the defrag cycle began */
  393. , @disableNCIX bit = 0
  394. /* 0 = does NOT disable non-clustered indexes prior to a rebuild;
  395. 1 = disables non-clustered indexes prior to a rebuild, if the database is not being replicated (space saving feature) */
  396. , @offlinelocktimeout int = -1
  397. /* -1 = (default) indicates no time-out period; Any other positive integer sets the number of milliseconds that will pass before Microsoft SQL Server returns a locking error */
  398. , @onlinelocktimeout int = 5
  399. /* 5 = (default) indicates a time-out period for locks to wait at low priority, expressed in minutes; this is valid from SQL Server 2014 onwards */
  400. , @abortAfterwait bit = 1
  401. /* NULL = (default) After lock timeout occurs, continue waiting for the lock with normal (regular) priority;
  402. 0 = Kill all user transactions that block the online index rebuild DDL operation so that the operation can continue.
  403. 1 = Exit the online index rebuild DDL operation currently being executed without taking any action.*/
  404. , @dealROWG bit = 0
  405. /* 0 = (default) compress closed rowgroups on columnstore.
  406. 1 = compress all rowgroups on columnstore, and not just closed ones.*/
  407. , @getBlobfrag bit = 0
  408. /* 0 = (default) exclude blobs from fragmentation scan.
  409. 1 = include blobs and off-row data when scanning for fragmentation.*/
  410. AS
  411. /*
  412. usp_AdaptiveIndexDefrag.sql - [email protected] (http://blogs.msdn.com/b/blogdoezequiel/)
  413. Inspired by Michelle Ufford (http://sqlfool.com)
  414. PURPOSE: Intelligent defrag on one or more indexes for one or more databases.
  415. DISCLAIMER:
  416. This code is not supported under any Microsoft standard support program or service.
  417. This code and information are provided "AS IS" without warranty of any kind, either expressed or implied.
  418. The entire risk arising out of the use or performance of the script and documentation remains with you.
  419. Furthermore, Microsoft, the author or "Blog do Ezequiel" team shall not be liable for any damages you may sustain by using this information, whether direct,
  420. indirect, special, incidental or consequential, including, without limitation, damages for loss of business profits, business interruption, loss of business information
  421. or other pecuniary loss even if it has been advised of the possibility of such damages.
  422. Read all the implementation and usage notes thoroughly.
  423. CHANGE LOG:
  424. v1 - 08-02-2011 - Initial release
  425. v1.1 - 15-02-2011 - Added support for maintaining current index padding options;
  426. Added logic for Exception of hypothetical objects;
  427. Deal with LOB compaction when reorganizing;
  428. Corrected bug with update stats kicking in when not supposed to;
  429. Corrected options not compatible with partitioned indexes;
  430. v1.2 - 10-03-2011 - Increased control over new or changed database handling;
  431. v1.2.1 - 22-03-2011 - Corrected method of finding available processors;
  432. v1.3 - 21-06-2011 - Added more options to act upon statistics (IX related or Table-wide);
  433. Added finer thresholds for updates on table-wide statistics when reorganizing (when SAMPLED or DETAILED scanMode is selected);
  434. Added option for no_recompute on index REBUILD;
  435. Added restrictions for spatial and XML indexes;
  436. Always rebuild filtered indexes;
  437. If found, output list of disabled or hypothetical indexes so that you can act on them;
  438. Added range scan count to logging table for comparison;
  439. Added update index related stats (with defaults) before rebuild operations. This provides better cardinality estimation, and thus a more time-efficient operation when rebuilding;
  440. Bug fix in Reorganize statements.
  441. Bug fix in one Rescanning condition.
  442. v1.3.1 - 28-06-2011 - Corrected issue with commands running on multiple partitions.
  443. Changed behaviour of update statistics when tables have multiple partitions.
  444. v1.3.2 - 01-07-2011 - Changed objects named %Exclusions to %Exceptions. When re-deploying, existing %Exclusions table will be renamed and not recreated.
  445. Added procedure to check current batch execution progress (usp_CurrentExecStats)
  446. v1.3.3 - 08-07-2011 - Corrected issue where explicit change in database scope parameter did not trigger rescan under certain conditions.
  447. Corrected statistics update thresholds.
  448. v1.3.4 - 22-07-2011 - Bug fix in indexes information regarding the sql version.
  449. v1.3.5 - 15-11-2011 - Bug fix in logging showing as NULL on some issued commands.
  450. Optimizations on support SP usp_AdaptiveIndexDefrag_Exceptions.
  451. v1.3.6 - 17-02-2012 - Allow larger object names in tables and indexes.
  452. v1.3.7 - 27-02-2012 - Enhanced error reporting view to incorporate stats updates;
  453. Bug fix when certain index options were chosen together.
  454. v1.3.8 - 28-02-2012 - Corrected view that reports last run;
  455. Added upgrade mode.
  456. v1.3.9 - 12-03-2012 - Fixed upgrade mode in case old data cannot be copied back.
  457. v1.4.0 - 12-04-2012 - Fixed issue with collation sensitive servers.
  458. v1.4.1 - 17-05-2012 - Fixed issue on support SP usp_AdaptiveIndexDefrag_Exceptions.
  459. v1.4.2 - 29-05-2012 - Fixed issue on support SP usp_AdaptiveIndexDefrag_CurrentExecStats,
  460. Fixed issue with large object IDs.
  461. v1.4.3 - 29-08-2012 - Fixed issue with upgrade mode data retention,
  462. Fixed issue with format dependent conversions.
  463. v1.4.4 - 10-09-2012 - Fixed issue where running the procedure to print commands only, previous execution errors would still be reported.
  464. v1.4.5 - 12-10-2012 - Added support for ignoring errors regarding database objects that were dropped since the defrag cycle began;
  465. Added support for disabling indexes before rebuilding (space saving feature) - see notes below on parameter @disableNCIX.
  466. v1.4.6 - 23-01-2013 - Added hard limit of 4 for MaxDOP setting;
  467. Changed default for statistics update to updates all stats in table, as opposed to just index related stats;
  468. Fixed issue on support SP usp_AdaptiveIndexDefrag_CurrentExecStats reporting incorrect number of already defraged indexes;
  469. Fixed null elimination message with vw_LastRun_Log;
  470. Incremented debug mode output;
  471. Redesigned table wide statistics update (updateStatsWhere parameter);
  472. Fixed issue with upgrade mode leaving old tables behind.
  473. v1.4.7 - 28-01-2013 - Fixed issue with exceptions not working with on some days i.e, on a day that should not be doing anything, it did;
  474. Tuned online rebuild options;
  475. Redesigned support SP usp_AdaptiveIndexDefrag_Exceptions.
  476. v1.4.9 - 11-04-2013 - Added support for Enterprise Core Edition;
  477. Added support for Always On secondary replicas;
  478. Changed maxdop hard limit to 8;
  479. Added support for sys.dm_db_stats_properties in statistics update, if on SQL 2008R2 SP2 or SQL 2012 SP1 or higher.
  480. v1.5.0 - 25-04-2013 - Fixed issue with online rebuilds;
  481. Fixed issue with commands not being printed when choosing @ExecPrint = 0.
  482. v1.5.1 - 01-05-2013 - Fixed issue with page locking off and trying index reorganize - should always rebuild;
  483. Fixed issue with specific db scope and Always On replica checking;
  484. Enhanced stats lookup for specific table scope;
  485. Fixed issue where disable index would also do extra update on previous index related statistic;
  486. Added support for online rebuild with LOBs in SQL Server 2012.
  487. v1.5.1.1- 02-05-2013 - Fixed MaxDOP issue introduced in v1.4.9;
  488. Fixed issue with DETAILED scan mode;
  489. Fixed issue with extended indexes not being picked up.
  490. v1.5.1.2- 05-05-2013 - Fixed issue with print command while executing introduced in v1.5.1;
  491. Fixed issue where a statistics update error would show in the log associated with an XML or Spatial index.
  492. v1.5.1.4- 10-05-2013 - Fixed issue with statistics update when there is no work to be done, introduced in v1.5.1.
  493. v1.5.2 - 17-06-2013 - Added option for lock timeout;
  494. Set deadlock priority to lowest possible;
  495. Simulate TF 2371 behavior on update statistics threshold;
  496. Fixed issue with @updateStatsWhere = 1 where not all non-index related statistics were updated.
  497. v1.5.3 - 02-07-2013 - Fixed issue with updating statistics and XML indexes;
  498. Fixed issue with log data being partially overwritten;
  499. Fixed issue where using @fillfactor to reset fill factor to default would not actually reset.
  500. v1.5.3.1- 08-07-2013 - Fixed issue where using @fillfactor to reset fill factor to default would output command error.
  501. v1.5.4 - 12-09-2013 - Changed system database exclusion choices;
  502. Fixed fill factor information not getting logged (thanks go to Chuck Lathrope);
  503. All statistics update now included in exception days rule.
  504. Changed partition handling to avoid unwarranted scanning and speed up process on tables with many partitions.
  505. v1.5.5 - 24-10-2013 - Added more verbose to debug mode;
  506. Fixed issue with error while keeping original fill factor when it was already set to 0 on the index;
  507. Fixed issue with error 35337 or 2706 on update statistics.
  508. v1.5.6 - 27-11-2013 - Added SQL 2014 support for online partition rebuild;
  509. Tuned LOB support with online operations;
  510. Improved detection of scope changes - saves unneeded database scans;
  511. Optimized defrag cycle pre-work with partially excluded DBs;
  512. Fixed issue with skipping partially excluded databases;
  513. Added resilience for CS collations.
  514. v1.5.7 - 14-01-2014 - Fixed issue on support SP usp_AdaptiveIndexDefrag_Exceptions with SQL Server 2005;
  515. Fixed issue with support SP usp_AdaptiveIndexDefrag_CurrentExecStats.
  516. v1.5.8 - 10-05-2014 - Added SQL 2014 support for Online Lock Priority;
  517. Fixed issue introduced in previous version where an Online rebuild operation could not be executed in SQL 2012.
  518. v1.5.9 - 17-11-2014 - Fixed issue on support SP usp_AdaptiveIndexDefrag_PurgeLogs.
  519. v1.6 - 18-11-2014 - Added resilience when objects are dropped while being scanned, avoiding error 2573.
  520. v1.6.1 - 04-02-2015 - Removed dependency of @scan_mode to use TF 2371 behavior for statistics update;
  521. Improved support for Columnstore indexes on SQL 2014, with specific rebuild threshold and reorg option.
  522. v1.6.2 - 10/3/2016 - Added option to determine whether to exclude blobs from fragmentation scan;
  523. Added support for incremental statistics;
  524. Fixed PK issue with columnstore fragmentation discovery.
  525. Fixed issue where auto created statistics would not be picked up for update.
  526. v1.6.3 - 10/14/2016 - Fixed issue with statistics collection in SQL Server 2012 and below;
  527. Fixed issue where indexes on views generated error 1934.
  528. v1.6.3.1 - 10/26/2016 - Fixed failed migration from v1.6.2 with NULL insert error;
  529. Fixed issue when running in debug mode.
  530. v1.6.3.2 - 11/4/2016 - Fixed DISABLE index applying to NCCI.
  531. Fixed statistics not being updated before index rebuild - introduced in v1.6.2;
  532. Fixed misplaced index disable statement if @Exec_Print = 0;
  533. Fixed issue with statistics collection in SQL Server 2012 and below;
  534. Added statistic related info to log table (rows, mod counter, rows sampled).
  535. IMPORTANT:
  536. Execute in the database context of where you created the log and working tables.
  537. ALL parameters are optional. If not specified, the defaults for each parameter are used.
  538. @Exec_Print 1 = execute the SQL code generated by this SP;
  539. 0 = print commands only
  540. @printCmds 1 = print commands to screen;
  541. 0 = do not print commands
  542. @outputResults 1 = output fragmentation information after run completes;
  543. 0 = do not output fragmentation information
  544. @debugMode 1 = display debug comments;
  545. 0 = do not display debug comments
  546. @timeLimit Limits how much time can be spent performing index defrags; expressed in minutes.
  547. NOTE: The time limit is checked BEFORE an index defrag begins, thus a long index defrag can exceed the time limit.
  548. @dbScope Specify specific database name to defrag; if not specified, all non-system databases plus msdb and model will be defragmented.
  549. @tblName Specify if you only want to defrag indexes for a specific table, format = schema.table_name; if not specified, all tables will be defragmented.
  550. @defragOrderColumn Defines how to prioritize the order of defrags. Only used if @Exec_Print = 1.
  551. range_scan_count = count of range and table scans on the index; this is what can benefit the most from defragmentation;
  552. fragmentation = amount of fragmentation in the index;
  553. page_count = number of pages in the index; bigger indexes can take longer to defrag and thus generate more contention; may want to start with these;
  554. @defragSortOrder The sort order of the ORDER BY clause on the above query on how to prioritize the order of defrags.
  555. ASC (ascending)
  556. DESC (descending) is the default.
  557. @forceRescan Action on index rescan. If = 0, a rescan will not occur until all indexes have been defragmented. This can span multiple executions.
  558. 1 = force a rescan
  559. 0 = use previous scan, if there are indexes left to defrag
  560. @defragDelay Time to wait between defrag commands; gives the server a breathe between runs
  561. @ixtypeOption NULL = all indexes will be defragmented;
  562. 1 = only Clustered indexes will be defragmented;
  563. 0 = only Non-Clustered indexes will be defragmented (includes XML and Spatial Indexes);
  564. @minFragmentation Defaults to 5%, will not defrag if fragmentation is less.
  565. Refer to http://msdn.microsoft.com/en-us/library/ms189858.aspx
  566. @rebuildThreshold Defaults to 30%. greater than 30% will result in rebuild instead of reorganize.
  567. Refer to http://msdn.microsoft.com/en-us/library/ms189858.aspx
  568. @rebuildThreshold_csDefaults to 10%. Greater than 10% will result in columnstore rebuild.
  569. Refer to https://msdn.microsoft.com/en-us/data/dn589807(v=sql.120)
  570. @minPageCount Specifies how many pages must exist in an index in order to be considered for a defrag. Default to an extent. Refer to http://msdn.microsoft.com/en-us/library/ms189858.aspx
  571. NOTE: The @minPageCount will restrict the indexes that are stored in tbl_AdaptiveIndexDefrag_Working table and can render other options inoperative.
  572. @maxPageCount Specifies the maximum number of pages that can exist in an index and still be considered for a defrag.
  573. Useful for scheduling small indexes during business hours and large indexes for non-business hours.
  574. NOTE: The @maxPageCount will restrict the indexes selective for defrag;
  575. @fillfactor 1 = original from when the index was created or last defragmented;
  576. 0 = default fill factor
  577. @scanMode Specifies which scan mode to use to determine fragmentation levels. Options are:
  578. LIMITED = the fastest mode and scans the smallest number of pages.
  579. For an index, only the parent-level pages of the B-tree (that is, the pages above the leaf level) are scanned.
  580. For a heap, only the associated PFS and IAM pages are examined; the data pages of the heap are not scanned.
  581. Recommended for most cases.
  582. SAMPLED = returns statistics based on a 1 percent sample of all the pages in the index or heap.
  583. If the index or heap has fewer than 10,000 pages, DETAILED mode is used instead of SAMPLED.
  584. DETAILED = scans all pages and returns all statistics. Can cause performance issues.
  585. @onlineRebuild 1 = online rebuild if possible; only in Enterprise Edition;
  586. 0 = offline rebuild
  587. @sortInTempDB When 1, the sort results are stored in TempDB. When 0, the sort results are stored in the filegroup or partition scheme in which the resulting index is stored.
  588. If a sort operation is not required, or if the sort can be performed in memory, SORT_IN_TEMPDB is ignored.
  589. Enabling this option can result in faster defrags and prevent database file size inflation. Just have monitor TempDB closely.
  590. More information here: http://msdn.microsoft.com/en-us/library/ms188281.aspx and http://msdn.microsoft.com/en-us/library/ms179542.aspx and http://msdn.microsoft.com/en-us/library/ms191183.aspx
  591. 1 = perform sort operation in TempDB
  592. 0 = perform sort operation in the indexes database
  593. @maxDopRestriction Option to specify a processor limit for index rebuilds
  594. @updateStats 1 = updates stats when reorganizing;
  595. 0 = does not update stats when reorganizing
  596. @updateStatsWhere Update statistics within certain thresholds (http://support.microsoft.com/kb/195565/en-us)
  597. 1 = updates only index related stats;
  598. 0 = updates all stats in entire table
  599. @statsSample NULL = perform a sample scan on the target table or indexed view. The database engine automatically computes the required sample size;
  600. FULLSCAN = all rows in table or view should be read to gather the statistics;
  601. RESAMPLE = statistics will be gathered using an inherited sampling ratio for all existing statistics including indexes
  602. @ix_statsnorecompute 1 = STATISTICS_NORECOMPUTE on will disable the auto update statistics.
  603. If you are dealing with stats update with a custom job (or even with this code by updating statistics), you may use this option;
  604. 0 = default which is with STATISTICS_NORECOMPUTE off
  605. @statsIncremental When Incremental is ON, the statistics created are per partition statistics.
  606. When OFF, the statistics tree is dropped and SQL Server re-computes the statistics. This setting overrides the database level INCREMENTAL property. (http://msdn.microsoft.com/en-us/library/ms190397.aspx)
  607. NULL = Keep server setting;
  608. 1 = Enable auto create statistics with Incremental
  609. 0 = Disable auto create statistics with Incremental
  610. @dealMaxPartition If an index is partitioned, this option specifies whether to exclude the right-most populated partition, or act only on that same partition, excluding all others.
  611. Typically, this is the partition that is currently being written to in a sliding-window scenario.
  612. Enabling this feature may reduce contention. This may not be applicable in other types of partitioning scenarios.
  613. Non-partitioned indexes are unaffected by this option. Only in Enterprise Edition.
  614. 1 = exclude right-most populated partition
  615. 0 = only right-most populated partition (remember to verify @minPageCount, if partition is smaller than @minPageCount, it won't be considered)
  616. NULL = do not exclude any partitions
  617. @dealLOB Specifies that all pages that contain large object (LOB) data are compacted. The LOB data types are image, text, ntext, varchar(max), nvarchar(max), varbinary(max), and xml.
  618. Compacting this data can improve disk space use.
  619. Reorganizing a specified clustered index compacts all LOB columns that are contained in the clustered index.
  620. Reorganizing a non-clustered index compacts all LOB columns that are nonkey (included) columns in the index.
  621. 0 = compact LOBs when reorganizing (default behavior);
  622. 1 = does not compact LOBs when reorganizing
  623. @ignoreDropObj If a table or index is dropped after the defrag cycle has begun, you can choose to ignore those errors in the overall outcome,
  624. thus not showing a job as failed if the only errors present refer to dropped database objects.
  625. 0 = includes errors about objects that have been dropped since the defrag cycle began (default behavior);
  626. 1 = for error reporting purposes, ignores the fact that objects have been dropped since the defrag cycle began
  627. @disableNCIX If disk space is limited, it may be helpful to disable the non-clustered index before rebuilding it;
  628. When a non-clustered index is not disabled, the rebuild operation requires enough temporary disk space to store both the old and new index;
  629. However, by disabling and rebuilding a non-clustered index in separate transactions, the disk space made available by disabling the index can be reused by the subsequent rebuild or any other operation;
  630. No additional space is required except for temporary disk space for sorting; this is typically 20 percent of the index size;
  631. Does not disable indexes on partitioned tables when defragging a subset of existing partitions;
  632. Keeps track of whatever indexes were disabled by the defrag cycle. In case the defrag is cancelled, it will account for these disabled indexes in the next run.
  633. 0 = does NOT disable non-clustered indexes prior to a rebuild (default behavior);
  634. 1 = disables non-clustered indexes prior to a rebuild (space saving feature)
  635. @offlinelocktimeout As set in SET LOCK_TIMEOUT (http://msdn.microsoft.com/en-us/library/ms189470.aspx)
  636. -1 = (default) indicates no time-out period
  637. Any other positive integer = sets the number of milliseconds that will pass before Microsoft SQL Server returns a locking error
  638. @onlinelocktimeout Indicates a time-out period for locks to wait at low priority, expressed in minutes; this is valid from SQL Server 2014 onwards
  639. @abortAfterwait If the online low priority lock timeout occurs, this will set the action to perform afterwards.
  640. NULL = (default) After lock timeout occurs, continue waiting for the lock with normal (regular) priority;
  641. 1 = Exit the online index rebuild DDL operation currently being executed without taking any action;
  642. 2 = Kill all user transactions that block the online index rebuild DDL operation so that the operation can continue.
  643. @dealROWG Set Columnstore reorg option to compress all rowgroups, and not just closed ones
  644. 0 = (default) compress closed rowgroups on columnstore.
  645. 1 = compress all rowgroups on columnstore, and not just closed ones.
  646. @getBlobfrag Indicates whether to exclude or include blobs from fragmentation scan.
  647. 0 = (default) exclude blobs from fragmentation scan.
  648. 1 = include blobs and off-row data when scanning for fragmentation.
  649. -------------------------------------------------------
  650. Usage:
  651. EXEC dbo.usp_AdaptiveIndexDefrag
  652. or customize it like the example:
  653. EXEC dbo.usp_AdaptiveIndexDefrag
  654. @Exec_Print = 0
  655. , @printCmds = 1
  656. , @updateStats = 1
  657. , @updateStatsWhere = 1
  658. , @debugMode = 1
  659. , @outputResults = 1
  660. , @dbScope = 'AdventureWorks2008R2'
  661. , @forceRescan = 1
  662. , @maxDopRestriction = 2
  663. , @minPageCount = 8
  664. , @maxPageCount = NULL
  665. , @minFragmentation = 1
  666. , @rebuildThreshold = 1
  667. , @rebuildThreshold_cs = 1
  668. , @defragDelay = '00:00:05'
  669. , @defragOrderColumn = 'range_scan_count'
  670. , @dealMaxPartition = NULL
  671. , @disableNCIX = 1
  672. , @offlinelocktimeout = 180;
  673. */
  674. SET NOCOUNT ON;
  675. SET XACT_ABORT ON;
  676. SET QUOTED_IDENTIFIER ON;
  677. SET DATEFORMAT ymd;
  678. SET DEADLOCK_PRIORITY -10;
  679. -- Required so it can update stats on IxVws and FiltIxs
  680. SET ANSI_WARNINGS ON;
  681. SET ANSI_PADDING ON;
  682. SET ANSI_NULLS ON;
  683. SET ARITHABORT ON;
  684. SET CONCAT_NULL_YIELDS_NULL ON;
  685. SET NUMERIC_ROUNDABORT OFF;
  686. BEGIN
  687. BEGIN TRY
  688. /* Validating and normalizing options... */
  689. IF @debugMode = 1
  690. RAISERROR('Validating options...', 0, 42) WITH NOWAIT;
  691. IF @minFragmentation IS NULL OR @minFragmentation NOT BETWEEN 0.00 AND 100.0
  692. SET @minFragmentation = 5.0;
  693. IF @rebuildThreshold IS NULL OR @rebuildThreshold NOT BETWEEN 0.00 AND 100.0
  694. SET @rebuildThreshold = 30.0;
  695. IF @rebuildThreshold_cs IS NULL OR @rebuildThreshold_cs NOT BETWEEN 0.00 AND 100.0
  696. SET @rebuildThreshold_cs = 10.0;
  697. IF @timeLimit IS NULL
  698. SET @timeLimit = 480;
  699. /* Validate if table name is fully qualified and database scope is set */
  700. IF @tblName IS NOT NULL AND @tblName NOT LIKE '%.%'
  701. BEGIN
  702. RAISERROR('WARNING: Table name must be fully qualified. Input format should be <schema>.<table_name>.', 15, 42) WITH NOWAIT;
  703. RETURN
  704. END;
  705. /* Validate if database scope is set when table name is also set */
  706. IF @tblName IS NOT NULL AND @dbScope IS NULL
  707. BEGIN
  708. RAISERROR('WARNING: A database scope must be set when using table names.', 15, 42) WITH NOWAIT;
  709. RETURN
  710. END;
  711. /* Validate if database scope exists */
  712. IF @dbScope IS NOT NULL AND LOWER(@dbScope) NOT IN (SELECT LOWER([name]) FROM sys.databases WHERE LOWER([name]) NOT IN ('master', 'tempdb', 'model', 'reportservertempdb','semanticsdb') AND is_distributor = 0)
  713. BEGIN
  714. RAISERROR('WARNING: The database in scope does not exist or is a system database.', 15, 42) WITH NOWAIT;
  715. RETURN
  716. END;
  717. /* Validate offline lock timeout settings */
  718. IF @offlinelocktimeout IS NULL OR ISNUMERIC(@offlinelocktimeout) <> 1
  719. BEGIN
  720. RAISERROR('WARNING: Offline lock timeout must be set to an integer number.', 15, 42) WITH NOWAIT;
  721. RETURN
  722. END;
  723. IF @offlinelocktimeout <> -1 AND @offlinelocktimeout IS NOT NULL
  724. SET @offlinelocktimeout = ABS(@offlinelocktimeout)
  725. /* Validate online lock timeout settings */
  726. IF @onlinelocktimeout IS NULL OR ISNUMERIC(@onlinelocktimeout) <> 1
  727. BEGIN
  728. RAISERROR('WARNING: Online lock timeout must be set to an integer number.', 15, 42) WITH NOWAIT;
  729. RETURN
  730. END;
  731. IF @onlinelocktimeout <> 5 AND @onlinelocktimeout IS NOT NULL
  732. SET @onlinelocktimeout = ABS(@onlinelocktimeout)
  733. /* Validate online lock timeout wait action settings */
  734. IF @abortAfterwait IS NOT NULL AND @abortAfterwait NOT IN (0,1)
  735. BEGIN
  736. RAISERROR('WARNING: Online lock timeout action is invalid.', 15, 42) WITH NOWAIT;
  737. RETURN
  738. END;
  739. /* Validate amount of breather time to give between operations*/
  740. IF @defragDelay NOT LIKE '00:[0-5][0-9]:[0-5][0-9]'
  741. BEGIN
  742. SET @defragDelay = '00:00:05';
  743. RAISERROR('Defrag delay input not valid. Defaulting to 5s.', 0, 42) WITH NOWAIT;
  744. END;
  745. IF @defragOrderColumn IS NULL OR LOWER(@defragOrderColumn) NOT IN ('range_scan_count', 'fragmentation', 'page_count')
  746. BEGIN
  747. SET @defragOrderColumn = 'range_scan_count';
  748. RAISERROR('Defrag order input not valid. Defaulting to range_scan_count.', 0, 42) WITH NOWAIT;
  749. END;
  750. IF @defragSortOrder IS NULL OR UPPER(@defragSortOrder) NOT IN ('ASC', 'DESC')
  751. SET @defragSortOrder = 'DESC';
  752. IF UPPER(@scanMode) NOT IN ('LIMITED', 'SAMPLED', 'DETAILED')
  753. BEGIN
  754. SET @scanMode = 'LIMITED';
  755. RAISERROR('Index scan mode input not valid. Defaulting to LIMITED.', 0, 42) WITH NOWAIT;
  756. END;
  757. IF @ixtypeOption IS NOT NULL AND @ixtypeOption NOT IN (0,1)
  758. SET @ixtypeOption = NULL;
  759. IF @statsSample IS NOT NULL AND UPPER(@statsSample) NOT IN ('FULLSCAN', 'RESAMPLE')
  760. SET @statsSample = NULL;
  761. /* Find sql server version info */
  762. DECLARE @sqlmajorver int, @sqlminorver int, @sqlbuild int;
  763. SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  764. SELECT @sqlminorver = CONVERT(int, (@@microsoftversion / 0x10000) & 0xff);
  765. SELECT @sqlbuild = CONVERT(int, @@microsoftversion & 0xffff);
  766. /* Recognize if database in scope is a Always On secondary replica */
  767. IF @dbScope IS NOT NULL AND @sqlmajorver >= 11
  768. BEGIN
  769. DECLARE @sqlcmdAO NVARCHAR(3000), @paramsAO NVARCHAR(50), @DBinAG int
  770. SET @sqlcmdAO = 'IF LOWER(@dbScopeIN) IN (SELECT LOWER(DB_NAME(dr.database_id))
  771. FROM sys.dm_hadr_database_replica_states dr
  772. INNER JOIN sys.dm_hadr_availability_replica_states rs ON dr.group_id = rs.group_id
  773. INNER JOIN sys.databases d ON dr.database_id = d.database_id
  774. WHERE rs.role = 2 -- Is Secondary
  775. AND dr.is_local = 1
  776. AND rs.is_local = 1)
  777. BEGIN
  778. SET @DBinAG_OUT = 1
  779. END
  780. ELSE
  781. BEGIN
  782. SET @DBinAG_OUT = 0
  783. END'
  784. SET @paramsAO = N'@dbScopeIN NVARCHAR(256), @DBinAG_OUT int OUTPUT'
  785. EXECUTE sp_executesql @sqlcmdAO, @paramsAO, @dbScopeIN = @dbScope, @DBinAG_OUT = @DBinAG OUTPUT
  786. IF @DBinAG = 1
  787. BEGIN
  788. RAISERROR('WARNING: Cannot defrag database in scope because it is part of an Always On secondary replica.', 15, 42) WITH NOWAIT;
  789. RETURN
  790. END
  791. END
  792. /* Check if database scope has changed, if rescan is not being forced */
  793. IF @forceRescan = 0 AND @dbScope IS NOT NULL -- Specific scope was set
  794. BEGIN
  795. IF (SELECT COUNT(DISTINCT [dbID]) FROM dbo.tbl_AdaptiveIndexDefrag_Working) = 1
  796. AND QUOTENAME(LOWER(@dbScope)) NOT IN (SELECT DISTINCT LOWER([dbName]) FROM dbo.tbl_AdaptiveIndexDefrag_Working UNION SELECT DISTINCT LOWER(dbName) FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working)
  797. BEGIN
  798. SET @forceRescan = 1
  799. RAISERROR('Scope has changed. Forcing rescan of single database in scope...', 0, 42) WITH NOWAIT;
  800. END;
  801. END;
  802. /* Recognize if we have indexes of the chosen type left to defrag or stats left to update;
  803. otherwise force rescan of database(s), if rescan is not being forced */
  804. IF @forceRescan = 0
  805. AND (NOT EXISTS (SELECT TOP 1 * FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE defragDate IS NULL AND [type] = 1 AND [exclusionMask] & POWER(2, DATEPART(weekday, GETDATE())-1) = 0) AND @ixtypeOption = 1)
  806. AND (NOT EXISTS (SELECT TOP 1 * FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE defragDate IS NULL AND [type] <> 1 AND [exclusionMask] & POWER(2, DATEPART(weekday, GETDATE())-1) = 0) AND @ixtypeOption = 0)
  807. AND (NOT EXISTS (SELECT TOP 1 * FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE defragDate IS NULL AND [exclusionMask] & POWER(2, DATEPART(weekday, GETDATE())-1) = 0 ) AND @ixtypeOption IS NULL)
  808. AND NOT EXISTS (SELECT TOP 1 * FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working AS idss WHERE idss.updateDate IS NULL AND NOT EXISTS (SELECT TOP 1 objectID FROM dbo.tbl_AdaptiveIndexDefrag_Working ids WHERE ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0))
  809. BEGIN
  810. SET @forceRescan = 1
  811. RAISERROR('No indexes of the chosen type left to defrag nor statistics left to update. Forcing rescan...', 0, 42) WITH NOWAIT;
  812. END;
  813. /* Check if any databases where dropped or created since last run, if rescan is not being forced */
  814. IF @forceRescan = 0 AND @dbScope IS NULL
  815. BEGIN
  816. DECLARE @sqlcmd_CntSrc NVARCHAR(3000), @params_CntSrc NVARCHAR(50), @CountSrc int
  817. DECLARE @sqlcmd_CntTgt NVARCHAR(3000), @params_CntTgt NVARCHAR(50), @CountTgt int
  818. DECLARE @dbIDIX int, @hasIXs bit, @hasIXsCntsqlcmd NVARCHAR(3000), @hasIXsCntsqlcmdParams NVARCHAR(50)
  819. -- What is in working tables plus exceptions that still exist in server
  820. SET @sqlcmd_CntSrc = 'SELECT @CountSrc_OUT = COUNT(DISTINCT Working.[dbID]) FROM
  821. (SELECT DISTINCT [dbID] FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Working
  822. UNION
  823. SELECT DISTINCT [dbID] FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  824. UNION
  825. SELECT DISTINCT [dbID] FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Exceptions
  826. WHERE [dbID] IN (SELECT DISTINCT database_id FROM master.sys.databases sd
  827. WHERE LOWER(sd.[name]) NOT IN (''master'', ''tempdb'', ''model'', ''reportservertempdb'',''semanticsdb'')
  828. AND [state] = 0 -- must be ONLINE
  829. AND is_read_only = 0 -- cannot be READ_ONLY
  830. AND is_distributor = 0)
  831. ) Working'
  832. SET @params_CntSrc = N'@CountSrc_OUT int OUTPUT'
  833. -- What exists in current instance, in ONLINE state and READ_WRITE
  834. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexFindInDatabaseList'))
  835. DROP TABLE #tblIndexFindInDatabaseList;
  836. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexFindInDatabaseList'))
  837. CREATE TABLE #tblIndexFindInDatabaseList
  838. (
  839. [dbID] int
  840. , hasIXs bit NOT NULL
  841. , scanStatus bit NULL
  842. );
  843. /* Retrieve the list of databases to loop, excluding Always On secondary replicas */
  844. SET @sqlcmd_CntTgt = 'SELECT [database_id], 0, 0 -- not yet scanned
  845. FROM master.sys.databases
  846. WHERE LOWER([name]) = ISNULL(LOWER(@dbScopeIN), LOWER([name]))
  847. AND LOWER([name]) NOT IN (''master'', ''tempdb'', ''model'', ''reportservertempdb'',''semanticsdb'') -- exclude system databases
  848. AND [state] = 0 -- must be ONLINE
  849. AND is_read_only = 0 -- cannot be READ_ONLY
  850. AND is_distributor = 0'
  851. IF @sqlmajorver >= 11 -- Except all local Always On secondary replicas
  852. BEGIN
  853. SET @sqlcmd_CntTgt = @sqlcmd_CntTgt + CHAR(10) + 'AND [database_id] NOT IN (SELECT dr.database_id FROM sys.dm_hadr_database_replica_states dr
  854. INNER JOIN sys.dm_hadr_availability_replica_states rs ON dr.group_id = rs.group_id
  855. INNER JOIN sys.databases d ON dr.database_id = d.database_id
  856. WHERE rs.role = 2 -- Is Secondary
  857. AND dr.is_local = 1
  858. AND rs.is_local = 1)'
  859. END
  860. SET @params_CntTgt = N'@dbScopeIN NVARCHAR(256)'
  861. INSERT INTO #tblIndexFindInDatabaseList
  862. EXECUTE sp_executesql @sqlcmd_CntTgt, @params_CntTgt, @dbScopeIN = @dbScope
  863. WHILE (SELECT COUNT(*) FROM #tblIndexFindInDatabaseList WHERE scanStatus = 0) > 0
  864. BEGIN
  865. SELECT TOP 1 @dbIDIX = [dbID] FROM #tblIndexFindInDatabaseList WHERE scanStatus = 0;
  866. SET @hasIXsCntsqlcmd = 'IF EXISTS (SELECT TOP 1 [index_id] from [' + DB_NAME(@dbIDIX) + '].sys.indexes AS si
  867. INNER JOIN [' + DB_NAME(@dbIDIX) + '].sys.objects so ON si.object_id = so.object_id
  868. WHERE so.is_ms_shipped = 0 AND [index_id] > 0 AND si.is_hypothetical = 0
  869. AND si.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + DB_NAME(@dbIDIX) + '].sys.internal_tables AS sit))
  870. OR
  871. EXISTS (SELECT TOP 1 [stats_id] from [' + DB_NAME(@dbIDIX) + '].sys.stats AS ss
  872. INNER JOIN [' + DB_NAME(@dbIDIX) + '].sys.objects so ON ss.[object_id] = so.[object_id]
  873. WHERE so.is_ms_shipped = 0
  874. AND ss.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + DB_NAME(@dbIDIX) + '].sys.internal_tables AS sit))
  875. BEGIN SET @hasIXsOUT = 1 END ELSE BEGIN SET @hasIXsOUT = 0 END'
  876. SET @hasIXsCntsqlcmdParams = '@hasIXsOUT int OUTPUT'
  877. EXECUTE sp_executesql @hasIXsCntsqlcmd, @hasIXsCntsqlcmdParams, @hasIXsOUT = @hasIXs OUTPUT
  878. UPDATE #tblIndexFindInDatabaseList
  879. SET hasIXs = @hasIXs, scanStatus = 1
  880. WHERE [dbID] = @dbIDIX
  881. END
  882. EXECUTE sp_executesql @sqlcmd_CntSrc, @params_CntSrc, @CountSrc_OUT = @CountSrc OUTPUT
  883. SELECT @CountTgt = COUNT([dbID]) FROM #tblIndexFindInDatabaseList WHERE hasIXs = 1
  884. IF @CountSrc <> @CountTgt -- current databases in working lists <> number of eligible databases in instance
  885. BEGIN
  886. SET @forceRescan = 1
  887. RAISERROR('Scope has changed. Forcing rescan...', 0, 42) WITH NOWAIT;
  888. END
  889. END
  890. IF @debugMode = 1
  891. RAISERROR('Starting up...', 0, 42) WITH NOWAIT;
  892. /* Declare variables */
  893. DECLARE @ver VARCHAR(10)
  894. , @objectID int
  895. , @dbID int
  896. , @dbName NVARCHAR(256)
  897. , @indexID int
  898. , @operationFlag bit -- 0 = Reorganize, 1 = Rebuild
  899. , @partitionCount bigint
  900. , @schemaName NVARCHAR(128)
  901. , @objectName NVARCHAR(256)
  902. , @indexName NVARCHAR(256)
  903. , @statsName NVARCHAR(256)
  904. , @statsschemaName NVARCHAR(128)
  905. , @statsobjectName NVARCHAR(256)
  906. , @stats_norecompute bit
  907. , @stats_isincremental bit
  908. , @is_primary_key bit
  909. , @fill_factor int
  910. , @is_disabled bit
  911. , @is_padded bit
  912. , @has_filter bit
  913. , @partitionNumber smallint
  914. , @maxpartitionNumber smallint
  915. , @minpartitionNumber smallint
  916. , @fragmentation float
  917. , @pageCount int
  918. , @sqlcommand NVARCHAR(4000)
  919. , @sqlcommand2 NVARCHAR(600)
  920. , @sqldisablecommand NVARCHAR(600)
  921. , @sqlprecommand NVARCHAR(600)
  922. , @rebuildcommand NVARCHAR(600)
  923. , @dateTimeStart DATETIME
  924. , @dateTimeEnd DATETIME
  925. , @containsColumnstore int
  926. , @CStore_SQL NVARCHAR(4000)
  927. , @CStore_SQL_Param NVARCHAR(1000)
  928. , @editionCheck bit
  929. , @debugMessage VARCHAR(2048)
  930. , @updateSQL NVARCHAR(4000)
  931. , @partitionSQL NVARCHAR(4000)
  932. , @partitionSQL_Param NVARCHAR(1000)
  933. , @rowmodctrSQL NVARCHAR(4000)
  934. , @rowmodctrSQL_Param NVARCHAR(1000)
  935. , @rowmodctr bigint
  936. , @record_count bigint
  937. , @range_scan_count bigint
  938. , @getStatSQL NVARCHAR(4000)
  939. , @getStatSQL_Param NVARCHAR(1000)
  940. , @statsID int
  941. , @ixtype tinyint -- 0 = Heap; 1 = Clustered; 2 = Nonclustered; 3 = XML; 4 = Spatial
  942. , @containsLOB int
  943. , @LOB_SQL NVARCHAR(4000)
  944. , @LOB_SQL_Param NVARCHAR(1000)
  945. , @indexDefrag_id int
  946. , @statsUpdate_id int
  947. , @statsObjectID int
  948. , @startDateTime DATETIME
  949. , @endDateTime DATETIME
  950. , @getIndexSQL NVARCHAR(4000)
  951. , @getIndexSQL_Param NVARCHAR(4000)
  952. , @allowPageLockSQL NVARCHAR(4000)
  953. , @allowPageLockSQL_Param NVARCHAR(4000)
  954. , @allowPageLocks bit
  955. , @dealMaxPartitionSQL NVARCHAR(4000)
  956. , @cpucount smallint
  957. , @tblNameFQN NVARCHAR(1000)
  958. , @TableScanSQL NVARCHAR(2000)
  959. , @ixCntSource int
  960. , @ixCntTarget int
  961. , @ixCntsqlcmd NVARCHAR(1000)
  962. , @ixCntsqlcmdParams NVARCHAR(100)
  963. , @ColumnStoreGetIXSQL NVARCHAR(2000)
  964. , @ColumnStoreGetIXSQL_Param NVARCHAR(1000)
  965. , @rows bigint
  966. , @rows_sampled bigint
  967. /* Initialize variables */
  968. SELECT @startDateTime = GETDATE(), @endDateTime = DATEADD(minute, @timeLimit, GETDATE()), @operationFlag = NULL, @ver = '1.6.3.2';
  969. /* Create temporary tables */
  970. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragDatabaseList'))
  971. DROP TABLE #tblIndexDefragDatabaseList;
  972. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragDatabaseList'))
  973. CREATE TABLE #tblIndexDefragDatabaseList
  974. (
  975. dbID int
  976. , dbName NVARCHAR(256)
  977. , scanStatus bit NULL
  978. );
  979. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragmaxPartitionList'))
  980. DROP TABLE #tblIndexDefragmaxPartitionList;
  981. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragmaxPartitionList'))
  982. CREATE TABLE #tblIndexDefragmaxPartitionList
  983. (
  984. objectID int
  985. , indexID int
  986. , maxPartition int
  987. );
  988. /* Create table for fragmentation scan per table, index and partition - slower but less chance of blocking*/
  989. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragScanWorking'))
  990. DROP TABLE #tblIndexDefragScanWorking;
  991. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragScanWorking'))
  992. CREATE TABLE #tblIndexDefragScanWorking
  993. (
  994. objectID int
  995. , indexID int
  996. , type tinyint
  997. , partitionNumber int
  998. , is_done bit
  999. );
  1000. /* Find available processors*/
  1001. SELECT @cpucount = COUNT(*)
  1002. FROM sys.dm_os_schedulers
  1003. WHERE is_online = 1 AND scheduler_id < 255 AND status = 'VISIBLE ONLINE'
  1004. IF @maxDopRestriction IS NOT NULL AND @maxDopRestriction > @cpucount AND @cpucount <= 8
  1005. BEGIN
  1006. SET @maxDopRestriction = @cpucount
  1007. END
  1008. ELSE IF @maxDopRestriction IS NOT NULL AND ((@maxDopRestriction > @cpucount AND @cpucount > 8) OR @maxDopRestriction > 8)
  1009. BEGIN
  1010. SET @maxDopRestriction = 8;
  1011. END
  1012. /* Refer to http://msdn.microsoft.com/en-us/library/ms174396.aspx */
  1013. IF (SELECT SERVERPROPERTY('EditionID')) IN (1804890536, 1872460670, 610778273, -2117995310)
  1014. SET @editionCheck = 1 -- supports enterprise only features: online rebuilds, partitioned indexes and MaxDOP
  1015. ELSE
  1016. SET @editionCheck = 0; -- does not support enterprise only features: online rebuilds, partitioned indexes and MaxDOP
  1017. /* Output the parameters to work with */
  1018. IF @debugMode = 1
  1019. BEGIN
  1020. SELECT @debugMessage = CHAR(10) + 'Executing AdaptiveIndexDefrag v' + @ver + ' on ' + @@VERSION + '.
  1021. The selected parameters are:
  1022. Defragment indexes with fragmentation greater or equal to ' + CAST(@minFragmentation AS NVARCHAR(10)) + ';
  1023. Rebuild indexes with fragmentation greater than ' + CAST(@rebuildThreshold AS NVARCHAR(10)) + ';
  1024. Rebuild columnstore indexes with fragmentation greater than ' + CAST(@rebuildThreshold_cs AS NVARCHAR(10)) + ';
  1025. ' + CASE WHEN @disableNCIX = 1 THEN 'Non-clustered indexes will be disabled prior to rebuild;
  1026. ' ELSE '' END + 'Defragment ' + CASE WHEN @ixtypeOption IS NULL THEN 'ALL indexes' WHEN @ixtypeOption = 1 THEN 'only CLUSTERED indexes' ELSE 'only NON-CLUSTERED, XML and Spatial indexes' END + ';
  1027. Commands' + CASE WHEN @Exec_Print = 1 THEN ' WILL' ELSE ' WILL NOT' END + ' be executed automatically;
  1028. Defragment indexes in ' + @defragSortOrder + ' order of the ' + UPPER(@defragOrderColumn) + ' value;
  1029. Time limit' + CASE WHEN @timeLimit IS NULL THEN ' was not specified;' ELSE ' was specified and is ' + CAST(@timeLimit AS NVARCHAR(10)) END + ' minutes;
  1030. ' + CASE WHEN @dbScope IS NULL THEN 'ALL databases' ELSE 'The ' + @dbScope + ' database' END + ' will be defragmented;
  1031. ' + CASE WHEN @tblName IS NULL THEN 'ALL tables' ELSE 'The ' + @tblName + ' table' END + ' will be defragmented;
  1032. ' + 'We' + CASE WHEN EXISTS(SELECT TOP 1 * FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE defragDate IS NULL) AND @forceRescan = 0 THEN ' will resume any existing previous run. If so, we WILL NOT' ELSE ' WILL' END + ' be rescanning indexes;
  1033. The scan will be performed in ' + @scanMode + ' mode;
  1034. LOBs will ' + CASE WHEN @dealLOB = 1 THEN 'NOT ' ELSE '' END + 'be compacted;
  1035. Limit defrags to indexes' + CASE WHEN @maxPageCount IS NULL THEN ' with more than ' + CAST(@minPageCount AS NVARCHAR(10)) ELSE
  1036. ' between ' + CAST(@minPageCount AS NVARCHAR(10)) + ' and ' + CAST(@maxPageCount AS NVARCHAR(10)) END + ' pages;
  1037. Indexes will be defragmented' + CASE WHEN @onlineRebuild = 0 OR @editionCheck = 0 THEN ' OFFLINE;' ELSE ' ONLINE;' END + '
  1038. Indexes will be sorted in' + CASE WHEN @sortInTempDB = 0 THEN ' the DATABASE;' ELSE ' TEMPDB;' END + '
  1039. Indexes will have' + CASE WHEN @fillfactor = 1 THEN ' its ORIGINAL' ELSE ' the DEFAULT' END + ' Fill Factor;' +
  1040. CASE WHEN @dealMaxPartition = 1 AND @editionCheck = 1 THEN '
  1041. The right-most populated partitions will be ignored;'
  1042. WHEN @dealMaxPartition = 0 AND @editionCheck = 1 THEN '
  1043. Only the right-most populated partitions will be considered if greater than ' + CAST(@minPageCount AS NVARCHAR(10)) + ' page(s);'
  1044. ELSE CHAR(10) + 'All partitions will be considered;' END +
  1045. CHAR(10) + 'Statistics ' + CASE WHEN @updateStats = 1 THEN 'WILL' ELSE 'WILL NOT' END + ' be updated ' + CASE WHEN @updateStatsWhere = 1 THEN 'on reorganized indexes;' ELSE 'on all stats belonging to parent table;' END +
  1046. CASE WHEN @updateStats = 1 AND @statsSample IS NOT NULL THEN CHAR(10) + 'Statistics will be updated with ' + @statsSample + '.' ELSE '' END +
  1047. CHAR(10) + 'Statistics will be updated with Incremental property (if any) ' + CASE WHEN @statsIncremental = 1 THEN 'as ON' WHEN @statsIncremental = 0 THEN 'as OFF' ELSE 'not changed from current setting' END + '.' +
  1048. CHAR(10) + 'Defragmentation will use ' + CASE WHEN @editionCheck = 0 OR @maxDopRestriction IS NULL THEN 'system defaults for processors;'
  1049. ELSE CAST(@maxDopRestriction AS VARCHAR(2)) + ' processors;' END +
  1050. CHAR(10) + 'Lock timeout is set to ' + CASE WHEN @offlinelocktimeout <> -1 AND @offlinelocktimeout IS NOT NULL THEN CONVERT(NVARCHAR(15), @offlinelocktimeout) ELSE 'system default' END + ' for offline rebuilds;' +
  1051. CHAR(10) + 'From SQL Server 2014, lock timeout is set to ' + CONVERT(NVARCHAR(15), @onlinelocktimeout) + ' for online rebuilds;' +
  1052. CHAR(10) + 'From SQL Server 2014, lock timeout action is set to ' + CASE WHEN @abortAfterwait = 0 THEN 'BLOCKERS' WHEN @abortAfterwait = 1 THEN 'SELF' ELSE 'NONE' END + ' for online rebuilds;' +
  1053. CHAR(10) + CASE WHEN @printCmds = 1 THEN ' DO print' ELSE ' DO NOT print' END + ' the sql commands;' +
  1054. CHAR(10) + CASE WHEN @outputResults = 1 THEN ' DO output' ELSE ' DO NOT output' END + ' fragmentation levels;
  1055. Wait ' + @defragDelay + ' (hh:mm:ss) between index operations;
  1056. Execute in' + CASE WHEN @debugMode = 1 THEN ' DEBUG' ELSE ' SILENT' END + ' mode.' + CHAR(10);
  1057. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1058. END;
  1059. /* If we are scanning the database(s), do some pre-work */
  1060. IF @forceRescan = 1 OR (NOT EXISTS (SELECT TOP 1 * FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE defragDate IS NULL AND [exclusionMask] & POWER(2, DATEPART(weekday, GETDATE())-1) = 0)
  1061. AND NOT EXISTS (SELECT TOP 1 * FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working AS idss WHERE idss.updateDate IS NULL AND NOT EXISTS (SELECT TOP 1 objectID FROM dbo.tbl_AdaptiveIndexDefrag_Working ids WHERE ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0)))
  1062. BEGIN
  1063. IF @debugMode = 1
  1064. RAISERROR('Listing databases...', 0, 42) WITH NOWAIT;
  1065. /* Retrieve the list of databases to loop, exclusing Always On secondary replicas */
  1066. DECLARE @sqlcmdAO2 NVARCHAR(4000), @paramsAO2 NVARCHAR(50)
  1067. IF @debugMode = 1 AND @sqlmajorver >= 11
  1068. RAISERROR('Retrieving list of databases to loop, excluding Always On secondary replicas...', 0, 42) WITH NOWAIT;
  1069. IF @debugMode = 1 AND @sqlmajorver < 11
  1070. RAISERROR('Retrieving list of databases to loop...', 0, 42) WITH NOWAIT;
  1071. SET @sqlcmdAO2 = 'SELECT [database_id], name, 0 -- not yet scanned for fragmentation
  1072. FROM master.sys.databases
  1073. WHERE LOWER([name]) = ISNULL(LOWER(@dbScopeIN), LOWER([name]))
  1074. AND LOWER([name]) NOT IN (''master'', ''tempdb'', ''model'', ''reportservertempdb'',''semanticsdb'') -- exclude system databases
  1075. AND [state] = 0 -- must be ONLINE
  1076. AND is_read_only = 0 -- cannot be READ_ONLY
  1077. AND is_distributor = 0'
  1078. IF @sqlmajorver >= 11 -- Except all local Always On secondary replicas
  1079. BEGIN
  1080. SET @sqlcmdAO2 = @sqlcmdAO2 + CHAR(10) + 'AND [database_id] NOT IN (SELECT dr.database_id FROM sys.dm_hadr_database_replica_states dr
  1081. INNER JOIN sys.dm_hadr_availability_replica_states rs ON dr.group_id = rs.group_id
  1082. INNER JOIN sys.databases d ON dr.database_id = d.database_id
  1083. WHERE rs.role = 2 -- Is Secondary
  1084. AND dr.is_local = 1
  1085. AND rs.is_local = 1)'
  1086. END
  1087. SET @paramsAO2 = N'@dbScopeIN NVARCHAR(256)'
  1088. INSERT INTO #tblIndexDefragDatabaseList
  1089. EXECUTE sp_executesql @sqlcmdAO2, @paramsAO2, @dbScopeIN = @dbScope
  1090. IF @debugMode = 1
  1091. RAISERROR('Cross checking with exceptions for today...', 0, 42) WITH NOWAIT;
  1092. /* Avoid scanning databases that have all its indexes in the exceptions table i.e, fully excluded */
  1093. WHILE (SELECT COUNT(*) FROM #tblIndexDefragDatabaseList WHERE scanStatus = 0) > 0
  1094. BEGIN
  1095. SELECT TOP 1 @dbID = dbID FROM #tblIndexDefragDatabaseList WHERE scanStatus = 0;
  1096. SELECT @ixCntSource = COUNT([indexName]) FROM dbo.tbl_AdaptiveIndexDefrag_Exceptions WHERE [dbID] = @dbID AND exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0
  1097. SET @ixCntsqlcmd = 'SELECT @ixCntTargetOUT = COUNT(si.index_id) FROM [' + DB_NAME(@dbID) + '].sys.indexes si
  1098. INNER JOIN [' + DB_NAME(@dbID) + '].sys.objects so ON si.object_id = so.object_id
  1099. WHERE so.is_ms_shipped = 0 AND si.index_id > 0 AND si.is_hypothetical = 0
  1100. AND si.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + DB_NAME(@dbID) + '].sys.internal_tables AS sit)' -- Exclude Heaps, Internal and Hypothetical objects
  1101. SET @ixCntsqlcmdParams = '@ixCntTargetOUT int OUTPUT'
  1102. EXECUTE sp_executesql @ixCntsqlcmd, @ixCntsqlcmdParams, @ixCntTargetOUT = @ixCntTarget OUTPUT
  1103. IF @ixCntSource = @ixCntTarget AND @ixCntSource > 0 -- All database objects are excluded, so skip database scanning
  1104. BEGIN
  1105. UPDATE #tblIndexDefragDatabaseList
  1106. SET scanStatus = NULL
  1107. WHERE dbID = @dbID;
  1108. IF @debugMode = 1
  1109. SELECT @debugMessage = ' Database ' + DB_NAME(@dbID) + ' is fully excluded from todays work.';
  1110. IF @debugMode = 1
  1111. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1112. END
  1113. IF @ixCntSource < @ixCntTarget AND @ixCntSource > 0 -- Only some database objects are excluded, so scan anyway and deal with exclusions on a granular level
  1114. BEGIN
  1115. UPDATE #tblIndexDefragDatabaseList
  1116. SET scanStatus = 1
  1117. WHERE dbID = @dbID;
  1118. IF @debugMode = 1
  1119. SELECT @debugMessage = ' Database ' + DB_NAME(@dbID) + ' is partially excluded from todays work.';
  1120. IF @debugMode = 1
  1121. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1122. END
  1123. IF @ixCntSource = 0 -- Database does not have excluded objects
  1124. BEGIN
  1125. UPDATE #tblIndexDefragDatabaseList
  1126. SET scanStatus = 1
  1127. WHERE dbID = @dbID;
  1128. END;
  1129. END;
  1130. /* Delete databases that are fully excluded for today */
  1131. DELETE FROM #tblIndexDefragDatabaseList
  1132. WHERE scanStatus IS NULL;
  1133. /* Reset status after cross check with exceptions */
  1134. UPDATE #tblIndexDefragDatabaseList
  1135. SET scanStatus = 0;
  1136. END
  1137. /* Check to see if we have indexes of the chosen type in need of defrag, or stats to update; otherwise, allow re-scanning the database(s) */
  1138. IF @forceRescan = 1 OR (NOT EXISTS (SELECT TOP 1 * FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE defragDate IS NULL AND [exclusionMask] & POWER(2, DATEPART(weekday, GETDATE())-1) = 0)
  1139. AND NOT EXISTS (SELECT TOP 1 * FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working AS idss WHERE idss.updateDate IS NULL AND NOT EXISTS (SELECT TOP 1 objectID FROM dbo.tbl_AdaptiveIndexDefrag_Working ids WHERE ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0)))
  1140. BEGIN
  1141. IF @debugMode = 1
  1142. RAISERROR('Preparing for new database scan...', 0, 42) WITH NOWAIT;
  1143. /* Truncate list of indexes and stats to prepare for a new scan */
  1144. TRUNCATE TABLE dbo.tbl_AdaptiveIndexDefrag_Working;
  1145. TRUNCATE TABLE dbo.tbl_AdaptiveIndexDefrag_Stats_Working;
  1146. END
  1147. ELSE
  1148. BEGIN
  1149. /* Print an error message if there are any indexes left to defragment according to the chosen criteria */
  1150. IF @debugMode = 1
  1151. RAISERROR('There are still fragmented indexes or out-of-date stats from last execution. Resuming...', 0, 42) WITH NOWAIT;
  1152. END
  1153. /* Scan the database(s) */
  1154. IF (SELECT COUNT(*) FROM dbo.tbl_AdaptiveIndexDefrag_Working) = 0
  1155. BEGIN
  1156. IF @debugMode = 1
  1157. RAISERROR('Scanning database(s)...', 0, 42) WITH NOWAIT;
  1158. IF @debugMode = 1
  1159. RAISERROR(' Looping through list of databases and checking for fragmentation...', 0, 42) WITH NOWAIT;
  1160. /* Loop through list of databases */
  1161. WHILE (SELECT COUNT(*) FROM #tblIndexDefragDatabaseList WHERE scanStatus = 0) > 0
  1162. BEGIN
  1163. SELECT TOP 1 @dbID = dbID FROM #tblIndexDefragDatabaseList WHERE scanStatus = 0;
  1164. IF @debugMode = 1
  1165. SELECT @debugMessage = ' Working on ' + DB_NAME(@dbID) + '...';
  1166. IF @debugMode = 1
  1167. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1168. IF @dbScope IS NOT NULL AND @tblName IS NOT NULL
  1169. SELECT @tblNameFQN = @dbScope + '.' + @tblName
  1170. /* Set partitioning rebuild options; requires Enterprise Edition */
  1171. IF @dealMaxPartition IS NOT NULL AND @editionCheck = 0
  1172. SET @dealMaxPartition = NULL;
  1173. /* Truncate list of tables, indexes and partitions to prepare for a new scan */
  1174. TRUNCATE TABLE #tblIndexDefragScanWorking;
  1175. IF @debugMode = 1
  1176. RAISERROR(' Building list of objects in database...', 0, 42) WITH NOWAIT;
  1177. SELECT @TableScanSQL = 'SELECT si.[object_id], si.index_id, si.type, sp.partition_number, 0
  1178. FROM [' + DB_NAME(@dbID) + '].sys.indexes si
  1179. INNER JOIN [' + DB_NAME(@dbID) + '].sys.partitions sp ON si.[object_id] = sp.[object_id] AND si.index_id = sp.index_id
  1180. INNER JOIN [' + DB_NAME(@dbID) + '].sys.tables AS mst ON mst.[object_id] = si.[object_id]
  1181. INNER JOIN [' + DB_NAME(@dbID) + '].sys.schemas AS t ON t.[schema_id] = mst.[schema_id]' +
  1182. CASE WHEN @dbScope IS NULL AND @tblName IS NULL THEN CHAR(10) + 'LEFT JOIN [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Exceptions AS ide ON ide.[dbID] = ' + CONVERT(NVARCHAR(10),@dbID) + ' AND ide.objectID = si.[object_id] AND ide.indexID = si.index_id' ELSE '' END +
  1183. CHAR(10) + 'WHERE mst.is_ms_shipped = 0 ' + CASE WHEN @dbScope IS NULL AND @tblName IS NULL THEN 'AND (ide.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0 OR ide.exclusionMask IS NULL)' ELSE '' END + '
  1184. AND si.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + DB_NAME(@dbID) + '].sys.internal_tables AS sit)' +
  1185. CASE WHEN @dbScope IS NOT NULL AND @tblName IS NOT NULL THEN '
  1186. AND t.name + ''.'' + mst.name = ''' + @tblName + ''';' ELSE ';' END
  1187. INSERT INTO #tblIndexDefragScanWorking
  1188. EXEC sp_executesql @TableScanSQL;
  1189. /* Do we want to act on a subset of existing partitions? */
  1190. IF @dealMaxPartition = 1 OR @dealMaxPartition = 0
  1191. BEGIN
  1192. IF @debugMode = 1
  1193. RAISERROR(' Setting partition handling...', 0, 42) WITH NOWAIT;
  1194. SET @dealMaxPartitionSQL = 'SELECT [object_id], index_id, MAX(partition_number) AS [maxPartition] FROM [' + DB_NAME(@dbID) + '].sys.partitions WHERE partition_number > 1 AND [rows] > 0 GROUP BY object_id, index_id;';
  1195. INSERT INTO #tblIndexDefragmaxPartitionList
  1196. EXEC sp_executesql @dealMaxPartitionSQL;
  1197. END;
  1198. /* We don't want to defrag the right-most populated partition, so delete any records for partitioned indexes where partition = MAX(partition) */
  1199. IF @dealMaxPartition = 1 AND @editionCheck = 1
  1200. BEGIN
  1201. IF @debugMode = 1
  1202. RAISERROR(' Ignoring right-most populated partition...', 0, 42) WITH NOWAIT;
  1203. DELETE ids
  1204. FROM #tblIndexDefragScanWorking AS ids
  1205. INNER JOIN #tblIndexDefragmaxPartitionList AS mpl ON ids.objectID = mpl.objectID AND ids.indexID = mpl.indexID AND ids.partitionNumber = mpl.maxPartition;
  1206. END;
  1207. /* We only want to defrag the right-most populated partition, so delete any records for partitioned indexes where partition <> MAX(partition) */
  1208. IF @dealMaxPartition = 0 AND @editionCheck = 1
  1209. BEGIN
  1210. IF @debugMode = 1
  1211. RAISERROR(' Setting only right-most populated partition...', 0, 42) WITH NOWAIT;
  1212. DELETE ids
  1213. FROM #tblIndexDefragScanWorking AS ids
  1214. INNER JOIN #tblIndexDefragmaxPartitionList AS mpl ON ids.objectID = mpl.objectID AND ids.indexID = mpl.indexID AND ids.partitionNumber <> mpl.maxPartition;
  1215. END;
  1216. /* Determine which indexes to defragment using user-defined parameters */
  1217. IF @debugMode = 1
  1218. RAISERROR(' Filtering indexes according to ixtypeOption parameter...', 0, 42) WITH NOWAIT;
  1219. IF @ixtypeOption IS NULL
  1220. BEGIN
  1221. DELETE FROM #tblIndexDefragScanWorking
  1222. WHERE [type] = 0; -- ignore heaps
  1223. END
  1224. ELSE IF @ixtypeOption = 1
  1225. BEGIN
  1226. DELETE FROM #tblIndexDefragScanWorking
  1227. WHERE [type] NOT IN (1,5); -- keep only clustered index
  1228. END
  1229. ELSE IF @ixtypeOption = 0
  1230. BEGIN
  1231. DELETE FROM #tblIndexDefragScanWorking
  1232. WHERE [type] NOT IN (2,6); -- keep only non-clustered indexes
  1233. END;
  1234. -- Get rowstore indexes to work on
  1235. IF @debugMode = 1
  1236. RAISERROR(' Getting rowstore indexes...', 0, 42) WITH NOWAIT;
  1237. WHILE (SELECT COUNT(*) FROM #tblIndexDefragScanWorking WHERE is_done = 0 AND [type] IN (1,2)) > 0
  1238. BEGIN
  1239. SELECT TOP 1 @objectID = objectID, @indexID = indexID, @partitionNumber = partitionNumber
  1240. FROM #tblIndexDefragScanWorking WHERE is_done = 0 AND type IN (1,2)
  1241. BEGIN TRY
  1242. IF @getBlobfrag = 1
  1243. BEGIN
  1244. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Working (dbID, dbName, objectID, indexID, partitionNumber, fragmentation, page_count, range_scan_count, record_count, scanDate)
  1245. SELECT @dbID AS [dbID], QUOTENAME(DB_NAME(ps.database_id)) AS [dbName], @objectID AS [objectID], @indexID AS [indexID], ps.partition_number AS [partitionNumber], SUM(ps.avg_fragmentation_in_percent) AS [fragmentation], SUM(ps.page_count) AS [page_count], os.range_scan_count, ps.record_count, GETDATE() AS [scanDate]
  1246. FROM sys.dm_db_index_physical_stats(@dbID, @objectID, @indexID, @partitionNumber, @scanMode) AS ps
  1247. LEFT JOIN sys.dm_db_index_operational_stats(@dbID, @objectID, @indexID, @partitionNumber) AS os ON ps.database_id = os.database_id AND ps.object_id = os.object_id AND ps.index_id = os.index_id AND ps.partition_number = os.partition_number
  1248. WHERE avg_fragmentation_in_percent >= @minFragmentation
  1249. AND ps.page_count >= @minPageCount
  1250. AND ps.index_level = 0 -- leaf-level nodes only, supports @scanMode
  1251. AND ps.alloc_unit_type_desc = 'IN_ROW_DATA' -- exclude blobs
  1252. GROUP BY ps.database_id, QUOTENAME(DB_NAME(ps.database_id)), ps.partition_number, os.range_scan_count, ps.record_count
  1253. OPTION (MAXDOP 2);
  1254. END
  1255. ELSE IF @getBlobfrag = 0
  1256. BEGIN
  1257. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Working (dbID, dbName, objectID, indexID, partitionNumber, fragmentation, page_count, range_scan_count, record_count, scanDate)
  1258. SELECT @dbID AS [dbID], QUOTENAME(DB_NAME(ps.database_id)) AS [dbName], @objectID AS [objectID], @indexID AS [indexID], ps.partition_number AS [partitionNumber], SUM(ps.avg_fragmentation_in_percent) AS [fragmentation], SUM(ps.page_count) AS [page_count], os.range_scan_count, ps.record_count, GETDATE() AS [scanDate]
  1259. FROM sys.dm_db_index_physical_stats(@dbID, @objectID, @indexID, @partitionNumber, @scanMode) AS ps
  1260. LEFT JOIN sys.dm_db_index_operational_stats(@dbID, @objectID, @indexID, @partitionNumber) AS os ON ps.database_id = os.database_id AND ps.object_id = os.object_id AND ps.index_id = os.index_id AND ps.partition_number = os.partition_number
  1261. WHERE avg_fragmentation_in_percent >= @minFragmentation
  1262. AND ps.page_count >= @minPageCount
  1263. AND ps.index_level = 0 -- leaf-level nodes only, supports @scanMode
  1264. GROUP BY ps.database_id, QUOTENAME(DB_NAME(ps.database_id)), ps.partition_number, os.range_scan_count, ps.record_count
  1265. OPTION (MAXDOP 2);
  1266. END
  1267. END TRY
  1268. BEGIN CATCH
  1269. IF @debugMode = 1
  1270. BEGIN
  1271. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred while determining which rowstore indexes to defragment. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  1272. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1273. --RAISERROR(' An error has occurred executing the pre-command! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 0, 42) WITH NOWAIT;
  1274. END
  1275. END CATCH
  1276. UPDATE #tblIndexDefragScanWorking
  1277. SET is_done = 1
  1278. WHERE objectID = @objectID AND indexID = @indexID AND partitionNumber = @partitionNumber
  1279. END;
  1280. -- Get columnstore indexes to work on
  1281. IF @debugMode = 1 AND @sqlmajorver >= 12
  1282. RAISERROR(' Getting columnstore indexes...', 0, 42) WITH NOWAIT;
  1283. IF @sqlmajorver >= 12
  1284. BEGIN
  1285. WHILE (SELECT COUNT(*) FROM #tblIndexDefragScanWorking WHERE is_done = 0 AND [type] IN (5,6)) > 0
  1286. BEGIN
  1287. SELECT TOP 1 @objectID = objectID, @indexID = indexID, @partitionNumber = partitionNumber
  1288. FROM #tblIndexDefragScanWorking WHERE is_done = 0 AND type IN (5,6)
  1289. BEGIN TRY
  1290. SELECT @ColumnStoreGetIXSQL = 'USE [' + DB_NAME(@dbID) + ']; SELECT @dbID_In, DB_NAME(@dbID_In), rg.object_id, rg.index_id, rg.partition_number, SUM((ISNULL(rg.deleted_rows,1)*100)/rg.total_rows) AS [fragmentation], SUM(ISNULL(rg.size_in_bytes,1)/1024/8) AS [simulated_page_count], SUM(rg.total_rows) AS total_rows, GETDATE() AS [scanDate]
  1291. FROM sys.column_store_row_groups rg
  1292. WHERE rg.object_id = @objectID_In
  1293. AND rg.index_id = @indexID_In
  1294. AND rg.partition_number = @partitionNumber_In
  1295. AND rg.state = 3 -- Only COMPRESSED row groups
  1296. GROUP BY rg.object_id, rg.index_id, rg.partition_number
  1297. OPTION (MAXDOP 2)'
  1298. SET @ColumnStoreGetIXSQL_Param = N'@dbID_In int, @objectID_In int, @indexID_In int, @partitionNumber_In smallint';
  1299. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Working (dbID, dbName, objectID, indexID, partitionNumber, fragmentation, page_count, record_count, scanDate)
  1300. EXECUTE sp_executesql @ColumnStoreGetIXSQL, @ColumnStoreGetIXSQL_Param, @dbID_In = @dbID, @objectID_In = @objectID, @indexID_In = @indexID, @partitionNumber_In = @partitionNumber;
  1301. END TRY
  1302. BEGIN CATCH
  1303. IF @debugMode = 1
  1304. BEGIN
  1305. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred while determining which columnstore indexes to defragment. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  1306. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1307. --RAISERROR(' An error has occurred executing the pre-command! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 0, 42) WITH NOWAIT;
  1308. END
  1309. END CATCH
  1310. UPDATE #tblIndexDefragScanWorking
  1311. SET is_done = 1
  1312. WHERE objectID = @objectID AND indexID = @indexID AND partitionNumber = @partitionNumber
  1313. END
  1314. END;
  1315. IF @debugMode = 1
  1316. RAISERROR(' Looking up additional index information...', 0, 42) WITH NOWAIT;
  1317. /* Look up index status for various purposes */
  1318. SELECT @updateSQL = N'UPDATE ids
  1319. SET schemaName = QUOTENAME(s.name), objectName = QUOTENAME(o.name), indexName = QUOTENAME(i.name), is_primary_key = i.is_primary_key, fill_factor = i.fill_factor, is_disabled = i.is_disabled, is_padded = i.is_padded, is_hypothetical = i.is_hypothetical, has_filter = ' + CASE WHEN @sqlmajorver >= 10 THEN 'i.has_filter' ELSE '0' END + ', allow_page_locks = i.allow_page_locks, type = i.type
  1320. FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Working ids
  1321. INNER JOIN [' + DB_NAME(@dbID) + '].sys.objects AS o ON ids.objectID = o.object_id
  1322. INNER JOIN [' + DB_NAME(@dbID) + '].sys.indexes AS i ON o.object_id = i.object_id AND ids.indexID = i.index_id
  1323. INNER JOIN [' + DB_NAME(@dbID) + '].sys.schemas AS s ON o.schema_id = s.schema_id
  1324. WHERE o.object_id = ids.objectID AND i.index_id = ids.indexID AND i.type > 0
  1325. AND o.object_id NOT IN (SELECT sit.object_id FROM [' + DB_NAME(@dbID) + '].sys.internal_tables AS sit)
  1326. AND ids.[dbID] = ' + CAST(@dbID AS NVARCHAR(10));
  1327. EXECUTE sp_executesql @updateSQL;
  1328. IF @scanMode = 'LIMITED'
  1329. BEGIN
  1330. SELECT @updateSQL = N'UPDATE ids
  1331. SET record_count = [rows]
  1332. FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Working ids
  1333. INNER JOIN [' + DB_NAME(@dbID) + '].sys.partitions AS p ON ids.objectID = p.[object_id] AND ids.indexID = p.index_id AND ids.partitionNumber = p.partition_number
  1334. WHERE ids.[dbID] = ' + CAST(@dbID AS NVARCHAR(10));
  1335. EXECUTE sp_executesql @updateSQL;
  1336. END
  1337. IF @debugMode = 1
  1338. RAISERROR(' Looking up additional statistic information...', 0, 42) WITH NOWAIT;
  1339. /* Look up stats information for various purposes */
  1340. IF @tblName IS NULL
  1341. BEGIN
  1342. SELECT @updateSQL = N'USE [' + DB_NAME(@dbID) + '];
  1343. SELECT DISTINCT ' + CAST(@dbID AS NVARCHAR(10)) + ', ''' + QUOTENAME(DB_NAME(@dbID)) + ''', ss.[object_id], ss.stats_id, ' + CASE WHEN @sqlmajorver >= 12 THEN 'ISNULL(sp.partition_number,1),' ELSE '1,' END + '
  1344. QUOTENAME(s.name), QUOTENAME(so.name), QUOTENAME(ss.name), ss.[no_recompute], ' + CASE WHEN @sqlmajorver < 12 THEN '0 AS ' ELSE 'ss.' END + '[is_incremental], GETDATE() AS scanDate
  1345. FROM sys.stats ss
  1346. INNER JOIN sys.objects so ON ss.[object_id] = so.[object_id]
  1347. INNER JOIN sys.schemas s ON so.[schema_id] = s.[schema_id]
  1348. LEFT JOIN sys.indexes si ON ss.[object_id] = si.[object_id] and ss.name = si.name
  1349. ' + CASE WHEN ((@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver > 12) THEN 'CROSS APPLY sys.dm_db_stats_properties_internal(ss.[object_id], ss.stats_id) sp' ELSE '' END + '
  1350. WHERE is_ms_shipped = 0 ' + CASE WHEN @sqlmajorver >= 12 THEN 'AND ss.is_temporary = 0' ELSE '' END + '
  1351. AND so.[object_id] NOT IN (SELECT sit.[object_id] FROM sys.internal_tables AS sit)
  1352. AND so.[type] IN (''U'',''V'')
  1353. AND (si.[type] IS NULL OR si.[type] NOT IN (5,6,7))' -- Avoid error 35337
  1354. END
  1355. ELSE
  1356. BEGIN
  1357. DECLARE @tblNameOnly NVARCHAR(1000), @schemaNameOnly NVARCHAR(128)
  1358. SELECT @tblNameOnly = RIGHT(@tblName, LEN(@tblName) - CHARINDEX('.', @tblName, 1)), @schemaNameOnly = LEFT(@tblName, CHARINDEX('.', @tblName, 1) -1)
  1359. SELECT @updateSQL = N'USE [' + DB_NAME(@dbID) + '];
  1360. SELECT DISTINCT ' + CAST(@dbID AS NVARCHAR(10)) + ', ''' + QUOTENAME(DB_NAME(@dbID)) + ''', ss.[object_id], ss.stats_id, ' + CASE WHEN @sqlmajorver >= 12 THEN 'ISNULL(sp.partition_number,1),' ELSE '1,' END + '
  1361. QUOTENAME(s.name), QUOTENAME(so.name), QUOTENAME(ss.name), ss.[no_recompute], ' + CASE WHEN @sqlmajorver < 12 THEN '0 AS ' ELSE 'ss.' END + '[is_incremental], GETDATE() AS scanDate
  1362. FROM sys.stats ss
  1363. INNER JOIN sys.objects so ON ss.[object_id] = so.[object_id]
  1364. INNER JOIN sys.schemas s ON so.[schema_id] = s.[schema_id]
  1365. LEFT JOIN sys.indexes si ON ss.[object_id] = si.[object_id] and ss.name = si.name
  1366. ' + CASE WHEN @sqlmajorver >= 12 THEN 'CROSS APPLY sys.dm_db_stats_properties_internal(ss.[object_id], ss.stats_id) sp' ELSE '' END + '
  1367. WHERE is_ms_shipped = 0 ' + CASE WHEN @sqlmajorver >= 12 THEN 'AND ss.is_temporary = 0' ELSE '' END + '
  1368. AND so.[object_id] NOT IN (SELECT sit.[object_id] FROM sys.internal_tables AS sit)
  1369. AND s.name = ''' + @schemaNameOnly + '''
  1370. AND so.name = ''' + @tblNameOnly + '''
  1371. AND so.[type] IN (''U'',''V'')
  1372. AND (si.[type] IS NULL OR si.[type] NOT IN (5,6,7))' -- Avoid error 35337
  1373. END
  1374. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Stats_Working (dbID, dbName, objectID, statsID, partitionNumber, schemaName, objectName, statsName, [no_recompute], [is_incremental], scanDate)
  1375. EXECUTE sp_executesql @updateSQL;
  1376. /* Keep track of which databases have already been scanned */
  1377. UPDATE #tblIndexDefragDatabaseList
  1378. SET scanStatus = 1
  1379. WHERE dbID = @dbID;
  1380. END;
  1381. /* Delete any records for disabled (except those disabled by the defrag cycle itself) or hypothetical indexes */
  1382. IF @debugMode = 1
  1383. RAISERROR(' Listing and removing disabled indexes (except those disabled by the defrag cycle itself) or hypothetical indexes from loop...', 0, 42) WITH NOWAIT;
  1384. IF (SELECT COUNT(*) FROM dbo.tbl_AdaptiveIndexDefrag_Working AS ids WHERE ids.is_disabled = 1 OR ids.is_hypothetical = 1) > 0
  1385. DELETE ids
  1386. FROM dbo.tbl_AdaptiveIndexDefrag_Working AS ids
  1387. LEFT JOIN dbo.tbl_AdaptiveIndexDefrag_IxDisableStatus AS ids_disable ON ids.objectID = ids_disable.objectID AND ids.indexID = ids_disable.indexID AND ids.[dbID] = ids_disable.dbID
  1388. WHERE ids.is_disabled = 1 OR ids.is_hypothetical = 1 AND ids_disable.indexID IS NULL;
  1389. IF @debugMode = 1
  1390. RAISERROR(' Updating Exception mask for any index that has a restriction on the days it CANNOT be defragmented...', 0, 42) WITH NOWAIT;
  1391. /* Update our Exception mask for any index that has a restriction on the days it CANNOT be defragmented
  1392. based on 1=Sunday, 2=Monday, 4=Tuesday, 8=Wednesday, 16=Thursday, 32=Friday, 64=Saturday, 127=AllWeek
  1393. */
  1394. UPDATE ids
  1395. SET ids.exclusionMask = ide.exclusionMask
  1396. FROM dbo.tbl_AdaptiveIndexDefrag_Working AS ids
  1397. INNER JOIN dbo.tbl_AdaptiveIndexDefrag_Exceptions AS ide ON ids.[dbID] = ide.[dbID] AND ids.objectID = ide.objectID AND ids.indexID = ide.indexID;
  1398. END;
  1399. IF @debugMode = 1
  1400. SELECT @debugMessage = 'Looping through batch list... There are ' + CAST(COUNT(DISTINCT indexName) AS NVARCHAR(10)) + ' indexes to defragment in ' + CAST(COUNT(DISTINCT dbName) AS NVARCHAR(10)) + ' database(s)!'
  1401. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  1402. WHERE defragDate IS NULL AND page_count BETWEEN @minPageCount AND ISNULL(@maxPageCount, page_count) AND exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0;
  1403. IF @debugMode = 1
  1404. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1405. IF @debugMode = 1
  1406. BEGIN
  1407. IF @updateStatsWhere = 1
  1408. BEGIN
  1409. SELECT @debugMessage = 'Looping through batch list... There are ' + CAST(COUNT(DISTINCT statsName) AS NVARCHAR(10)) + ' index related statistics to update in ' + CAST(COUNT(DISTINCT idss.dbName) AS NVARCHAR(10)) + ' database(s)!'
  1410. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss
  1411. INNER JOIN dbo.tbl_AdaptiveIndexDefrag_Working ids ON ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID
  1412. WHERE idss.schemaName = ids.schemaName AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0;
  1413. END
  1414. ELSE
  1415. BEGIN
  1416. SELECT @debugMessage = 'Looping through batch list... There are ' + CAST(COUNT(DISTINCT statsName) AS NVARCHAR(10)) + ' index related statistics to update in ' + CAST(COUNT(DISTINCT idss.dbName) AS NVARCHAR(10)) + ' database(s),'
  1417. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss
  1418. INNER JOIN dbo.tbl_AdaptiveIndexDefrag_Working ids ON ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID
  1419. WHERE idss.schemaName = ids.schemaName AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0;
  1420. SELECT @debugMessage = @debugMessage + ' plus ' + CAST(COUNT(DISTINCT statsName) AS NVARCHAR(10)) + ' other statistics to update in ' + CAST(COUNT(DISTINCT dbName) AS NVARCHAR(10)) + ' database(s)!'
  1421. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss
  1422. WHERE idss.updateDate IS NULL
  1423. AND NOT EXISTS (SELECT TOP 1 objectID FROM dbo.tbl_AdaptiveIndexDefrag_Working ids WHERE ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0);
  1424. END
  1425. END
  1426. IF @debugMode = 1
  1427. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1428. IF @Exec_Print = 0 AND @printCmds = 1
  1429. BEGIN
  1430. RAISERROR(' Printing SQL statements...', 0, 42) WITH NOWAIT;
  1431. END;
  1432. /* Begin defragmentation loop */
  1433. WHILE (SELECT COUNT(*) FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE ((@Exec_Print = 1 AND defragDate IS NULL) OR (@Exec_Print = 0 AND defragDate IS NULL AND printStatus = 0)) AND exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0 AND page_count BETWEEN @minPageCount AND ISNULL(@maxPageCount, page_count)) > 0
  1434. BEGIN
  1435. /* Check to see if we need to exit loop because of our time limit */
  1436. IF ISNULL(@endDateTime, GETDATE()) < GETDATE()
  1437. RAISERROR('Time limit has been exceeded for this maintenance window!', 16, 42) WITH NOWAIT;
  1438. IF @debugMode = 1
  1439. RAISERROR(' Selecting an index to defragment...', 0, 42) WITH NOWAIT;
  1440. /* Select the index with highest priority, based on the values submitted; Verify date constraint for this index in the Exception table */
  1441. SET @getIndexSQL = N'SELECT TOP 1 @objectID_Out = objectID, @indexID_Out = indexID, @dbID_Out = dbID
  1442. FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE defragDate IS NULL '
  1443. + CASE WHEN @Exec_Print = 0 THEN 'AND printStatus = 0 ' ELSE '' END + '
  1444. AND exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0
  1445. AND page_count BETWEEN @p_minPageCount AND ISNULL(@p_maxPageCount, page_count)
  1446. ORDER BY + ' + @defragOrderColumn + ' ' + @defragSortOrder;
  1447. SET @getIndexSQL_Param = N'@objectID_Out int OUTPUT, @indexID_Out int OUTPUT, @dbID_Out int OUTPUT, @p_minPageCount int, @p_maxPageCount int';
  1448. EXECUTE sp_executesql @getIndexSQL, @getIndexSQL_Param, @p_minPageCount = @minPageCount, @p_maxPageCount = @maxPageCount, @objectID_Out = @objectID OUTPUT, @indexID_Out = @indexID OUTPUT, @dbID_Out = @dbID OUTPUT;
  1449. IF @debugMode = 1
  1450. RAISERROR(' Getting partition count...', 0, 42) WITH NOWAIT;
  1451. /* Determine if the index is partitioned */
  1452. SELECT @partitionCount = MAX(partitionNumber)
  1453. FROM dbo.tbl_AdaptiveIndexDefrag_Working AS ids
  1454. WHERE objectID = @objectID AND indexID = @indexID AND dbID = @dbID
  1455. IF @debugMode = 1
  1456. RAISERROR(' Getting selected index information...', 0, 42) WITH NOWAIT;
  1457. /* Get object names and info */
  1458. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1459. BEGIN
  1460. SELECT TOP 1 @objectName = objectName, @schemaName = schemaName, @indexName = indexName, @dbName = dbName, @fragmentation = fragmentation, @partitionNumber = partitionNumber, @pageCount = page_count, @range_scan_count = range_scan_count, @is_primary_key = is_primary_key, @fill_factor = fill_factor, @record_count = record_count, @ixtype = [type], @is_disabled = is_disabled, @is_padded = is_padded, @has_filter = has_filter
  1461. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  1462. WHERE objectID = @objectID AND indexID = @indexID AND dbID = @dbID AND ((@Exec_Print = 1 AND defragDate IS NULL) OR (@Exec_Print = 0 AND defragDate IS NULL AND printStatus = 0));
  1463. END
  1464. ELSE
  1465. BEGIN
  1466. SELECT TOP 1 @objectName = objectName, @schemaName = schemaName, @indexName = indexName, @dbName = dbName, @fragmentation = fragmentation, @partitionNumber = NULL, @pageCount = page_count, @range_scan_count = range_scan_count, @is_primary_key = is_primary_key, @fill_factor = fill_factor, @record_count = record_count, @ixtype = [type], @is_disabled = is_disabled, @is_padded = is_padded, @has_filter = has_filter
  1467. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  1468. WHERE objectID = @objectID AND indexID = @indexID AND dbID = @dbID AND ((@Exec_Print = 1 AND defragDate IS NULL) OR (@Exec_Print = 0 AND defragDate IS NULL AND printStatus = 0));
  1469. END
  1470. /* Determine maximum partition number for use with stats update*/
  1471. IF @updateStats = 1
  1472. BEGIN
  1473. SELECT @maxpartitionNumber = MAX(partitionNumber), @minpartitionNumber = MIN(partitionNumber)
  1474. FROM tbl_AdaptiveIndexDefrag_Working
  1475. WHERE objectID = @objectID AND indexID = @indexID AND dbID = @dbID;
  1476. END
  1477. IF @debugMode = 1
  1478. RAISERROR(' Checking if any LOBs exist...', 0, 42) WITH NOWAIT;
  1479. SET @containsLOB = 0
  1480. /* Determine if the index contains LOBs, with info from sys.types */
  1481. IF @ixtype = 2 AND @sqlmajorver < 11 -- Nonclustered and LOBs in INCLUDED columns? Up to SQL 2008R2
  1482. BEGIN
  1483. SELECT @LOB_SQL = 'SELECT @containsLOB_OUT = COUNT(*) FROM ' + @dbName + '.sys.columns c WITH (NOLOCK)
  1484. INNER JOIN ' + @dbName + '.sys.index_columns ic WITH (NOLOCK) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
  1485. INNER JOIN ' + @dbName + '.sys.indexes i WITH (NOLOCK) ON i.[object_id] = ic.[object_id] and i.index_id = ic.index_id
  1486. WHERE max_length = -1 AND ic.is_included_column = 1
  1487. AND i.object_id = ' + CAST(@objectID AS NVARCHAR(10)) + ' AND i.index_id = ' + CAST(@indexID AS NVARCHAR(10)) + ';'
  1488. /* max_length = -1 for VARBINARY(MAX), VARCHAR(MAX), NVARCHAR(MAX), XML */
  1489. ,@LOB_SQL_Param = '@containsLOB_OUT int OUTPUT';
  1490. EXECUTE sp_executesql @LOB_SQL, @LOB_SQL_Param, @containsLOB_OUT = @containsLOB OUTPUT;
  1491. IF @debugMode = 1 AND @containsLOB > 0 AND @onlineRebuild = 1
  1492. RAISERROR(' Online rebuild not possible on indexes with LOBs in INCLUDED columns...', 0, 42) WITH NOWAIT;
  1493. END
  1494. IF @ixtype = 1 -- Clustered and has LOBs in table?
  1495. BEGIN
  1496. SELECT @LOB_SQL = 'SELECT @containsLOB_OUT = COUNT(*) FROM ' + @dbName + '.sys.columns c WITH (NOLOCK)
  1497. INNER JOIN ' + @dbName + '.sys.indexes i WITH (NOLOCK) ON c.[object_id] = i.[object_id]
  1498. WHERE system_type_id IN (34, 35, 99) ' + CASE WHEN @sqlmajorver < 11 THEN 'OR max_length = -1 ' ELSE '' END +
  1499. 'AND i.object_id = ' + CAST(@objectID AS NVARCHAR(10)) + ' AND i.index_id = ' + CAST(@indexID AS NVARCHAR(10)) + ';'
  1500. /* system_type_id = 34 for IMAGE, 35 for TEXT, 99 for NTEXT,
  1501. max_length = -1 for VARBINARY(MAX), VARCHAR(MAX), NVARCHAR(MAX), XML */
  1502. ,@LOB_SQL_Param = '@containsLOB_OUT int OUTPUT';
  1503. EXECUTE sp_executesql @LOB_SQL, @LOB_SQL_Param, @containsLOB_OUT = @containsLOB OUTPUT;
  1504. IF @debugMode = 1 AND @containsLOB > 0 AND @onlineRebuild = 1
  1505. RAISERROR(' Online rebuild not possible on clustered index when certain LOBs exist in table...', 0, 42) WITH NOWAIT;
  1506. END
  1507. IF @debugMode = 1 AND (@sqlmajorver >= 11 OR @ixtype IN (5,6))
  1508. RAISERROR(' Checking for Columnstore index...', 0, 42) WITH NOWAIT;
  1509. SET @containsColumnstore = 0
  1510. IF @ixtype NOT IN (5,6) -- Not already in the scope of a Columnstore index
  1511. AND @sqlmajorver >= 11 -- Parent table has Columnstore indexes?
  1512. BEGIN
  1513. SELECT @CStore_SQL = 'SELECT @containsColumnstore_OUT = COUNT(*) FROM ' + @dbName + '.sys.indexes i WITH (NOLOCK) WHERE i.object_id = ' + CAST(@objectID AS NVARCHAR(10)) + ' AND i.type IN (5,6);'
  1514. ,@CStore_SQL_Param = '@containsColumnstore_OUT int OUTPUT';
  1515. EXECUTE sp_executesql @CStore_SQL, @CStore_SQL_Param, @containsColumnstore_OUT = @containsColumnstore OUTPUT;
  1516. IF @debugMode = 1 AND @containsColumnstore > 0 AND @onlineRebuild = 1
  1517. RAISERROR(' Online rebuild not possible when parent table has Columnstore index...', 0, 42) WITH NOWAIT;
  1518. END
  1519. IF @ixtype IN (5,6)
  1520. BEGIN
  1521. SET @containsColumnstore = 1
  1522. IF @debugMode = 1 AND @containsColumnstore > 0 AND @onlineRebuild = 1
  1523. RAISERROR(' Online rebuild not possible on Columnstore indexes...', 0, 42) WITH NOWAIT;
  1524. END
  1525. IF @debugMode = 1
  1526. RAISERROR(' Checking if index does not allow page locks...', 0, 42) WITH NOWAIT;
  1527. /* Determine if page locks are not allowed; these must always rebuild; if @forceRescan = 0 then always check in real time in case it has changed*/
  1528. IF @forceRescan = 0
  1529. BEGIN
  1530. SELECT @allowPageLockSQL = 'SELECT @allowPageLocks_OUT = allow_page_locks FROM ' + @dbName + '.sys.indexes WHERE [object_id] = ' + CAST(@objectID AS NVARCHAR(10)) + ' AND [index_id] = ' + CAST(@indexID AS NVARCHAR(10)) + ';'
  1531. ,@allowPageLockSQL_Param = '@allowPageLocks_OUT bit OUTPUT';
  1532. EXECUTE sp_executesql @allowPageLockSQL, @allowPageLockSQL_Param, @allowPageLocks_OUT = @allowPageLocks OUTPUT;
  1533. END
  1534. ELSE
  1535. BEGIN
  1536. SELECT @allowPageLocks = [allow_page_locks] FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE objectID = @objectID AND indexID = @indexID AND [dbID] = @dbID
  1537. END
  1538. IF @debugMode = 1 AND @allowPageLocks = 0
  1539. RAISERROR(' Index does not allow page locks...', 0, 42) WITH NOWAIT;
  1540. IF @debugMode = 1
  1541. BEGIN
  1542. SELECT @debugMessage = ' Found ' + CONVERT(NVARCHAR(10), @fragmentation) + ' percent fragmentation on index ' + @indexName + '...';
  1543. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1544. END
  1545. IF @debugMode = 1
  1546. RAISERROR(' Building SQL statements...', 0, 42) WITH NOWAIT;
  1547. /* If there's not a lot of fragmentation, or if we have a LOB, we should reorganize.
  1548. Filtered indexes or indexes that do not allow page locks should always rebuild. */
  1549. IF (@fragmentation < @rebuildThreshold AND @ixtype IN (1,2) AND @has_filter = 0 AND @allowPageLocks = 1)
  1550. OR (@fragmentation < @rebuildThreshold_cs AND @ixtype IN (5,6))
  1551. BEGIN
  1552. SET @operationFlag = 0
  1553. /* Set Reorg command */
  1554. SET @sqlcommand = N'ALTER INDEX ' + @indexName + N' ON ' + @dbName + N'.' + @schemaName + N'.' + @objectName + N' REORGANIZE';
  1555. /* Set partition reorg options; requires Enterprise Edition; valid only if more than one partition exists */
  1556. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1557. SET @sqlcommand = @sqlcommand + N' PARTITION = ' + CAST(@partitionNumber AS NVARCHAR(10));
  1558. /* Set LOB reorg options; valid only if no more than one partition exists */
  1559. IF @dealLOB = 1 AND @partitionCount = 1 AND @ixtype IN (1,2)
  1560. SET @sqlcommand = @sqlcommand + N' WITH (LOB_COMPACTION = OFF)';
  1561. IF @dealLOB = 0 AND @partitionCount = 1 AND @ixtype IN (1,2)
  1562. SET @sqlcommand = @sqlcommand + N' WITH (LOB_COMPACTION = ON)';
  1563. /* Set Columnstore reorg option to compress all rowgroups, and not just closed ones */
  1564. IF @sqlmajorver >= 12 AND @dealROWG = 1 AND @ixtype IN (5,6)
  1565. SET @sqlcommand = @sqlcommand + N' WITH (COMPRESS_ALL_ROW_GROUPS = ON)';
  1566. SET @sqlcommand = @sqlcommand + N';';
  1567. END
  1568. /* If the index is heavily fragmented and doesn't contain any partitions,
  1569. or if the index does not allow page locks, or if it is a filtered index, rebuild it */
  1570. ELSE IF (@fragmentation >= @rebuildThreshold AND @ixtype IN (1,2))
  1571. OR (@fragmentation >= @rebuildThreshold_cs AND @ixtype IN (5,6))
  1572. OR @has_filter = 1 OR @allowPageLocks = 0
  1573. BEGIN
  1574. SET @rebuildcommand = N' REBUILD'
  1575. SET @operationFlag = 1
  1576. /* Set partition rebuild options; requires Enterprise Edition; valid only if more than one partition exists */
  1577. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1578. SET @rebuildcommand = @rebuildcommand + N' PARTITION = ' + CAST(@partitionNumber AS NVARCHAR(10));
  1579. --ELSE IF @dealMaxPartition IS NULL AND @editionCheck = 1 AND @partitionCount > 1
  1580. --SET @rebuildcommand = @rebuildcommand + N' PARTITION = ALL';
  1581. /* Disallow disabling indexes on partitioned tables when defraging a subset of existing partitions */
  1582. IF @dealMaxPartition IS NOT NULL AND @partitionCount > 1
  1583. SET @disableNCIX = 0
  1584. /* Set defrag options*/
  1585. SET @rebuildcommand = @rebuildcommand + N' WITH ('
  1586. /* Set index pad options; not compatible with partition operations*/
  1587. IF @is_padded = 1 AND (@dealMaxPartition IS NULL OR (@dealMaxPartition IS NOT NULL AND @partitionCount = 1))
  1588. SET @rebuildcommand = @rebuildcommand + N'PAD_INDEX = ON, '
  1589. /* Set online rebuild options; requires Enterprise Edition; not compatible with partition operations, Columnstore indexes in table and XML or Spatial indexes.
  1590. Up to SQL Server 2008R2, not compatible with clustered indexes with LOB columnns in table or non-clustered indexes with LOBs in INCLUDED columns.
  1591. In SQL Server 2012, not compatible with clustered indexes with LOB columnns in table.*/
  1592. IF @sqlmajorver <= 11 AND @onlineRebuild = 1 AND @editionCheck = 1
  1593. AND @ixtype IN (1,2) AND @containsLOB = 0
  1594. AND (@dealMaxPartition IS NULL OR (@dealMaxPartition IS NOT NULL AND @partitionCount = 1))
  1595. SET @rebuildcommand = @rebuildcommand + N'ONLINE = ON, ';
  1596. /* Set online rebuild options; requires Enterprise Edition; not compatible with partition operations, Columnstore indexes in table and XML or Spatial indexes.
  1597. In SQL Server 2014, not compatible with clustered indexes with LOB columnns in table, but compatible with partition operations.
  1598. Also, we can use Lock Priority with online indexing.*/
  1599. IF @sqlmajorver > 11 AND @onlineRebuild = 1 AND @editionCheck = 1
  1600. AND @ixtype IN (1,2) AND @containsLOB = 0
  1601. SELECT @rebuildcommand = @rebuildcommand + N'ONLINE = ON (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CONVERT(NVARCHAR(15), @onlinelocktimeout) + ', ABORT_AFTER_WAIT = ' + CASE WHEN @abortAfterwait = 0 THEN 'BLOCKERS' WHEN @abortAfterwait = 1 THEN 'SELF' ELSE 'NONE' END + ')), '
  1602. /* Set fill factor operation preferences; not compatible with partition operations and Columnstore indexes*/
  1603. IF @fillfactor = 1 AND (@dealMaxPartition IS NULL OR (@dealMaxPartition IS NOT NULL AND @partitionCount = 1)) AND @ixtype IN (1,2)
  1604. SET @rebuildcommand = @rebuildcommand + N'FILLFACTOR = ' + CONVERT(NVARCHAR, CASE WHEN @fill_factor = 0 THEN 100 ELSE @fill_factor END) + N', ';
  1605. IF @fillfactor = 0 AND (@dealMaxPartition IS NULL OR (@dealMaxPartition IS NOT NULL AND @partitionCount = 1)) AND @ixtype IN (1,2)
  1606. SET @rebuildcommand = @rebuildcommand + N'FILLFACTOR = 100, ';
  1607. /* Set sort operation preferences */
  1608. IF @sortInTempDB = 1 AND @ixtype IN (1,2)
  1609. SET @rebuildcommand = @rebuildcommand + N'SORT_IN_TEMPDB = ON, ';
  1610. IF @sortInTempDB = 0 AND @ixtype IN (1,2)
  1611. SET @rebuildcommand = @rebuildcommand + N'SORT_IN_TEMPDB = OFF, ';
  1612. /* Set NO_RECOMPUTE preference */
  1613. IF @ix_statsnorecompute = 1 AND @ixtype IN (1,2)
  1614. SET @sqlcommand = @sqlcommand + N' STATISTICS_NORECOMPUTE = ON, ';
  1615. IF @ix_statsnorecompute = 0 AND @ixtype IN (1,2)
  1616. SET @sqlcommand = @sqlcommand + N' STATISTICS_NORECOMPUTE = OFF, ';
  1617. /* Set processor restriction options; requires Enterprise Edition */
  1618. IF @maxDopRestriction IS NOT NULL AND @editionCheck = 1
  1619. SET @rebuildcommand = @rebuildcommand + N'MAXDOP = ' + CAST(@maxDopRestriction AS VARCHAR(2)) + N');';
  1620. ELSE
  1621. SET @rebuildcommand = @rebuildcommand + N');';
  1622. IF @rebuildcommand LIKE '% WITH ();'
  1623. SET @rebuildcommand = REPLACE(@rebuildcommand, ' WITH ()', '')
  1624. /* Set NCIX disable command, except for clustered index*/
  1625. SET @sqldisablecommand = NULL
  1626. IF @disableNCIX = 1 AND @ixtype = 2 AND @is_primary_key = 0
  1627. BEGIN
  1628. SET @sqldisablecommand = N'ALTER INDEX ' + @indexName + N' ON ' + @dbName + N'.' + @schemaName + N'.' + @objectName + ' DISABLE;';
  1629. END
  1630. /* Set update statistics command for index only, before rebuild, as rebuild performance is dependent on statistics (only working on non-partitioned tables)
  1631. http://blogs.msdn.com/b/psssql/archive/2009/03/18/be-aware-of-parallel-index-creation-performance-issues.aspx */
  1632. SET @sqlprecommand = NULL
  1633. /* Is stat incremental? */
  1634. SELECT TOP 1 @stats_isincremental = [is_incremental] FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1635. WHERE dbName = @dbName AND schemaName = @schemaName AND objectName = @objectName AND statsName = @indexName;
  1636. IF (@sqlmajorver < 13 OR @partitionCount = 1) AND @sqldisablecommand IS NULL AND @ixtype IN (1,2)
  1637. BEGIN
  1638. SET @sqlprecommand = N'UPDATE STATISTICS ' + @dbName + N'.' + @schemaName + N'.' + @objectName + N' (' + @indexName + N')'
  1639. SET @sqlprecommand = @sqlprecommand + N'; '
  1640. END
  1641. ELSE IF @sqlmajorver >= 13 AND @partitionCount > 1 AND @stats_isincremental = 1 AND @sqldisablecommand IS NULL AND @ixtype IN (1,2)
  1642. BEGIN
  1643. SET @sqlprecommand = N'UPDATE STATISTICS ' + @dbName + N'.' + @schemaName + N'.' + @objectName + N' (' + @indexName + N') WITH RESAMPLE ON PARTITIONS(' + CONVERT(NVARCHAR(10), @partitionNumber) + N')'
  1644. SET @sqlprecommand = @sqlprecommand + N'; '
  1645. END
  1646. /* Set Rebuild command */
  1647. SET @sqlcommand = N'ALTER INDEX ' + @indexName + N' ON ' + @dbName + N'.' + @schemaName + N'.' + @objectName + REPLACE(@rebuildcommand,', )', ')');
  1648. /* For offline rebuilds, set lock timeout if not default */
  1649. IF @onlineRebuild = 0 AND @offlinelocktimeout > -1 AND @offlinelocktimeout IS NOT NULL
  1650. SET @sqlcommand = 'SET LOCK_TIMEOUT ' + CONVERT(NVARCHAR(15), @offlinelocktimeout) + '; ' + @sqlcommand
  1651. END
  1652. ELSE
  1653. BEGIN
  1654. /* Print an error message if any indexes happen to not meet the criteria above */
  1655. IF @debugMode = 1
  1656. BEGIN
  1657. SET @debugMessage = 'We are unable to defrag index ' + @indexName + N' on table ' + @dbName + N'.' + @schemaName + N'.' + @objectName
  1658. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1659. END
  1660. END;
  1661. IF @operationFlag = 0 AND @sqlprecommand IS NOT NULL
  1662. SET @sqlprecommand = NULL
  1663. IF @operationFlag = 0 AND @sqldisablecommand IS NOT NULL
  1664. SET @sqldisablecommand = NULL
  1665. /* Are we executing the SQL? If so, do it */
  1666. IF @Exec_Print = 1
  1667. BEGIN
  1668. /* Get the time for logging purposes */
  1669. SET @dateTimeStart = GETDATE();
  1670. /* Start log actions */
  1671. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1672. BEGIN
  1673. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_log (dbID, dbName, objectID, objectName, indexID, indexName, partitionNumber, fragmentation, page_count, range_scan_count, fill_factor, dateTimeStart, sqlStatement)
  1674. SELECT @dbID, @dbName, @objectID, @objectName, @indexID, @indexName, @partitionNumber, @fragmentation, @pageCount, @range_scan_count, @fill_factor, @dateTimeStart, ISNULL(@sqlprecommand, '') + @sqlcommand;
  1675. END
  1676. ELSE
  1677. BEGIN
  1678. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_log (dbID, dbName, objectID, objectName, indexID, indexName, partitionNumber, fragmentation, page_count, range_scan_count, fill_factor, dateTimeStart, sqlStatement)
  1679. SELECT @dbID, @dbName, @objectID, @objectName, @indexID, @indexName, 1, @fragmentation, @pageCount, @range_scan_count, @fill_factor, @dateTimeStart, ISNULL(@sqlprecommand, '') + @sqlcommand;
  1680. END
  1681. SET @indexDefrag_id = SCOPE_IDENTITY();
  1682. IF @sqlprecommand IS NULL AND @sqldisablecommand IS NULL
  1683. BEGIN
  1684. SET @debugMessage = ' ' + @sqlcommand;
  1685. END
  1686. ELSE IF @sqlprecommand IS NOT NULL AND @sqldisablecommand IS NULL
  1687. BEGIN
  1688. SET @debugMessage = ' ' + @sqlprecommand + CHAR(10) + ' ' + @sqlcommand;
  1689. END;
  1690. ELSE IF @sqlprecommand IS NULL AND @sqldisablecommand IS NOT NULL
  1691. BEGIN
  1692. SET @debugMessage = ' ' + @sqldisablecommand + CHAR(10) + ' ' + @sqlcommand;
  1693. END;
  1694. ELSE IF @sqlprecommand IS NOT NULL AND @sqldisablecommand IS NOT NULL
  1695. BEGIN
  1696. SET @debugMessage = ' ' + @sqldisablecommand + CHAR(10) + ' ' + @sqlprecommand + CHAR(10) + ' ' + @sqlcommand;
  1697. END;
  1698. /* Print the commands we'll be executing, if specified to do so */
  1699. IF (@debugMode = 1 OR @printCmds = 1) AND @sqlcommand IS NOT NULL
  1700. BEGIN
  1701. RAISERROR(' Printing SQL statements...', 0, 42) WITH NOWAIT;
  1702. SET @debugMessage = ' Executing: ' + CHAR(10) + @debugMessage;
  1703. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1704. END;
  1705. /* Execute default update stats on index only. With better stats, index rebuild process will generally have better performance */
  1706. IF @operationFlag = 1
  1707. BEGIN
  1708. BEGIN TRY
  1709. EXECUTE sp_executesql @sqlprecommand;
  1710. SET @sqlprecommand = NULL
  1711. SET @dateTimeEnd = GETDATE();
  1712. /* Update log with completion time */
  1713. UPDATE dbo.tbl_AdaptiveIndexDefrag_log
  1714. SET dateTimeEnd = @dateTimeEnd, durationSeconds = DATEDIFF(second, @dateTimeStart, @dateTimeEnd)
  1715. WHERE indexDefrag_id = @indexDefrag_id AND dateTimeEnd IS NULL;
  1716. /* If rebuilding, update statistics log with completion time */
  1717. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1718. BEGIN
  1719. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Stats_log (dbID, dbName, objectID, objectName, statsID, statsName, [partitionNumber], [rows], [rows_sampled], [modification_counter], [no_recompute], dateTimeStart, dateTimeEnd, durationSeconds, sqlStatement)
  1720. SELECT @dbID, @dbName, @objectID, @objectName, statsID, statsName, @partitionNumber, -1, -1, -1, [no_recompute], @dateTimeStart, @dateTimeEnd, DATEDIFF(second, @dateTimeStart, @dateTimeEnd), @sqlcommand
  1721. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1722. WHERE objectID = @objectID AND dbID = @dbID
  1723. AND statsName = @indexName
  1724. AND ((@Exec_Print = 1 AND updateDate IS NULL) OR (@Exec_Print = 0 AND updateDate IS NULL AND printStatus = 0));
  1725. END
  1726. ELSE
  1727. BEGIN
  1728. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Stats_log (dbID, dbName, objectID, objectName, statsID, statsName, [partitionNumber], [rows], [rows_sampled], [modification_counter],[no_recompute], dateTimeStart, dateTimeEnd, durationSeconds, sqlStatement)
  1729. SELECT @dbID, @dbName, @objectID, @objectName, statsID, statsName, 1, -1, -1, -1, [no_recompute], @dateTimeStart, @dateTimeEnd, DATEDIFF(second, @dateTimeStart, @dateTimeEnd), @sqlcommand
  1730. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1731. WHERE objectID = @objectID AND dbID = @dbID
  1732. AND statsName = @indexName
  1733. AND ((@Exec_Print = 1 AND updateDate IS NULL) OR (@Exec_Print = 0 AND updateDate IS NULL AND printStatus = 0));
  1734. END
  1735. END TRY
  1736. BEGIN CATCH
  1737. /* Update log with error message */
  1738. UPDATE dbo.tbl_AdaptiveIndexDefrag_log
  1739. SET dateTimeEnd = GETDATE(), durationSeconds = -1, errorMessage = 'Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing the pre-command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  1740. WHERE indexDefrag_id = @indexDefrag_id AND dateTimeEnd IS NULL;
  1741. IF @debugMode = 1
  1742. BEGIN
  1743. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing the pre-command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  1744. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1745. --RAISERROR(' An error has occurred executing the pre-command! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 0, 42) WITH NOWAIT;
  1746. END
  1747. END CATCH
  1748. END;
  1749. /* Execute NCIX disable command */
  1750. IF @operationFlag = 1 AND @disableNCIX = 1 AND @indexID > 1 AND (@sqldisablecommand IS NOT NULL OR LEN(@sqldisablecommand) > 0)
  1751. BEGIN
  1752. BEGIN TRY
  1753. EXECUTE sp_executesql @sqldisablecommand;
  1754. /* Insert into working table for disabled state control */
  1755. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_IxDisableStatus (dbID, objectID, indexID, [is_disabled], dateTimeChange)
  1756. SELECT @dbID, @objectID, @indexID, 1, GETDATE()
  1757. END TRY
  1758. BEGIN CATCH
  1759. /* Delete from working table for disabled state control */
  1760. DELETE FROM dbo.tbl_AdaptiveIndexDefrag_IxDisableStatus
  1761. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID;
  1762. IF @debugMode = 1
  1763. BEGIN
  1764. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing the disable index command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  1765. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1766. --RAISERROR(' An error has occurred executing the disable index command! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 0, 42) WITH NOWAIT;
  1767. END
  1768. END CATCH
  1769. END;
  1770. /* Execute defrag! */
  1771. BEGIN TRY
  1772. EXECUTE sp_executesql @sqlcommand;
  1773. SET @dateTimeEnd = GETDATE();
  1774. UPDATE dbo.tbl_AdaptiveIndexDefrag_log
  1775. /* Update log with completion time */
  1776. SET dateTimeEnd = @dateTimeEnd, durationSeconds = DATEDIFF(second, @dateTimeStart, @dateTimeEnd)
  1777. WHERE indexDefrag_id = @indexDefrag_id AND dateTimeEnd IS NULL;
  1778. IF @operationFlag = 1 AND @disableNCIX = 1 AND @indexID > 1
  1779. BEGIN
  1780. /* Delete from working table for disabled state control */
  1781. DELETE FROM dbo.tbl_AdaptiveIndexDefrag_IxDisableStatus
  1782. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID;
  1783. END;
  1784. END TRY
  1785. BEGIN CATCH
  1786. /* Update log with error message */
  1787. UPDATE dbo.tbl_AdaptiveIndexDefrag_log
  1788. SET dateTimeEnd = GETDATE(), durationSeconds = -1, errorMessage = 'Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing this command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  1789. WHERE indexDefrag_id = @indexDefrag_id AND dateTimeEnd IS NULL;
  1790. IF @debugMode = 1
  1791. BEGIN
  1792. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing this command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  1793. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1794. --RAISERROR(' An error has occurred executing this command! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 0, 42) WITH NOWAIT;
  1795. END
  1796. END CATCH
  1797. /* Update working table and resume loop */
  1798. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1799. BEGIN
  1800. UPDATE dbo.tbl_AdaptiveIndexDefrag_Working
  1801. SET defragDate = ISNULL(@dateTimeEnd, GETDATE()), printStatus = 1
  1802. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID AND partitionNumber = @partitionNumber;
  1803. END
  1804. ELSE
  1805. BEGIN
  1806. UPDATE dbo.tbl_AdaptiveIndexDefrag_Working
  1807. SET defragDate = ISNULL(@dateTimeEnd, GETDATE()), printStatus = 1
  1808. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID;
  1809. END
  1810. IF @operationFlag = 1
  1811. BEGIN
  1812. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1813. SET updateDate = ISNULL(@dateTimeEnd, GETDATE()), printStatus = 1
  1814. WHERE objectID = @objectID AND dbID = @dbID AND statsName = @indexName;
  1815. END
  1816. /* Just a little breather for the server */
  1817. WAITFOR DELAY @defragDelay;
  1818. END;
  1819. ELSE IF @Exec_Print = 0
  1820. BEGIN
  1821. IF @operationFlag = 0 AND @sqlprecommand IS NOT NULL
  1822. SET @sqlprecommand = NULL
  1823. IF @sqlprecommand IS NULL AND (@sqldisablecommand IS NULL OR @sqldisablecommand = '')
  1824. BEGIN
  1825. SET @debugMessage = ' ' + @sqlcommand;
  1826. END
  1827. ELSE IF @sqlprecommand IS NOT NULL AND (@sqldisablecommand IS NULL OR @sqldisablecommand = '')
  1828. BEGIN
  1829. SET @debugMessage = ' ' + @sqlprecommand + CHAR(10) + ' ' + @sqlcommand;
  1830. END;
  1831. ELSE IF @sqlprecommand IS NULL AND (@sqldisablecommand IS NOT NULL OR LEN(@sqldisablecommand) > 0)
  1832. BEGIN
  1833. SET @debugMessage = ' ' + @sqldisablecommand + CHAR(10) + ' ' + @sqlcommand;
  1834. END;
  1835. ELSE IF @sqlprecommand IS NOT NULL AND (@sqldisablecommand IS NOT NULL OR LEN(@sqldisablecommand) > 0)
  1836. BEGIN
  1837. SET @debugMessage = ' ' + @sqldisablecommand + CHAR(10) + ' ' + @sqlprecommand + CHAR(10) + ' ' + @sqlcommand;
  1838. END;
  1839. /* Print the commands we're executing if specified to do so */
  1840. IF (@debugMode = 1 OR @printCmds = 1) AND @sqlcommand IS NOT NULL
  1841. BEGIN
  1842. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1843. END
  1844. /* Update working table and resume loop */
  1845. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1846. BEGIN
  1847. UPDATE dbo.tbl_AdaptiveIndexDefrag_Working
  1848. SET printStatus = 1
  1849. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID AND partitionNumber = @partitionNumber;
  1850. END
  1851. ELSE
  1852. BEGIN
  1853. UPDATE dbo.tbl_AdaptiveIndexDefrag_Working
  1854. SET printStatus = 1
  1855. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID;
  1856. END
  1857. IF @operationFlag = 1
  1858. BEGIN
  1859. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1860. SET printStatus = 1
  1861. WHERE objectID = @objectID AND dbID = @dbID AND statsName = @indexName;
  1862. END;
  1863. END;
  1864. IF @operationFlag = 0 AND @updateStats = 1 -- When reorganizing, update stats afterwards
  1865. AND @updateStatsWhere = 0 AND @ixtype NOT IN (5,6,7)
  1866. BEGIN
  1867. IF @debugMode = 1
  1868. RAISERROR(' Updating index related statistics using finer thresholds (if any)...', 0, 42) WITH NOWAIT;
  1869. /* Handling index related statistics */
  1870. IF @debugMode = 1
  1871. RAISERROR(' Selecting a statistic to update...', 0, 42) WITH NOWAIT;
  1872. /* Select the stat */
  1873. BEGIN TRY
  1874. SET @getStatSQL = N'SELECT TOP 1 @statsID_Out = idss.statsID FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss WHERE idss.updateDate IS NULL ' + CASE WHEN @Exec_Print = 0 THEN 'AND idss.printStatus = 0 ' ELSE '' END + ' AND idss.[dbID] = ' + CONVERT(NVARCHAR, @dbID) + ' AND idss.statsName = ''' + @indexName + '''' + ' AND idss.objectID = ' + CONVERT(NVARCHAR, @objectID) + ' AND EXISTS (SELECT TOP 1 objectID FROM dbo.tbl_AdaptiveIndexDefrag_Working ids WHERE ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0)';
  1875. SET @getStatSQL_Param = N'@statsID_Out int OUTPUT'
  1876. EXECUTE sp_executesql @getStatSQL, @getStatSQL_Param, @statsID_Out = @statsID OUTPUT;
  1877. END TRY
  1878. BEGIN CATCH
  1879. IF @debugMode = 1
  1880. BEGIN
  1881. SET @debugMessage = ' Error ' + CONVERT(VARCHAR(20),ERROR_NUMBER()) + ' has occurred while determining which statistic to update. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS VARCHAR(10)) + ')'
  1882. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1883. END
  1884. END CATCH
  1885. IF @debugMode = 1
  1886. RAISERROR(' Getting information on selected statistic...', 0, 42) WITH NOWAIT;
  1887. /* Get object name and auto update setting */
  1888. SELECT TOP 1 @statsName = statsName, @partitionNumber = partitionNumber, @stats_norecompute = [no_recompute], @stats_isincremental = [is_incremental]
  1889. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1890. WHERE objectID = @objectID AND statsID = @statsID AND [dbID] = @dbID;
  1891. IF @debugMode = 1
  1892. BEGIN
  1893. SET @debugMessage = ' Determining modification row counter for statistic ' + @statsName + ' on table or view ' + @objectName + ' of DB ' + @dbName + '...';
  1894. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1895. END;
  1896. /* Determine modification row counter to ascertain if update stats is required */
  1897. IF ((@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver >= 13) AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE')
  1898. BEGIN
  1899. IF @debugMode = 1
  1900. RAISERROR(' Using sys.dm_db_incremental_stats_properties DMF...', 0, 42) WITH NOWAIT;
  1901. SELECT @rowmodctrSQL = N'USE ' + @dbName + '; SELECT @rowmodctr_Out = ISNULL(modification_counter,0), @rows_Out = ISNULL(rows,0), @rows_sampled_Out = ISNULL(rows_sampled,0) FROM sys.dm_db_incremental_stats_properties(' + CAST(@statsObjectID AS NVARCHAR(10)) + ',' + CAST(@statsID AS NVARCHAR(10)) + ') WHERE partition_number = @partitionNumber_In;'
  1902. END
  1903. ELSE IF (@sqlmajorver = 12 AND @sqlbuild < 5000) AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE')
  1904. BEGIN
  1905. IF @debugMode = 1
  1906. RAISERROR(' Using sys.dm_db_stats_properties_internal DMF...', 0, 42) WITH NOWAIT;
  1907. SELECT @rowmodctrSQL = N'USE ' + @dbName + '; SELECT @rowmodctr_Out = ISNULL(modification_counter,0), @rows_Out = ISNULL(rows,0), @rows_sampled_Out = ISNULL(rows_sampled,0) FROM sys.dm_db_stats_properties_internal(' + CAST(@statsObjectID AS NVARCHAR(10)) + ',' + CAST(@statsID AS NVARCHAR(10)) + ') WHERE partition_number = @partitionNumber_In;'
  1908. END
  1909. ELSE IF ((@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4000) OR (@sqlmajorver = 11 AND @sqlbuild >= 3000) OR @sqlmajorver >= 12) AND (@stats_isincremental = 0 OR UPPER(@statsSample) = 'FULLSCAN')
  1910. BEGIN
  1911. IF @debugMode = 1
  1912. RAISERROR(' Using sys.dm_db_stats_properties DMF...', 0, 42) WITH NOWAIT;
  1913. SELECT @rowmodctrSQL = N'USE ' + @dbName + '; SELECT @rowmodctr_Out = ISNULL(modification_counter,0), @rows_Out = ISNULL(rows,0), @rows_sampled_Out = ISNULL(rows_sampled,0) FROM sys.dm_db_stats_properties(' + CAST(@statsObjectID AS NVARCHAR(10)) + ',' + CAST(@statsID AS NVARCHAR(10)) + ');'
  1914. END
  1915. ELSE
  1916. BEGIN
  1917. IF @debugMode = 1
  1918. RAISERROR(' Using sys.sysindexes...', 0, 42) WITH NOWAIT;
  1919. SELECT @rowmodctrSQL = N'USE ' + @dbName + '; SELECT @rowmodctr_Out = SUM(ISNULL(rowmodctr,0)), @rows_Out = ISNULL(rowcnt,0), @rows_sampled_Out = -1 FROM sys.sysindexes WHERE id = ' + CAST(@statsObjectID AS NVARCHAR(10)) + ' AND indid = ' + CAST(@statsID AS NVARCHAR(10)) + ' AND rowmodctr > 0;'
  1920. END
  1921. SET @rowmodctrSQL_Param = N'@partitionNumber_In smallint, @rowmodctr_Out bigint OUTPUT, @rows_Out bigint OUTPUT, @rows_sampled_Out bigint OUTPUT'
  1922. BEGIN TRY
  1923. EXECUTE sp_executesql @rowmodctrSQL, @rowmodctrSQL_Param, @partitionNumber_In = @partitionNumber, @rowmodctr_Out = @rowmodctr OUTPUT, @rows_Out = @rows OUTPUT, @rows_sampled_Out = @rows_sampled OUTPUT;
  1924. SET @rowmodctr = (SELECT ISNULL(@rowmodctr, 0));
  1925. END TRY
  1926. BEGIN CATCH
  1927. IF @debugMode = 1
  1928. BEGIN
  1929. SET @debugMessage = ' Error ' + CONVERT(VARCHAR(20),ERROR_NUMBER()) + ' has occurred while determining row modification counter. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS VARCHAR(10)) + ')'
  1930. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1931. END
  1932. END CATCH
  1933. IF @rows IS NOT NULL AND @rows > 0
  1934. SET @record_count = @rows
  1935. IF @debugMode = 1
  1936. BEGIN
  1937. SELECT @debugMessage = ' Found a row modification counter of ' + CONVERT(NVARCHAR(10), @rowmodctr) + ' and ' + CONVERT(NVARCHAR(10), @record_count) + ' rows' + CASE WHEN @stats_isincremental = 1 THEN ' on partition ' + CONVERT(NVARCHAR(10), @partitionNumber) ELSE '' END + '...';
  1938. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1939. END
  1940. /* Because we are reorganizing, we will update statistics if they have changed since last update with same threshold as TF2371.
  1941. Default rules for auto update stats are:
  1942. If the cardinality for a table is greater than 6, but less than or equal to 500, update status every 500 modifications.
  1943. If the cardinality for a table is greater than 500, update statistics when (500 + 20 percent of the table) changes have occurred.
  1944. Reference: http://support.microsoft.com/kb/195565
  1945. */
  1946. IF (
  1947. (@record_count BETWEEN 6 AND 500 AND @rowmodctr >= 500) OR -- like the default
  1948. (@record_count BETWEEN 501 AND 10000 AND (@rowmodctr >= (@record_count*20)/100 + 500 OR @rowmodctr >= SQRT(@record_count*1000))) OR -- 500 + 20 percent or simulate TF 2371
  1949. (@record_count BETWEEN 10001 AND 100000 AND (@rowmodctr >= (@record_count*15)/100 + 500 OR @rowmodctr >= SQRT(@record_count*1000))) OR -- 500 + 15 percent or simulate TF 2371
  1950. (@record_count BETWEEN 100001 AND 1000000 AND (@rowmodctr >= (@record_count*10)/100 + 500 OR @rowmodctr >= SQRT(@record_count*1000))) OR -- 500 + 10 percent or simulate TF 2371
  1951. (@record_count >= 1000001 AND (@rowmodctr >= (@record_count*5)/100 + 500 OR @rowmodctr >= SQRT(@record_count*1000))) -- 500 + 5 percent or simulate TF 2371
  1952. )
  1953. BEGIN
  1954. SET @sqlcommand2 = N'UPDATE STATISTICS ' + @dbName + N'.'+ @schemaName + N'.' + @objectName + N' (' + @statsName + N')'
  1955. IF UPPER(@statsSample) = 'FULLSCAN' AND (@partitionNumber = 1 OR @partitionNumber = @maxpartitionNumber)
  1956. SET @sqlcommand2 = @sqlcommand2 + N' WITH FULLSCAN'
  1957. ELSE IF UPPER(@statsSample) = 'RESAMPLE'
  1958. SET @sqlcommand2 = @sqlcommand2 + N' WITH RESAMPLE'
  1959. IF @partitionCount > 1 AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE') AND UPPER(@sqlcommand2) LIKE '%WITH%'
  1960. SET @sqlcommand2 = @sqlcommand2 + N' ON PARTITIONS(' + CONVERT(NVARCHAR(10), @partitionNumber) + N');'
  1961. ELSE IF @partitionCount > 1 AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE') AND UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  1962. SET @sqlcommand2 = @sqlcommand2 + N' WITH RESAMPLE ON PARTITIONS(' + CONVERT(NVARCHAR(10), @partitionNumber) + N')'
  1963. IF @stats_norecompute = 1 AND UPPER(@sqlcommand2) LIKE '%WITH%'
  1964. SET @sqlcommand2 = @sqlcommand2 + N' ,NORECOMPUTE'
  1965. ELSE IF @stats_norecompute = 1 AND @sqlcommand2 NOT LIKE '%WITH%'
  1966. SET @sqlcommand2 = @sqlcommand2 + N' WITH NORECOMPUTE'
  1967. /* For list of incremental stats unsupported scenarios check https://msdn.microsoft.com/en-us/library/ms187348.aspx */
  1968. IF @partitionCount > 1 AND @statsIncremental = 1 AND @has_filter = 0
  1969. BEGIN
  1970. IF UPPER(@sqlcommand2) LIKE '%WITH%'
  1971. SET @sqlcommand2 = @sqlcommand2 + N' ,INCREMENTAL = ON'
  1972. ELSE IF UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  1973. SET @sqlcommand2 = @sqlcommand2 + N'WITH INCREMENTAL = ON'
  1974. END
  1975. ELSE IF @statsIncremental = 0
  1976. BEGIN
  1977. IF UPPER(@sqlcommand2) LIKE '%WITH%'
  1978. SET @sqlcommand2 = @sqlcommand2 + N', INCREMENTAL = OFF'
  1979. ELSE IF UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  1980. SET @sqlcommand2 = @sqlcommand2 + N'WITH INCREMENTAL = OFF'
  1981. END
  1982. SET @sqlcommand2 = @sqlcommand2 + N';'
  1983. END
  1984. ELSE
  1985. BEGIN
  1986. SET @sqlcommand2 = NULL
  1987. END
  1988. /* Are we executing the SQL? If so, do it */
  1989. IF @Exec_Print = 1 AND @sqlcommand2 IS NOT NULL
  1990. BEGIN
  1991. SET @debugMessage = ' ' + @sqlcommand2;
  1992. /* Print the commands we'll be executing, if specified to do so */
  1993. IF (@printCmds = 1 OR @debugMode = 1)
  1994. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1995. /* Get the time for logging purposes */
  1996. SET @dateTimeStart = GETDATE();
  1997. /* Log actions */
  1998. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Stats_log (dbID, dbName, objectID, objectName, statsID, statsName, [partitionNumber], [rows], rows_sampled, modification_counter, [no_recompute], dateTimeStart, sqlStatement)
  1999. SELECT @dbID, @dbName, @objectID, @objectName, @statsID, @statsName, @partitionNumber, @rows, @rows_sampled, @rowmodctr, @stats_norecompute, @dateTimeStart, @sqlcommand2;
  2000. SET @statsUpdate_id = SCOPE_IDENTITY();
  2001. /* Wrap execution attempt in a TRY/CATCH and log any errors that occur */
  2002. IF @operationFlag = 0
  2003. BEGIN
  2004. BEGIN TRY
  2005. /* Execute update! */
  2006. EXECUTE sp_executesql @sqlcommand2;
  2007. SET @dateTimeEnd = GETDATE();
  2008. SET @sqlcommand2 = NULL
  2009. /* Update log with completion time */
  2010. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2011. SET dateTimeEnd = @dateTimeEnd, durationSeconds = DATEDIFF(second, @dateTimeStart, @dateTimeEnd)
  2012. WHERE statsUpdate_id = @statsUpdate_id AND partitionNumber = @partitionNumber AND dateTimeEnd IS NULL;
  2013. /* Update working table */
  2014. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2015. SET updateDate = GETDATE(), printStatus = 1
  2016. WHERE dbID = @dbID AND objectID = @objectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2017. END TRY
  2018. BEGIN CATCH
  2019. /* Update log with error message */
  2020. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2021. SET dateTimeEnd = GETDATE(), durationSeconds = -1, errorMessage = 'Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing this command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  2022. WHERE statsUpdate_id = @statsUpdate_id AND partitionNumber = @partitionNumber AND dateTimeEnd IS NULL;
  2023. /* Update working table */
  2024. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2025. SET updateDate = GETDATE(), printStatus = 1
  2026. WHERE dbID = @dbID AND objectID = @objectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2027. IF @debugMode = 1
  2028. BEGIN
  2029. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing this command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  2030. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2031. --RAISERROR(' An error has occurred executing this command. Please review the tbl_AdaptiveIndexDefrag_Stats_log table for details.', 0, 42) WITH NOWAIT;
  2032. END
  2033. END CATCH
  2034. END
  2035. END
  2036. ELSE IF @Exec_Print = 1 AND @sqlcommand2 IS NULL
  2037. BEGIN
  2038. IF @debugMode = 1
  2039. BEGIN
  2040. SELECT @debugMessage = ' No need to update statistic ' + @statsName + ' on table or view ' + @objectName + ' of DB ' + @dbName + CASE WHEN @stats_isincremental = 1 THEN ', on partition ' + CONVERT(NVARCHAR(10), @partitionNumber) ELSE '' END + '...';
  2041. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2042. END
  2043. IF @printCmds = 1 AND @debugMode = 0
  2044. BEGIN
  2045. SELECT @debugMessage = ' -- No need to update statistic ' + @statsName + ' on table or view ' + @objectName + ' of DB ' + @dbName + CASE WHEN @stats_isincremental = 1 THEN ', on partition ' + CONVERT(NVARCHAR(10), @partitionNumber) ELSE '' END + '...';
  2046. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2047. END
  2048. /* Update working table */
  2049. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2050. SET updateDate = GETDATE(), printStatus = 1
  2051. WHERE dbID = @dbID AND objectID = @objectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2052. END
  2053. ELSE IF @Exec_Print = 0
  2054. BEGIN
  2055. IF @debugMode = 1 AND @sqlcommand2 IS NULL
  2056. BEGIN
  2057. SET @debugMessage = ' No need to update statistic ' + @statsName + ' on table or view ' + @objectName + ' of DB ' + @dbName + CASE WHEN @stats_isincremental = 1 THEN ', on partition ' + CONVERT(NVARCHAR(10), @partitionNumber) ELSE '' END + '...';
  2058. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2059. END
  2060. /* Print the commands we're executing if specified to do so */
  2061. IF (@printCmds = 1 OR @debugMode = 1) AND @sqlcommand2 IS NOT NULL
  2062. BEGIN
  2063. SET @debugMessage = ' ' + @sqlcommand2;
  2064. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2065. END
  2066. IF @printCmds = 1 AND @debugMode = 0 AND @sqlcommand2 IS NULL
  2067. BEGIN
  2068. SET @debugMessage = ' -- No need to update statistic ' + @statsName + ' on table or view ' + @objectName + ' of DB ' + @dbName + CASE WHEN @stats_isincremental = 1 THEN ', on partition ' + CONVERT(NVARCHAR(10), @partitionNumber) ELSE '' END + '...';
  2069. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2070. END
  2071. /* Update working table */
  2072. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2073. SET printStatus = 1
  2074. WHERE dbID = @dbID AND objectID = @objectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2075. END
  2076. END
  2077. END;
  2078. /* Handling all the other statistics not covered before*/
  2079. IF @updateStats = 1 -- When reorganizing, update stats afterwards
  2080. AND @updateStatsWhere = 0 -- @updateStatsWhere = 0 then table-wide statistics;
  2081. AND (SELECT COUNT(*) FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss WHERE ((@Exec_Print = 1 AND idss.updateDate IS NULL) OR (@Exec_Print = 0 AND idss.updateDate IS NULL AND idss.printStatus = 0)) AND NOT EXISTS (SELECT TOP 1 objectID FROM dbo.tbl_AdaptiveIndexDefrag_Working ids WHERE ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0)) > 0 -- If any unhandled statistics remain
  2082. BEGIN
  2083. IF @debugMode = 1
  2084. RAISERROR(' Updating all other unhandled statistics using finer thresholds (if any)...', 0, 42) WITH NOWAIT;
  2085. WHILE (SELECT COUNT(*) FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss WHERE ((@Exec_Print = 1 AND idss.updateDate IS NULL) OR (@Exec_Print = 0 AND idss.updateDate IS NULL AND idss.printStatus = 0)) AND NOT EXISTS (SELECT TOP 1 objectID FROM dbo.tbl_AdaptiveIndexDefrag_Working ids WHERE ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0)) > 0
  2086. BEGIN
  2087. /* Check to see if we need to exit loop because of our time limit */
  2088. IF ISNULL(@endDateTime, GETDATE()) < GETDATE()
  2089. RAISERROR('Time limit has been exceeded for this maintenance window!', 16, 42) WITH NOWAIT;
  2090. IF @debugMode = 1
  2091. RAISERROR(' Selecting a statistic to update...', 0, 42) WITH NOWAIT;
  2092. /* Select the stat */
  2093. IF @Exec_Print = 1
  2094. BEGIN
  2095. SELECT TOP 1 @statsID = idss.statsID, @dbID = idss.dbID, @statsObjectID = idss.objectID, @dbName = idss.dbName, @statsobjectName = idss.objectName, @statsschemaName = idss.schemaName, @partitionNumber = idss.partitionNumber
  2096. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss
  2097. WHERE idss.updateDate IS NULL AND NOT EXISTS (SELECT TOP 1 objectID FROM dbo.tbl_AdaptiveIndexDefrag_Working ids WHERE ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0)
  2098. END
  2099. ELSE IF @Exec_Print = 0
  2100. BEGIN
  2101. SELECT TOP 1 @statsID = idss.statsID, @dbID = idss.dbID, @statsObjectID = idss.objectID, @dbName = idss.dbName, @statsobjectName = idss.objectName, @statsschemaName = idss.schemaName, @partitionNumber = idss.partitionNumber
  2102. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss
  2103. WHERE idss.updateDate IS NULL AND idss.printStatus = 0 AND NOT EXISTS (SELECT TOP 1 objectID FROM dbo.tbl_AdaptiveIndexDefrag_Working ids WHERE ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID AND idss.statsName = ids.indexName AND idss.updateDate IS NULL AND ids.exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0)
  2104. END
  2105. /* Get stat associated table record count */
  2106. BEGIN TRY
  2107. SELECT @getStatSQL = N'USE ' + @dbName + '; SELECT TOP 1 @record_count_Out = p.[rows] FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss INNER JOIN sys.partitions AS p ON idss.objectID = p.[object_id] AND idss.partitionNumber = p.partition_number WHERE idss.updateDate IS NULL ' + CASE WHEN @Exec_Print = 0 THEN 'AND idss.printStatus = 0 ' ELSE '' END + ' AND idss.statsID = @statsID_In AND idss.dbID = @dbID_In AND idss.objectID = @statsObjectID_In'
  2108. SET @getStatSQL_Param = N'@statsID_In int, @dbID_In int, @statsObjectID_In int, @record_count_Out bigint OUTPUT'
  2109. EXECUTE sp_executesql @getStatSQL, @getStatSQL_Param, @statsID_In = @statsID, @dbID_In = @dbID, @statsObjectID_In = @statsObjectID, @record_count_Out = @record_count OUTPUT;
  2110. END TRY
  2111. BEGIN CATCH
  2112. IF @debugMode = 1
  2113. BEGIN
  2114. SET @debugMessage = ' Error ' + CONVERT(VARCHAR(20),ERROR_NUMBER()) + ' has occurred while getting stat associated table row count. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS VARCHAR(10)) + ')'
  2115. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2116. END
  2117. END CATCH
  2118. IF @debugMode = 1
  2119. RAISERROR(' Getting information on selected statistic...', 0, 42) WITH NOWAIT;
  2120. /* Get object name and auto update setting */
  2121. SELECT TOP 1 @statsName = statsName, @stats_norecompute = [no_recompute], @stats_isincremental = [is_incremental]
  2122. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2123. WHERE objectID = @statsObjectID AND statsID = @statsID AND [dbID] = @dbID AND partitionNumber = @partitionNumber;
  2124. IF @debugMode = 1
  2125. BEGIN
  2126. SET @debugMessage = ' Determining modification row counter for statistic ' + @statsName + ' on table or view ' + @statsobjectName + ' of DB ' + @dbName + '...';
  2127. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2128. END
  2129. /* Determine modification row counter to ascertain if update stats is required */
  2130. IF ((@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver >= 13) AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE')
  2131. BEGIN
  2132. IF @debugMode = 1
  2133. RAISERROR(' Using sys.dm_db_incremental_stats_properties DMF...', 0, 42) WITH NOWAIT;
  2134. SELECT @rowmodctrSQL = N'USE ' + @dbName + '; SELECT @rowmodctr_Out = ISNULL(modification_counter,0), @rows_Out = ISNULL(rows,0), @rows_sampled_Out = ISNULL(rows_sampled,0) FROM sys.dm_db_incremental_stats_properties(' + CAST(@statsObjectID AS NVARCHAR(10)) + ',' + CAST(@statsID AS NVARCHAR(10)) + ') WHERE partition_number = @partitionNumber_In;'
  2135. END
  2136. ELSE IF (@sqlmajorver = 12 AND @sqlbuild < 5000) AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE')
  2137. BEGIN
  2138. IF @debugMode = 1
  2139. RAISERROR(' Using sys.dm_db_stats_properties_internal DMF...', 0, 42) WITH NOWAIT;
  2140. SELECT @rowmodctrSQL = N'USE ' + @dbName + '; SELECT @rowmodctr_Out = ISNULL(modification_counter,0), @rows_Out = ISNULL(rows,0), @rows_sampled_Out = ISNULL(rows_sampled,0) FROM sys.dm_db_stats_properties_internal(' + CAST(@statsObjectID AS NVARCHAR(10)) + ',' + CAST(@statsID AS NVARCHAR(10)) + ') WHERE partition_number = @partitionNumber_In;'
  2141. END
  2142. ELSE IF ((@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4000) OR (@sqlmajorver = 11 AND @sqlbuild >= 3000) OR @sqlmajorver >= 12) AND (@stats_isincremental = 0 OR UPPER(@statsSample) = 'FULLSCAN')
  2143. BEGIN
  2144. IF @debugMode = 1
  2145. RAISERROR(' Using sys.dm_db_stats_properties DMF...', 0, 42) WITH NOWAIT;
  2146. SELECT @rowmodctrSQL = N'USE ' + @dbName + '; SELECT @rowmodctr_Out = ISNULL(modification_counter,0), @rows_Out = ISNULL(rows,0), @rows_sampled_Out = ISNULL(rows_sampled,0) FROM sys.dm_db_stats_properties(' + CAST(@statsObjectID AS NVARCHAR(10)) + ',' + CAST(@statsID AS NVARCHAR(10)) + ');'
  2147. END
  2148. ELSE
  2149. BEGIN
  2150. IF @debugMode = 1
  2151. RAISERROR(' Using sys.sysindexes...', 0, 42) WITH NOWAIT;
  2152. SELECT @rowmodctrSQL = N'USE ' + @dbName + '; SELECT @rowmodctr_Out = SUM(ISNULL(rowmodctr,0)), @rows_Out = ISNULL(rowcnt,0), @rows_sampled_Out = -1 FROM sys.sysindexes WHERE id = ' + CAST(@statsObjectID AS NVARCHAR(10)) + ' AND indid = ' + CAST(@statsID AS NVARCHAR(10)) + ' AND rowmodctr > 0;'
  2153. END
  2154. SET @rowmodctrSQL_Param = N'@partitionNumber_In smallint, @rowmodctr_Out bigint OUTPUT, @rows_Out bigint OUTPUT, @rows_sampled_Out bigint OUTPUT'
  2155. BEGIN TRY
  2156. EXECUTE sp_executesql @rowmodctrSQL, @rowmodctrSQL_Param, @partitionNumber_In = @partitionNumber, @rowmodctr_Out = @rowmodctr OUTPUT, @rows_Out = @rows OUTPUT, @rows_sampled_Out = @rows_sampled OUTPUT;
  2157. SET @rowmodctr = (SELECT ISNULL(@rowmodctr, 0));
  2158. END TRY
  2159. BEGIN CATCH
  2160. IF @debugMode = 1
  2161. BEGIN
  2162. SET @debugMessage = ' Error ' + CONVERT(VARCHAR(20),ERROR_NUMBER()) + ' has occurred while determining row modification counter. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS VARCHAR(10)) + ')'
  2163. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2164. END
  2165. END CATCH
  2166. IF @rows IS NOT NULL AND @rows > 0
  2167. SET @record_count = @rows
  2168. IF @debugMode = 1
  2169. BEGIN
  2170. SELECT @debugMessage = ' Found a row modification counter of ' + CONVERT(NVARCHAR(10), @rowmodctr) + ' and ' + CONVERT(NVARCHAR(10), CASE WHEN @rows IS NOT NULL AND @rows < @record_count THEN @rows ELSE @record_count END) + ' rows' + CASE WHEN @stats_isincremental = 1 THEN ' on partition ' + CONVERT(NVARCHAR(10), @partitionNumber) ELSE '' END + '...';
  2171. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2172. --select @debugMessage
  2173. END
  2174. /* We will update statistics if they have changed since last update with customized, more finer values, just like when TF2371 is enabled for Auto-Update.
  2175. Default rules for auto update stats are:
  2176. If the cardinality for a table is greater than 6, but less than or equal to 500, update status every 500 modifications.
  2177. If the cardinality for a table is greater than 500, update statistics when (500 + 20 percent of the table) changes have occurred.
  2178. */
  2179. IF (
  2180. (@record_count BETWEEN 6 AND 500 AND @rowmodctr >= 500) OR -- like the default
  2181. (@record_count BETWEEN 501 AND 10000 AND (@rowmodctr >= (@record_count*20)/100 + 500 OR @rowmodctr >= SQRT(@record_count*1000))) OR -- 500 + 20 percent or simulate TF 2371
  2182. (@record_count BETWEEN 10001 AND 100000 AND (@rowmodctr >= (@record_count*15)/100 + 500 OR @rowmodctr >= SQRT(@record_count*1000))) OR -- 500 + 15 percent or simulate TF 2371
  2183. (@record_count BETWEEN 100001 AND 1000000 AND (@rowmodctr >= (@record_count*10)/100 + 500 OR @rowmodctr >= SQRT(@record_count*1000))) OR -- 500 + 10 percent or simulate TF 2371
  2184. (@record_count >= 1000001 AND (@rowmodctr >= (@record_count*5)/100 + 500 OR @rowmodctr >= SQRT(@record_count*1000))) -- 500 + 5 percent or simulate TF 2371
  2185. )
  2186. BEGIN
  2187. SET @sqlcommand2 = N'UPDATE STATISTICS ' + @dbName + N'.' + @statsschemaName + N'.' + @statsobjectName + N' (' + @statsName + N')'
  2188. IF UPPER(@statsSample) = 'FULLSCAN' AND (@partitionNumber = 1 OR @partitionNumber = @maxpartitionNumber)
  2189. SET @sqlcommand2 = @sqlcommand2 + N' WITH FULLSCAN'
  2190. ELSE IF UPPER(@statsSample) = 'RESAMPLE'
  2191. SET @sqlcommand2 = @sqlcommand2 + N' WITH RESAMPLE'
  2192. IF @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE') AND UPPER(@sqlcommand2) LIKE '%WITH%'
  2193. SET @sqlcommand2 = @sqlcommand2 + N' ON PARTITIONS(' + CONVERT(NVARCHAR(10), @partitionNumber) + N');'
  2194. ELSE IF @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE') AND UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  2195. SET @sqlcommand2 = @sqlcommand2 + N' WITH RESAMPLE ON PARTITIONS(' + CONVERT(NVARCHAR(10), @partitionNumber) + N')'
  2196. IF @stats_norecompute = 1 AND UPPER(@sqlcommand2) LIKE '%WITH%'
  2197. SET @sqlcommand2 = @sqlcommand2 + N' ,NORECOMPUTE'
  2198. ELSE IF @stats_norecompute = 1 AND UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  2199. SET @sqlcommand2 = @sqlcommand2 + N' WITH NORECOMPUTE'
  2200. /* For list of incremental stats unsupported scenarios check https://msdn.microsoft.com/en-us/library/ms187348.aspx */
  2201. IF @partitionCount > 1 AND @statsIncremental = 1 AND @has_filter = 0
  2202. BEGIN
  2203. IF UPPER(@sqlcommand2) LIKE '%WITH%'
  2204. SET @sqlcommand2 = @sqlcommand2 + N' ,INCREMENTAL = ON'
  2205. ELSE IF UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  2206. SET @sqlcommand2 = @sqlcommand2 + N'WITH INCREMENTAL = ON'
  2207. END
  2208. ELSE IF @statsIncremental = 0
  2209. BEGIN
  2210. IF UPPER(@sqlcommand2) LIKE '%WITH%'
  2211. SET @sqlcommand2 = @sqlcommand2 + N', INCREMENTAL = OFF'
  2212. ELSE IF UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  2213. SET @sqlcommand2 = @sqlcommand2 + N'WITH INCREMENTAL = OFF'
  2214. END
  2215. SET @sqlcommand2 = @sqlcommand2 + N';'
  2216. END
  2217. ELSE
  2218. BEGIN
  2219. SET @sqlcommand2 = NULL
  2220. END;
  2221. /* Are we executing the SQL? If so, do it */
  2222. IF @Exec_Print = 1 AND @sqlcommand2 IS NOT NULL
  2223. BEGIN
  2224. SET @debugMessage = ' ' + @sqlcommand2;
  2225. /* Print the commands we're executing if specified to do so */
  2226. IF (@printCmds = 1 OR @debugMode = 1)
  2227. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2228. /* Get the time for logging purposes */
  2229. SET @dateTimeStart = GETDATE();
  2230. /* Log actions */
  2231. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Stats_log (dbID, dbName, objectID, objectName, statsID, statsName, [partitionNumber], [rows], rows_sampled, modification_counter, [no_recompute], dateTimeStart, sqlStatement)
  2232. SELECT @dbID, @dbName, @objectID, @objectName, @statsID, @statsName, @partitionNumber, @rows, @rows_sampled, @rowmodctr, @stats_norecompute, @dateTimeStart, @sqlcommand2;
  2233. SET @statsUpdate_id = SCOPE_IDENTITY();
  2234. /* Wrap execution attempt in a TRY/CATCH and log any errors that occur */
  2235. BEGIN TRY
  2236. /* Execute update! */
  2237. EXECUTE sp_executesql @sqlcommand2;
  2238. SET @dateTimeEnd = GETDATE();
  2239. SET @sqlcommand2 = NULL
  2240. /* Update log with completion time */
  2241. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2242. SET dateTimeEnd = @dateTimeEnd, durationSeconds = DATEDIFF(second, @dateTimeStart, @dateTimeEnd)
  2243. WHERE statsUpdate_id = @statsUpdate_id AND partitionNumber = @partitionNumber AND dateTimeEnd IS NULL;
  2244. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2245. SET updateDate = GETDATE(), printStatus = 1
  2246. WHERE dbID = @dbID AND objectID = @statsObjectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2247. END TRY
  2248. BEGIN CATCH
  2249. /* Update log with error message */
  2250. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2251. SET dateTimeEnd = GETDATE(), durationSeconds = -1, errorMessage = 'Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing this command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  2252. WHERE statsUpdate_id = @statsUpdate_id AND partitionNumber = @partitionNumber AND dateTimeEnd IS NULL;
  2253. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2254. SET updateDate = GETDATE(), printStatus = 1
  2255. WHERE dbID = @dbID AND objectID = @statsObjectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2256. IF @debugMode = 1
  2257. BEGIN
  2258. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing this command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  2259. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2260. --RAISERROR(' An error has occurred executing this command. Please review the tbl_AdaptiveIndexDefrag_Stats_log table for details.', 0, 42) WITH NOWAIT;
  2261. END
  2262. END CATCH
  2263. END
  2264. ELSE IF @Exec_Print = 1 AND @sqlcommand2 IS NULL
  2265. BEGIN
  2266. IF @debugMode = 1
  2267. BEGIN
  2268. SET @debugMessage = ' No need to update statistic ' + @statsName + ' on DB ' + @dbName + ' and object ' + @statsobjectName + CASE WHEN @stats_isincremental = 1 THEN ', on partition ' + CONVERT(NVARCHAR(10), @partitionNumber) ELSE '' END + '...';
  2269. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2270. END
  2271. IF @printCmds = 1 AND @debugMode = 0
  2272. BEGIN
  2273. SET @debugMessage = ' -- No need to update statistic ' + @statsName + ' on DB ' + @dbName + ' and object ' + @statsobjectName + CASE WHEN @stats_isincremental = 1 THEN ', on partition ' + CONVERT(NVARCHAR(10), @partitionNumber) ELSE '' END + '...';
  2274. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2275. END
  2276. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2277. SET updateDate = GETDATE(), printStatus = 1
  2278. WHERE dbID = @dbID AND objectID = @statsObjectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2279. END
  2280. ELSE IF @Exec_Print = 0
  2281. BEGIN
  2282. IF @debugMode = 1 AND @sqlcommand2 IS NULL
  2283. BEGIN
  2284. SET @debugMessage = ' No need to update statistic ' + @statsName + ' on DB ' + @dbName + ' and object ' + @statsobjectName + CASE WHEN @stats_isincremental = 1 THEN ', on partition ' + CONVERT(NVARCHAR(10), @partitionNumber) ELSE '' END + '...';
  2285. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2286. END
  2287. /* Print the commands we're executing if specified to do so */
  2288. IF (@printCmds = 1 OR @debugMode = 1) AND @sqlcommand2 IS NOT NULL
  2289. BEGIN
  2290. SET @debugMessage = ' ' + @sqlcommand2;
  2291. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2292. END
  2293. IF @printCmds = 1 AND @debugMode = 0 AND @sqlcommand2 IS NULL
  2294. BEGIN
  2295. SET @debugMessage = ' -- No need to update statistic ' + @statsName + ' on DB ' + @dbName + ' and object ' + @statsobjectName + CASE WHEN @stats_isincremental = 1 THEN ', on partition ' + CONVERT(NVARCHAR(10), @partitionNumber) ELSE '' END + '...';
  2296. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2297. END
  2298. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2299. SET printStatus = 1
  2300. WHERE dbID = @dbID AND objectID = @statsObjectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2301. END
  2302. END
  2303. IF (@printCmds = 1 OR @debugMode = 1)
  2304. PRINT ' No remaining statistics to update...';
  2305. END
  2306. ELSE
  2307. BEGIN
  2308. IF (@printCmds = 1 OR @debugMode = 1)
  2309. PRINT ' No remaining statistics to update...';
  2310. END
  2311. /* Output results? */
  2312. IF @outputResults = 1 AND @Exec_Print = 1
  2313. BEGIN
  2314. IF (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Working WHERE defragDate >= @startDateTime) > 0
  2315. OR (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Stats_Working WHERE updateDate >= @startDateTime) > 0
  2316. BEGIN
  2317. IF @debugMode = 1
  2318. RAISERROR(' Displaying a summary of our actions...', 0, 42) WITH NOWAIT;
  2319. SELECT [dbName], objectName, indexName, partitionNumber, CONVERT(decimal(9,2),fragmentation) AS fragmentation, page_count, fill_factor, range_scan_count, defragDate
  2320. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2321. WHERE defragDate >= @startDateTime
  2322. ORDER BY defragDate;
  2323. SELECT [dbName], [statsName], partitionNumber, [no_recompute], [is_incremental], updateDate
  2324. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2325. WHERE updateDate >= @startDateTime
  2326. ORDER BY updateDate;
  2327. IF @debugMode = 1 AND (SELECT COUNT(*) FROM dbo.tbl_AdaptiveIndexDefrag_log WHERE errorMessage IS NOT NULL AND dateTimeStart >= @startDateTime) > 0
  2328. BEGIN
  2329. RAISERROR('Displaying a summary of all errors...', 0, 42) WITH NOWAIT;
  2330. SELECT dbName, objectName, indexName, partitionNumber, dateTimeStart, dateTimeEnd, sqlStatement, errorMessage
  2331. FROM dbo.tbl_AdaptiveIndexDefrag_log
  2332. WHERE errorMessage IS NOT NULL AND dateTimeStart >= @startDateTime
  2333. ORDER BY dateTimeStart;
  2334. END
  2335. IF @debugMode = 1
  2336. RAISERROR(' Displaying some statistical information about this defragmentation run...', 0, 42) WITH NOWAIT;
  2337. SELECT TOP 10 'Longest time' AS Comment, dbName, objectName, indexName, partitionNumber, dateTimeStart, dateTimeEnd, durationSeconds
  2338. FROM dbo.tbl_AdaptiveIndexDefrag_log
  2339. WHERE dateTimeStart >= @startDateTime
  2340. ORDER BY durationSeconds DESC;
  2341. END
  2342. END;
  2343. END TRY
  2344. BEGIN CATCH
  2345. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  2346. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2347. END CATCH;
  2348. /* Reset printStatus */
  2349. IF @debugMode = 1
  2350. RAISERROR(' Reseting working table statuses.', 0, 42) WITH NOWAIT;
  2351. UPDATE dbo.tbl_AdaptiveIndexDefrag_Working
  2352. SET printStatus = 0;
  2353. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2354. SET printStatus = 0;
  2355. /* Drop all temp tables */
  2356. IF @debugMode = 1
  2357. RAISERROR(' Droping temporary objects', 0, 42) WITH NOWAIT;
  2358. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragDatabaseList'))
  2359. DROP TABLE #tblIndexDefragDatabaseList;
  2360. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragmaxPartitionList'))
  2361. DROP TABLE #tblIndexDefragmaxPartitionList;
  2362. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragScanWorking'))
  2363. DROP TABLE #tblIndexDefragScanWorking;
  2364. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexFindInDatabaseList'))
  2365. DROP TABLE #tblIndexFindInDatabaseList;
  2366. IF @debugMode = 1
  2367. RAISERROR('All done!', 0, 42) WITH NOWAIT;
  2368. IF @Exec_Print = 0
  2369. BEGIN
  2370. IF @ignoreDropObj = 0
  2371. BEGIN
  2372. IF (SELECT COUNT([errorMessage]) FROM dbo.vw_LastRun_Log) > 0 AND @ignoreDropObj = 0
  2373. BEGIN
  2374. RAISERROR('Defrag job found execution errors! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 16, 42) WITH NOWAIT;
  2375. RETURN -1
  2376. END
  2377. ELSE
  2378. BEGIN
  2379. RETURN 0
  2380. END
  2381. END
  2382. ELSE
  2383. BEGIN
  2384. IF (SELECT COUNT([errorMessage]) FROM dbo.vw_LastRun_Log WHERE [errorMessage] NOT LIKE 'Table%does not exist%') > 0
  2385. BEGIN
  2386. RAISERROR('Defrag job found execution errors! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 16, 42) WITH NOWAIT;
  2387. RETURN -1
  2388. END
  2389. ELSE
  2390. BEGIN
  2391. RETURN 0
  2392. END
  2393. END
  2394. END
  2395. END
  2396. GO
  2397. --EXEC sys.sp_MS_marksystemobject 'usp_AdaptiveIndexDefrag'
  2398. --GO
  2399. PRINT 'Procedure usp_AdaptiveIndexDefrag created';
  2400. GO
  2401. ------------------------------------------------------------------------------------------------------------------------------
  2402. CREATE VIEW vw_ErrLst30Days
  2403. AS
  2404. SELECT TOP 100 PERCENT dbName, objectName, indexName, partitionNumber, NULL AS statsName, dateTimeStart, dateTimeEnd, sqlStatement, errorMessage
  2405. FROM dbo.tbl_AdaptiveIndexDefrag_log
  2406. WHERE errorMessage IS NOT NULL AND dateTimeStart >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2407. UNION ALL
  2408. SELECT TOP 100 PERCENT dbName, objectName, NULL AS indexName, NULL AS partitionNumber, statsName, dateTimeStart, dateTimeEnd, sqlStatement, errorMessage
  2409. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2410. WHERE errorMessage IS NOT NULL AND dateTimeStart >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2411. ORDER BY dateTimeStart;
  2412. GO
  2413. CREATE VIEW vw_ErrLst24Hrs
  2414. AS
  2415. SELECT TOP 100 PERCENT dbName, objectName, indexName, partitionNumber, NULL AS statsName, dateTimeStart, dateTimeEnd, sqlStatement, errorMessage
  2416. FROM dbo.tbl_AdaptiveIndexDefrag_log
  2417. WHERE errorMessage IS NOT NULL AND dateTimeStart >= DATEADD(hh, -24, GETDATE())
  2418. UNION ALL
  2419. SELECT TOP 100 PERCENT dbName, objectName, NULL AS indexName, NULL AS partitionNumber, statsName, dateTimeStart, dateTimeEnd, sqlStatement, errorMessage
  2420. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2421. WHERE errorMessage IS NOT NULL AND dateTimeStart >= DATEADD(hh, -24, GETDATE())
  2422. ORDER BY dateTimeStart;
  2423. GO
  2424. CREATE VIEW vw_AvgTimeLst30Days
  2425. AS
  2426. SELECT TOP 100 PERCENT 'Longest time' AS Comment, dbName, objectName, indexName, partitionNumber, AVG(durationSeconds) AS Avg_durationSeconds
  2427. FROM dbo.tbl_AdaptiveIndexDefrag_log
  2428. WHERE dateTimeStart >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2429. GROUP BY dbName, objectName, indexName, partitionNumber
  2430. ORDER BY AVG(durationSeconds) DESC, dbName, objectName, indexName, partitionNumber;
  2431. GO
  2432. CREATE VIEW vw_AvgFragLst30Days
  2433. AS
  2434. SELECT TOP 100 PERCENT 'Most fragmented' AS Comment, dbName, objectName, indexName, partitionNumber, CONVERT(decimal(9,2),AVG(fragmentation)) AS Avg_fragmentation
  2435. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2436. WHERE defragDate >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2437. GROUP BY dbName, objectName, indexName, partitionNumber
  2438. ORDER BY AVG(fragmentation) DESC, dbName, objectName, indexName, partitionNumber;
  2439. GO
  2440. CREATE VIEW vw_AvgLargestLst30Days
  2441. AS
  2442. SELECT TOP 100 PERCENT 'Largest' AS Comment, dbName, objectName, indexName, partitionNumber, AVG(page_count)*8 AS Avg_size_KB, fill_factor
  2443. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2444. WHERE defragDate >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2445. GROUP BY dbName, objectName, indexName, partitionNumber, fill_factor
  2446. ORDER BY AVG(page_count) DESC, dbName, objectName, indexName, partitionNumber
  2447. GO
  2448. CREATE VIEW vw_AvgMostUsedLst30Days
  2449. AS
  2450. SELECT TOP 100 PERCENT 'Most used' AS Comment, dbName, objectName, indexName, partitionNumber, AVG(range_scan_count) AS Avg_range_scan_count
  2451. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2452. WHERE defragDate >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2453. GROUP BY dbName, objectName, indexName, partitionNumber
  2454. ORDER BY AVG(range_scan_count) DESC;
  2455. GO
  2456. CREATE VIEW vw_LastRun_Log
  2457. AS
  2458. SELECT TOP 100 percent [dbName]
  2459. ,[objectName]
  2460. ,[indexName]
  2461. , NULL AS [statsName]
  2462. ,[partitionNumber]
  2463. ,[fragmentation]
  2464. ,[page_count]
  2465. ,[range_scan_count]
  2466. ,[dateTimeStart]
  2467. ,[dateTimeEnd]
  2468. ,[durationSeconds]
  2469. ,CASE WHEN [sqlStatement] LIKE '%REORGANIZE%' THEN 'Reorg' ELSE 'Rebuild' END AS [Operation]
  2470. ,[errorMessage]
  2471. FROM dbo.tbl_AdaptiveIndexDefrag_log ixlog
  2472. CROSS APPLY (SELECT TOP 1 minIxDate = CASE WHEN defragDate IS NULL THEN CONVERT(DATETIME, CONVERT(NVARCHAR, scanDate, 112))
  2473. ELSE CONVERT(DATETIME, CONVERT(NVARCHAR, defragDate, 112)) END
  2474. FROM [dbo].[tbl_AdaptiveIndexDefrag_Working]
  2475. ORDER BY defragDate ASC, scanDate ASC) AS minDateIxCte
  2476. WHERE dateTimeStart >= minIxDate
  2477. UNION ALL
  2478. SELECT TOP 100 percent [dbName]
  2479. ,[objectName]
  2480. ,NULL AS [indexName]
  2481. ,[statsName]
  2482. ,NULL AS [partitionNumber]
  2483. ,NULL AS [fragmentation]
  2484. ,NULL AS [page_count]
  2485. ,NULL AS [range_scan_count]
  2486. ,[dateTimeStart]
  2487. ,[dateTimeEnd]
  2488. ,[durationSeconds]
  2489. ,'UpdateStats' AS [Operation]
  2490. ,[errorMessage]
  2491. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_log statlog
  2492. CROSS APPLY (SELECT TOP 1 minStatDate = CASE WHEN updateDate IS NULL THEN CONVERT(DATETIME, CONVERT(NVARCHAR, scanDate, 112))
  2493. ELSE CONVERT(DATETIME, CONVERT(NVARCHAR, updateDate, 112)) END
  2494. FROM [dbo].[tbl_AdaptiveIndexDefrag_Stats_Working]
  2495. ORDER BY updateDate ASC, scanDate ASC) AS minDateStatCte
  2496. WHERE dateTimeStart >= minStatDate
  2497. ORDER BY dateTimeEnd ASC
  2498. GO
  2499. PRINT 'Reporting views created';
  2500. GO
  2501. ------------------------------------------------------------------------------------------------------------------------------
  2502. CREATE PROCEDURE usp_AdaptiveIndexDefrag_PurgeLogs @daystokeep smallint = 90
  2503. AS
  2504. /*
  2505. usp_AdaptiveIndexDefrag_PurgeLogs.sql - [email protected] (http://blogs.msdn.com/b/blogdoezequiel/)
  2506. Purge log tables to avoid indefinite growth.
  2507. Default is data older than 90 days.
  2508. Change @daystokeep as you deem fit.
  2509. */
  2510. SET NOCOUNT ON;
  2511. SET DATEFORMAT ymd;
  2512. DELETE FROM dbo.tbl_AdaptiveIndexDefrag_log
  2513. WHERE dateTimeStart <= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -@daystokeep);
  2514. DELETE FROM dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2515. WHERE dateTimeStart <= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -@daystokeep);
  2516. GO
  2517. --EXEC sys.sp_MS_marksystemobject 'usp_AdaptiveIndexDefrag_PurgeLogs'
  2518. --GO
  2519. PRINT 'Procedure usp_AdaptiveIndexDefrag_PurgeLogs created (Default purge is 90 days old)';
  2520. GO
  2521. ------------------------------------------------------------------------------------------------------------------------------
  2522. CREATE PROCEDURE usp_AdaptiveIndexDefrag_CurrentExecStats @dbname NVARCHAR(255) = NULL
  2523. AS
  2524. /*
  2525. usp_AdaptiveIndexDefrag_CurrentExecStats.sql - [email protected] (http://blogs.msdn.com/b/blogdoezequiel/)
  2526. Allows monitoring of what has been done so far in the defrag loop.
  2527. Use @dbname to monitor a specific database
  2528. Example:
  2529. EXEC usp_AdaptiveIndexDefrag_CurrentExecStats @dbname = 'AdventureWorks2008R2'
  2530. */
  2531. SET NOCOUNT ON;
  2532. IF @dbname IS NULL
  2533. BEGIN
  2534. WITH cte1 ([Database_Name], Total_indexes) AS (SELECT [dbName], COUNT(indexID) AS Total_Indexes FROM dbo.tbl_AdaptiveIndexDefrag_Working GROUP BY [dbName]),
  2535. cte2 ([Database_Name], Defraged_Indexes) AS (SELECT [dbName], COUNT(indexID) AS Total_Indexes FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE defragDate IS NOT NULL OR printStatus = 1 GROUP BY [dbName]),
  2536. cte3 ([Database_Name], Total_statistics) AS (SELECT [dbName], COUNT(statsID) AS Total_statistics FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working GROUP BY [dbName]),
  2537. cte4 ([Database_Name], Updated_statistics) AS (SELECT [dbName], COUNT(statsID) AS Updated_statistics FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working WHERE updateDate IS NOT NULL OR printStatus = 1 GROUP BY [dbName])
  2538. SELECT cte1.[Database_Name], SUM(cte1.Total_indexes) AS Total_indexes, SUM(ISNULL(cte2.Defraged_Indexes, 0)) AS Defraged_Indexes,
  2539. SUM(cte3.Total_statistics) AS Total_statistics, SUM(ISNULL(cte4.Updated_statistics, 0)) AS Updated_statistics
  2540. FROM cte1 INNER JOIN cte3 ON cte1.Database_Name = cte3.Database_Name
  2541. LEFT JOIN cte2 ON cte1.Database_Name = cte2.Database_Name
  2542. LEFT JOIN cte4 ON cte1.Database_Name = cte4.Database_Name
  2543. GROUP BY cte1.[Database_Name];
  2544. SELECT 'Index' AS [Type], 'Done' AS [Result], dbName, objectName, indexName
  2545. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2546. WHERE defragDate IS NOT NULL OR printStatus = 1
  2547. UNION ALL
  2548. SELECT 'Index' AS [Type], 'To do' AS [Result], dbName, objectName, indexName
  2549. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2550. WHERE defragDate IS NULL AND printStatus = 0
  2551. ORDER BY 2, dbName, objectName, indexName;
  2552. SELECT 'Statistic' AS [Type], 'Done' AS [Result], dbName, objectName, statsName
  2553. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2554. WHERE updateDate IS NOT NULL OR printStatus = 1
  2555. UNION ALL
  2556. SELECT 'Statistic' AS [Type], 'To do' AS [Result], dbName, objectName, statsName
  2557. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2558. WHERE updateDate IS NULL AND printStatus = 0
  2559. ORDER BY 2, dbName, objectName, statsName;
  2560. END
  2561. ELSE
  2562. BEGIN
  2563. WITH cte1 ([Database_Name], Total_indexes) AS (SELECT [dbName], COUNT(indexID) AS Total_Indexes FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE [dbName] = QUOTENAME(@dbname) GROUP BY [dbName]),
  2564. cte2 ([Database_Name], Defraged_Indexes) AS (SELECT [dbName], COUNT(indexID) AS Total_Indexes FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE [dbName] = QUOTENAME(@dbname) AND defragDate IS NOT NULL OR printStatus = 1 GROUP BY [dbName]),
  2565. cte3 ([Database_Name], Total_statistics) AS (SELECT [dbName], COUNT(statsID) AS Total_statistics FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working WHERE [dbName] = QUOTENAME(@dbname) GROUP BY [dbName]),
  2566. cte4 ([Database_Name], Updated_statistics) AS (SELECT [dbName], COUNT(statsID) AS Updated_statistics FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working WHERE [dbName] = QUOTENAME(@dbname) AND updateDate IS NOT NULL OR printStatus = 1 GROUP BY [dbName])
  2567. SELECT cte1.[Database_Name], SUM(cte1.Total_indexes) AS Total_indexes, SUM(ISNULL(cte2.Defraged_Indexes, 0)) AS Defraged_Indexes,
  2568. SUM(cte3.Total_statistics) AS Total_statistics, SUM(ISNULL(cte4.Updated_statistics, 0)) AS Updated_statistics
  2569. FROM cte1 INNER JOIN cte3 ON cte1.Database_Name = cte3.Database_Name
  2570. LEFT JOIN cte2 ON cte1.Database_Name = cte2.Database_Name
  2571. LEFT JOIN cte4 ON cte1.Database_Name = cte4.Database_Name
  2572. GROUP BY cte1.[Database_Name];
  2573. SELECT 'Index' AS [Type], 'Done' AS [Result], dbName, objectName, indexName, partitionNumber
  2574. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2575. WHERE [dbName] = QUOTENAME(@dbname) AND (defragDate IS NOT NULL OR printStatus = 1)
  2576. UNION ALL
  2577. SELECT 'Index' AS [Type], 'To do' AS [Result], dbName, objectName, indexName, partitionNumber
  2578. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2579. WHERE [dbName] = QUOTENAME(@dbname) AND defragDate IS NULL AND printStatus = 0
  2580. ORDER BY 2, dbName, objectName, indexName;
  2581. SELECT 'Statistic' AS [Type], 'Done' AS [Result], dbName, objectName, statsName
  2582. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2583. WHERE [dbName] = QUOTENAME(@dbname) AND ([updateDate] IS NOT NULL OR printStatus = 1)
  2584. UNION ALL
  2585. SELECT 'Statistic' AS [Type], 'To do' AS [Result], dbName, objectName, statsName
  2586. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2587. WHERE [dbName] = QUOTENAME(@dbname) AND [updateDate] IS NULL AND printStatus = 0
  2588. ORDER BY 2, dbName, objectName, statsName;
  2589. END
  2590. GO
  2591. --EXEC sys.sp_MS_marksystemobject 'usp_AdaptiveIndexDefrag_CurrentExecStats'
  2592. --GO
  2593. PRINT 'Procedure usp_AdaptiveIndexDefrag_CurrentExecStats created (Use this to monitor defrag loop progress)';
  2594. GO
  2595. ------------------------------------------------------------------------------------------------------------------------------
  2596. CREATE PROCEDURE usp_AdaptiveIndexDefrag_Exceptions @exceptionMask_DB NVARCHAR(255) = NULL,
  2597. @exceptionMask_days NVARCHAR(27) = NULL,
  2598. @exceptionMask_tables NVARCHAR(500) = NULL,
  2599. @exceptionMask_indexes NVARCHAR(500) = NULL
  2600. AS
  2601. /*
  2602. usp_AdaptiveIndexDefrag_Exceptions.sql - [email protected] (http://blogs.msdn.com/b/blogdoezequiel/)
  2603. To insert info into the Exceptions table, use the following guidelines:
  2604. For @exceptionMask_DB, enter only one database name at a time.
  2605. For @exceptionMask_days, enter weekdays in short form, between commas.
  2606. * NOTE: Keep only the weekdays you DO NOT WANT to ALLOW defrag. *
  2607. Order is not mandatory, but weekday short names are important AS IS ('Sun,Mon,Tue,Wed,Thu,Fri,Sat').
  2608. * NOTE: If you WANT to NEVER allow defrag, set as NULL or leave blank *
  2609. For @exceptionMask_tables (optional) enter table names separated by commas ('table_name_1, table_name_2, table_name_3').
  2610. For @exceptionMask_indexes (optional) enter index names separated by commas ('index_name_1, index_name_2, index_name_3').
  2611. If you want to exclude all indexes in a given table, enter its name but don't add index names.
  2612. Example:
  2613. EXEC usp_AdaptiveIndexDefrag_Exceptions @exceptionMask_DB = 'AdventureWorks2008R2',
  2614. @exceptionMask_days = 'Mon,Wed',
  2615. @exceptionMask_tables = 'Employee',
  2616. @exceptionMask_indexes = 'AK_Employee_LoginID'
  2617. */
  2618. SET NOCOUNT ON;
  2619. IF @exceptionMask_DB IS NULL OR QUOTENAME(@exceptionMask_DB) NOT IN (SELECT QUOTENAME(name) FROM master.sys.sysdatabases)
  2620. RAISERROR('Syntax error. Please input a valid database name.', 15, 42) WITH NOWAIT;
  2621. IF @exceptionMask_days IS NOT NULL AND
  2622. (@exceptionMask_days NOT LIKE '___' AND
  2623. @exceptionMask_days NOT LIKE '___,___' AND
  2624. @exceptionMask_days NOT LIKE '___,___,___' AND
  2625. @exceptionMask_days NOT LIKE '___,___,___,___' AND
  2626. @exceptionMask_days NOT LIKE '___,___,___,___,___' AND
  2627. @exceptionMask_days NOT LIKE '___,___,___,___,___,___' AND
  2628. @exceptionMask_days NOT LIKE '___,___,___,___,___,___,___')
  2629. RAISERROR('Syntax error. Please input weekdays in short form, between commas, or leave NULL to always exclude.', 15, 42) WITH NOWAIT;
  2630. IF @exceptionMask_days LIKE '[___,___,___,___,___,___,___]'
  2631. RAISERROR('Warning. You chose to permanently exclude a table and/or index from being defragmented.', 0, 42) WITH NOWAIT;
  2632. IF @exceptionMask_tables IS NOT NULL AND @exceptionMask_tables LIKE '%.%'
  2633. RAISERROR('Syntax error. Please do not input schema with table name(s).', 15, 42) WITH NOWAIT;
  2634. DECLARE @debugMessage NVARCHAR(4000), @sqlcmd NVARCHAR(4000), @sqlmajorver int
  2635. /* Find sql server version */
  2636. SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  2637. BEGIN TRY
  2638. --Always exclude from defrag?
  2639. IF @exceptionMask_days IS NULL OR @exceptionMask_days = ''
  2640. BEGIN
  2641. SET @exceptionMask_days = 127
  2642. END
  2643. ELSE
  2644. BEGIN
  2645. -- 1=Sunday, 2=Monday, 4=Tuesday, 8=Wednesday, 16=Thursday, 32=Friday, 64=Saturday, 127=AllWeek
  2646. SET @exceptionMask_days = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@exceptionMask_days,',','+'),'Sun',1),'Mon',2),'Tue',4),'Wed',8),'Thu',16),'Fri',32),'Sat',64);
  2647. END
  2648. --Just get everything as it should be
  2649. SET @exceptionMask_tables = CHAR(39) + REPLACE(REPLACE(@exceptionMask_tables, ' ', ''),',', CHAR(39) + ',' + CHAR(39)) + CHAR(39)
  2650. SET @exceptionMask_indexes = CHAR(39) + REPLACE(REPLACE(@exceptionMask_indexes, ' ', ''),',', CHAR(39) + ',' + CHAR(39)) + CHAR(39)
  2651. --Get the exceptions insert command
  2652. IF @sqlmajorver > 9
  2653. BEGIN
  2654. SELECT @sqlcmd = 'MERGE dbo.tbl_AdaptiveIndexDefrag_Exceptions AS target
  2655. USING (SELECT ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB)) + ' AS dbID, si.[object_id] AS objectID, si.index_id AS indexID,
  2656. ''' + @exceptionMask_DB + ''' AS dbName, OBJECT_NAME(si.[object_id], ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB)) + ') AS objectName, si.[name] AS indexName,
  2657. ' + CONVERT(NVARCHAR,@exceptionMask_days) + ' AS exclusionMask
  2658. FROM ' + QUOTENAME(@exceptionMask_DB) + '.sys.indexes si
  2659. INNER JOIN ' + QUOTENAME(@exceptionMask_DB) + '.sys.objects so ON si.object_id = so.object_id
  2660. WHERE so.is_ms_shipped = 0 AND si.index_id > 0 AND si.is_hypothetical = 0
  2661. AND si.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + @exceptionMask_DB + '].sys.internal_tables AS sit)' -- Exclude Heaps, Internal and Hypothetical objects
  2662. + CASE WHEN @exceptionMask_tables IS NOT NULL THEN ' AND OBJECT_NAME(si.[object_id], ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB)) + ') IN (' + @exceptionMask_tables + ')' ELSE '' END
  2663. + CASE WHEN @exceptionMask_indexes IS NOT NULL THEN ' AND si.[name] IN (' + @exceptionMask_indexes + ')' ELSE '' END
  2664. + ') AS source
  2665. ON (target.[dbID] = source.[dbID] AND target.objectID = source.objectID AND target.indexID = source.indexID)
  2666. WHEN MATCHED THEN
  2667. UPDATE SET exclusionMask = source.exclusionMask
  2668. WHEN NOT MATCHED THEN
  2669. INSERT (dbID, objectID, indexID, dbName, objectName, indexName, exclusionMask)
  2670. VALUES (source.dbID, source.objectID, source.indexID, source.dbName, source.objectName, source.indexName, source.exclusionMask);';
  2671. END
  2672. ELSE
  2673. BEGIN
  2674. SELECT @sqlcmd = 'DELETE FROM dbo.tbl_AdaptiveIndexDefrag_Exceptions
  2675. WHERE dbID = ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB))
  2676. + CASE WHEN @exceptionMask_tables IS NOT NULL THEN ' AND [objectName] IN (' + @exceptionMask_tables + ')' ELSE '' END
  2677. + CASE WHEN @exceptionMask_indexes IS NOT NULL THEN ' AND [indexName] IN (' + @exceptionMask_indexes + ');' ELSE ';' END +
  2678. 'INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Exceptions
  2679. SELECT ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB)) + ' AS dbID, si.[object_id] AS objectID, si.index_id AS indexID,
  2680. ''' + @exceptionMask_DB + ''' AS dbName, OBJECT_NAME(si.[object_id], ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB)) + ') AS objectName, si.[name] AS indexName,
  2681. ' + CONVERT(NVARCHAR,@exceptionMask_days) + ' AS exclusionMask
  2682. FROM ' + QUOTENAME(@exceptionMask_DB) + '.sys.indexes si
  2683. INNER JOIN ' + QUOTENAME(@exceptionMask_DB) + '.sys.objects so ON si.object_id = so.object_id
  2684. WHERE so.is_ms_shipped = 0 AND si.index_id > 0 AND si.is_hypothetical = 0
  2685. AND si.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + @exceptionMask_DB + '].sys.internal_tables AS sit)' -- Exclude Heaps, Internal and Hypothetical objects
  2686. + CASE WHEN @exceptionMask_tables IS NOT NULL THEN ' AND OBJECT_NAME(si.[object_id], ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB)) + ') IN (' + @exceptionMask_tables + ')' ELSE '' END
  2687. + CASE WHEN @exceptionMask_indexes IS NOT NULL THEN ' AND si.[name] IN (' + @exceptionMask_indexes + ')' ELSE '' END;
  2688. END;
  2689. EXEC sp_executesql @sqlcmd;
  2690. END TRY
  2691. BEGIN CATCH
  2692. SET @debugMessage = 'Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ': ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')';
  2693. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2694. END CATCH;
  2695. GO
  2696. --EXEC sys.sp_MS_marksystemobject 'usp_AdaptiveIndexDefrag_Exceptions'
  2697. --GO
  2698. PRINT 'Procedure usp_AdaptiveIndexDefrag_Exceptions created (If the defrag should not be daily, use this to set on which days to disallow it. It can be on entire DBs, tables and/or indexes)';
  2699. PRINT 'All done!'
  2700. GO