1
0

usp_AdaptiveIndexDefrag.sql 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107
  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. v1.6.3.3 - 11/7/2016 - Rolled back previously reported issue with REORGANIZE and database names.
  536. v1.6.4 - 11/10/2016 - Fixed support for incremental statistics in SQL Server 2016 RTM.
  537. v1.6.4.1 - 11/16/2016 - Added support for incremental statistics in SQL Server 2016 SP1.
  538. IMPORTANT:
  539. Execute in the database context of where you created the log and working tables.
  540. ALL parameters are optional. If not specified, the defaults for each parameter are used.
  541. @Exec_Print 1 = execute the SQL code generated by this SP;
  542. 0 = print commands only
  543. @printCmds 1 = print commands to screen;
  544. 0 = do not print commands
  545. @outputResults 1 = output fragmentation information after run completes;
  546. 0 = do not output fragmentation information
  547. @debugMode 1 = display debug comments;
  548. 0 = do not display debug comments
  549. @timeLimit Limits how much time can be spent performing index defrags; expressed in minutes.
  550. NOTE: The time limit is checked BEFORE an index defrag begins, thus a long index defrag can exceed the time limit.
  551. @dbScope Specify specific database name to defrag; if not specified, all non-system databases plus msdb and model will be defragmented.
  552. @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.
  553. @defragOrderColumn Defines how to prioritize the order of defrags. Only used if @Exec_Print = 1.
  554. range_scan_count = count of range and table scans on the index; this is what can benefit the most from defragmentation;
  555. fragmentation = amount of fragmentation in the index;
  556. 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;
  557. @defragSortOrder The sort order of the ORDER BY clause on the above query on how to prioritize the order of defrags.
  558. ASC (ascending)
  559. DESC (descending) is the default.
  560. @forceRescan Action on index rescan. If = 0, a rescan will not occur until all indexes have been defragmented. This can span multiple executions.
  561. 1 = force a rescan
  562. 0 = use previous scan, if there are indexes left to defrag
  563. @defragDelay Time to wait between defrag commands; gives the server a breathe between runs
  564. @ixtypeOption NULL = all indexes will be defragmented;
  565. 1 = only Clustered indexes will be defragmented;
  566. 0 = only Non-Clustered indexes will be defragmented (includes XML and Spatial Indexes);
  567. @minFragmentation Defaults to 5%, will not defrag if fragmentation is less.
  568. Refer to http://msdn.microsoft.com/en-us/library/ms189858.aspx
  569. @rebuildThreshold Defaults to 30%. greater than 30% will result in rebuild instead of reorganize.
  570. Refer to http://msdn.microsoft.com/en-us/library/ms189858.aspx
  571. @rebuildThreshold_csDefaults to 10%. Greater than 10% will result in columnstore rebuild.
  572. Refer to https://msdn.microsoft.com/en-us/data/dn589807(v=sql.120)
  573. @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
  574. NOTE: The @minPageCount will restrict the indexes that are stored in tbl_AdaptiveIndexDefrag_Working table and can render other options inoperative.
  575. @maxPageCount Specifies the maximum number of pages that can exist in an index and still be considered for a defrag.
  576. Useful for scheduling small indexes during business hours and large indexes for non-business hours.
  577. NOTE: The @maxPageCount will restrict the indexes selective for defrag;
  578. @fillfactor 1 = original from when the index was created or last defragmented;
  579. 0 = default fill factor
  580. @scanMode Specifies which scan mode to use to determine fragmentation levels. Options are:
  581. LIMITED = the fastest mode and scans the smallest number of pages.
  582. For an index, only the parent-level pages of the B-tree (that is, the pages above the leaf level) are scanned.
  583. For a heap, only the associated PFS and IAM pages are examined; the data pages of the heap are not scanned.
  584. Recommended for most cases.
  585. SAMPLED = returns statistics based on a 1 percent sample of all the pages in the index or heap.
  586. If the index or heap has fewer than 10,000 pages, DETAILED mode is used instead of SAMPLED.
  587. DETAILED = scans all pages and returns all statistics. Can cause performance issues.
  588. @onlineRebuild 1 = online rebuild if possible; only in Enterprise Edition;
  589. 0 = offline rebuild
  590. @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.
  591. If a sort operation is not required, or if the sort can be performed in memory, SORT_IN_TEMPDB is ignored.
  592. Enabling this option can result in faster defrags and prevent database file size inflation. Just have monitor TempDB closely.
  593. 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
  594. 1 = perform sort operation in TempDB
  595. 0 = perform sort operation in the indexes database
  596. @maxDopRestriction Option to specify a processor limit for index rebuilds
  597. @updateStats 1 = updates stats when reorganizing;
  598. 0 = does not update stats when reorganizing
  599. @updateStatsWhere Update statistics within certain thresholds (http://support.microsoft.com/kb/195565/en-us)
  600. 1 = updates only index related stats;
  601. 0 = updates all stats in entire table
  602. @statsSample NULL = perform a sample scan on the target table or indexed view. The database engine automatically computes the required sample size;
  603. FULLSCAN = all rows in table or view should be read to gather the statistics;
  604. RESAMPLE = statistics will be gathered using an inherited sampling ratio for all existing statistics including indexes
  605. @ix_statsnorecompute 1 = STATISTICS_NORECOMPUTE on will disable the auto update statistics.
  606. If you are dealing with stats update with a custom job (or even with this code by updating statistics), you may use this option;
  607. 0 = default which is with STATISTICS_NORECOMPUTE off
  608. @statsIncremental When Incremental is ON, the statistics created are per partition statistics.
  609. 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)
  610. NULL = Keep server setting;
  611. 1 = Enable auto create statistics with Incremental
  612. 0 = Disable auto create statistics with Incremental
  613. @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.
  614. Typically, this is the partition that is currently being written to in a sliding-window scenario.
  615. Enabling this feature may reduce contention. This may not be applicable in other types of partitioning scenarios.
  616. Non-partitioned indexes are unaffected by this option. Only in Enterprise Edition.
  617. 1 = exclude right-most populated partition
  618. 0 = only right-most populated partition (remember to verify @minPageCount, if partition is smaller than @minPageCount, it won't be considered)
  619. NULL = do not exclude any partitions
  620. @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.
  621. Compacting this data can improve disk space use.
  622. Reorganizing a specified clustered index compacts all LOB columns that are contained in the clustered index.
  623. Reorganizing a non-clustered index compacts all LOB columns that are nonkey (included) columns in the index.
  624. 0 = compact LOBs when reorganizing (default behavior);
  625. 1 = does not compact LOBs when reorganizing
  626. @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,
  627. thus not showing a job as failed if the only errors present refer to dropped database objects.
  628. 0 = includes errors about objects that have been dropped since the defrag cycle began (default behavior);
  629. 1 = for error reporting purposes, ignores the fact that objects have been dropped since the defrag cycle began
  630. @disableNCIX If disk space is limited, it may be helpful to disable the non-clustered index before rebuilding it;
  631. When a non-clustered index is not disabled, the rebuild operation requires enough temporary disk space to store both the old and new index;
  632. 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;
  633. No additional space is required except for temporary disk space for sorting; this is typically 20 percent of the index size;
  634. Does not disable indexes on partitioned tables when defragging a subset of existing partitions;
  635. 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.
  636. 0 = does NOT disable non-clustered indexes prior to a rebuild (default behavior);
  637. 1 = disables non-clustered indexes prior to a rebuild (space saving feature)
  638. @offlinelocktimeout As set in SET LOCK_TIMEOUT (http://msdn.microsoft.com/en-us/library/ms189470.aspx)
  639. -1 = (default) indicates no time-out period
  640. Any other positive integer = sets the number of milliseconds that will pass before Microsoft SQL Server returns a locking error
  641. @onlinelocktimeout Indicates a time-out period for locks to wait at low priority, expressed in minutes; this is valid from SQL Server 2014 onwards
  642. @abortAfterwait If the online low priority lock timeout occurs, this will set the action to perform afterwards.
  643. NULL = (default) After lock timeout occurs, continue waiting for the lock with normal (regular) priority;
  644. 1 = Exit the online index rebuild DDL operation currently being executed without taking any action;
  645. 2 = Kill all user transactions that block the online index rebuild DDL operation so that the operation can continue.
  646. @dealROWG Set Columnstore reorg option to compress all rowgroups, and not just closed ones
  647. 0 = (default) compress closed rowgroups on columnstore.
  648. 1 = compress all rowgroups on columnstore, and not just closed ones.
  649. @getBlobfrag Indicates whether to exclude or include blobs from fragmentation scan.
  650. 0 = (default) exclude blobs from fragmentation scan.
  651. 1 = include blobs and off-row data when scanning for fragmentation.
  652. -------------------------------------------------------
  653. Usage:
  654. EXEC dbo.usp_AdaptiveIndexDefrag
  655. or customize it like the example:
  656. EXEC dbo.usp_AdaptiveIndexDefrag
  657. @Exec_Print = 0
  658. , @printCmds = 1
  659. , @updateStats = 1
  660. , @updateStatsWhere = 1
  661. , @debugMode = 1
  662. , @outputResults = 1
  663. , @dbScope = 'AdventureWorks2008R2'
  664. , @forceRescan = 1
  665. , @maxDopRestriction = 2
  666. , @minPageCount = 8
  667. , @maxPageCount = NULL
  668. , @minFragmentation = 1
  669. , @rebuildThreshold = 1
  670. , @rebuildThreshold_cs = 1
  671. , @defragDelay = '00:00:05'
  672. , @defragOrderColumn = 'range_scan_count'
  673. , @dealMaxPartition = NULL
  674. , @disableNCIX = 1
  675. , @offlinelocktimeout = 180;
  676. */
  677. SET NOCOUNT ON;
  678. SET XACT_ABORT ON;
  679. SET QUOTED_IDENTIFIER ON;
  680. SET DATEFORMAT ymd;
  681. SET DEADLOCK_PRIORITY -10;
  682. -- Required so it can update stats on IxVws and FiltIxs
  683. SET ANSI_WARNINGS ON;
  684. SET ANSI_PADDING ON;
  685. SET ANSI_NULLS ON;
  686. SET ARITHABORT ON;
  687. SET CONCAT_NULL_YIELDS_NULL ON;
  688. SET NUMERIC_ROUNDABORT OFF;
  689. BEGIN
  690. BEGIN TRY
  691. /* Validating and normalizing options... */
  692. IF @debugMode = 1
  693. RAISERROR('Validating options...', 0, 42) WITH NOWAIT;
  694. IF @minFragmentation IS NULL OR @minFragmentation NOT BETWEEN 0.00 AND 100.0
  695. SET @minFragmentation = 5.0;
  696. IF @rebuildThreshold IS NULL OR @rebuildThreshold NOT BETWEEN 0.00 AND 100.0
  697. SET @rebuildThreshold = 30.0;
  698. IF @rebuildThreshold_cs IS NULL OR @rebuildThreshold_cs NOT BETWEEN 0.00 AND 100.0
  699. SET @rebuildThreshold_cs = 10.0;
  700. IF @timeLimit IS NULL
  701. SET @timeLimit = 480;
  702. /* Validate if table name is fully qualified and database scope is set */
  703. IF @tblName IS NOT NULL AND @tblName NOT LIKE '%.%'
  704. BEGIN
  705. RAISERROR('WARNING: Table name must be fully qualified. Input format should be <schema>.<table_name>.', 15, 42) WITH NOWAIT;
  706. RETURN
  707. END;
  708. /* Validate if database scope is set when table name is also set */
  709. IF @tblName IS NOT NULL AND @dbScope IS NULL
  710. BEGIN
  711. RAISERROR('WARNING: A database scope must be set when using table names.', 15, 42) WITH NOWAIT;
  712. RETURN
  713. END;
  714. /* Validate if database scope exists */
  715. 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)
  716. BEGIN
  717. RAISERROR('WARNING: The database in scope does not exist or is a system database.', 15, 42) WITH NOWAIT;
  718. RETURN
  719. END;
  720. /* Validate offline lock timeout settings */
  721. IF @offlinelocktimeout IS NULL OR ISNUMERIC(@offlinelocktimeout) <> 1
  722. BEGIN
  723. RAISERROR('WARNING: Offline lock timeout must be set to an integer number.', 15, 42) WITH NOWAIT;
  724. RETURN
  725. END;
  726. IF @offlinelocktimeout <> -1 AND @offlinelocktimeout IS NOT NULL
  727. SET @offlinelocktimeout = ABS(@offlinelocktimeout)
  728. /* Validate online lock timeout settings */
  729. IF @onlinelocktimeout IS NULL OR ISNUMERIC(@onlinelocktimeout) <> 1
  730. BEGIN
  731. RAISERROR('WARNING: Online lock timeout must be set to an integer number.', 15, 42) WITH NOWAIT;
  732. RETURN
  733. END;
  734. IF @onlinelocktimeout <> 5 AND @onlinelocktimeout IS NOT NULL
  735. SET @onlinelocktimeout = ABS(@onlinelocktimeout)
  736. /* Validate online lock timeout wait action settings */
  737. IF @abortAfterwait IS NOT NULL AND @abortAfterwait NOT IN (0,1)
  738. BEGIN
  739. RAISERROR('WARNING: Online lock timeout action is invalid.', 15, 42) WITH NOWAIT;
  740. RETURN
  741. END;
  742. /* Validate amount of breather time to give between operations*/
  743. IF @defragDelay NOT LIKE '00:[0-5][0-9]:[0-5][0-9]'
  744. BEGIN
  745. SET @defragDelay = '00:00:05';
  746. RAISERROR('Defrag delay input not valid. Defaulting to 5s.', 0, 42) WITH NOWAIT;
  747. END;
  748. IF @defragOrderColumn IS NULL OR LOWER(@defragOrderColumn) NOT IN ('range_scan_count', 'fragmentation', 'page_count')
  749. BEGIN
  750. SET @defragOrderColumn = 'range_scan_count';
  751. RAISERROR('Defrag order input not valid. Defaulting to range_scan_count.', 0, 42) WITH NOWAIT;
  752. END;
  753. IF @defragSortOrder IS NULL OR UPPER(@defragSortOrder) NOT IN ('ASC', 'DESC')
  754. SET @defragSortOrder = 'DESC';
  755. IF UPPER(@scanMode) NOT IN ('LIMITED', 'SAMPLED', 'DETAILED')
  756. BEGIN
  757. SET @scanMode = 'LIMITED';
  758. RAISERROR('Index scan mode input not valid. Defaulting to LIMITED.', 0, 42) WITH NOWAIT;
  759. END;
  760. IF @ixtypeOption IS NOT NULL AND @ixtypeOption NOT IN (0,1)
  761. SET @ixtypeOption = NULL;
  762. IF @statsSample IS NOT NULL AND UPPER(@statsSample) NOT IN ('FULLSCAN', 'RESAMPLE')
  763. SET @statsSample = NULL;
  764. /* Find sql server version info */
  765. DECLARE @sqlmajorver int, @sqlminorver int, @sqlbuild int;
  766. SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  767. SELECT @sqlminorver = CONVERT(int, (@@microsoftversion / 0x10000) & 0xff);
  768. SELECT @sqlbuild = CONVERT(int, @@microsoftversion & 0xffff);
  769. /* Recognize if database in scope is a Always On secondary replica */
  770. IF @dbScope IS NOT NULL AND @sqlmajorver >= 11
  771. BEGIN
  772. DECLARE @sqlcmdAO NVARCHAR(3000), @paramsAO NVARCHAR(50), @DBinAG int
  773. SET @sqlcmdAO = 'IF LOWER(@dbScopeIN) IN (SELECT LOWER(DB_NAME(dr.database_id))
  774. FROM sys.dm_hadr_database_replica_states dr
  775. INNER JOIN sys.dm_hadr_availability_replica_states rs ON dr.group_id = rs.group_id
  776. INNER JOIN sys.databases d ON dr.database_id = d.database_id
  777. WHERE rs.role = 2 -- Is Secondary
  778. AND dr.is_local = 1
  779. AND rs.is_local = 1)
  780. BEGIN
  781. SET @DBinAG_OUT = 1
  782. END
  783. ELSE
  784. BEGIN
  785. SET @DBinAG_OUT = 0
  786. END'
  787. SET @paramsAO = N'@dbScopeIN NVARCHAR(256), @DBinAG_OUT int OUTPUT'
  788. EXECUTE sp_executesql @sqlcmdAO, @paramsAO, @dbScopeIN = @dbScope, @DBinAG_OUT = @DBinAG OUTPUT
  789. IF @DBinAG = 1
  790. BEGIN
  791. RAISERROR('WARNING: Cannot defrag database in scope because it is part of an Always On secondary replica.', 15, 42) WITH NOWAIT;
  792. RETURN
  793. END
  794. END
  795. /* Check if database scope has changed, if rescan is not being forced */
  796. IF @forceRescan = 0 AND @dbScope IS NOT NULL -- Specific scope was set
  797. BEGIN
  798. IF (SELECT COUNT(DISTINCT [dbID]) FROM dbo.tbl_AdaptiveIndexDefrag_Working) = 1
  799. 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)
  800. BEGIN
  801. SET @forceRescan = 1
  802. RAISERROR('Scope has changed. Forcing rescan of single database in scope...', 0, 42) WITH NOWAIT;
  803. END;
  804. END;
  805. /* Recognize if we have indexes of the chosen type left to defrag or stats left to update;
  806. otherwise force rescan of database(s), if rescan is not being forced */
  807. IF @forceRescan = 0
  808. 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)
  809. 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)
  810. 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)
  811. 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))
  812. BEGIN
  813. SET @forceRescan = 1
  814. RAISERROR('No indexes of the chosen type left to defrag nor statistics left to update. Forcing rescan...', 0, 42) WITH NOWAIT;
  815. END;
  816. /* Check if any databases where dropped or created since last run, if rescan is not being forced */
  817. IF @forceRescan = 0 AND @dbScope IS NULL
  818. BEGIN
  819. DECLARE @sqlcmd_CntSrc NVARCHAR(3000), @params_CntSrc NVARCHAR(50), @CountSrc int
  820. DECLARE @sqlcmd_CntTgt NVARCHAR(3000), @params_CntTgt NVARCHAR(50), @CountTgt int
  821. DECLARE @dbIDIX int, @hasIXs bit, @hasIXsCntsqlcmd NVARCHAR(3000), @hasIXsCntsqlcmdParams NVARCHAR(50)
  822. -- What is in working tables plus exceptions that still exist in server
  823. SET @sqlcmd_CntSrc = 'SELECT @CountSrc_OUT = COUNT(DISTINCT Working.[dbID]) FROM
  824. (SELECT DISTINCT [dbID] FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Working
  825. UNION
  826. SELECT DISTINCT [dbID] FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  827. UNION
  828. SELECT DISTINCT [dbID] FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Exceptions
  829. WHERE [dbID] IN (SELECT DISTINCT database_id FROM master.sys.databases sd
  830. WHERE LOWER(sd.[name]) NOT IN (''master'', ''tempdb'', ''model'', ''reportservertempdb'',''semanticsdb'')
  831. AND [state] = 0 -- must be ONLINE
  832. AND is_read_only = 0 -- cannot be READ_ONLY
  833. AND is_distributor = 0)
  834. ) Working'
  835. SET @params_CntSrc = N'@CountSrc_OUT int OUTPUT'
  836. -- What exists in current instance, in ONLINE state and READ_WRITE
  837. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexFindInDatabaseList'))
  838. DROP TABLE #tblIndexFindInDatabaseList;
  839. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexFindInDatabaseList'))
  840. CREATE TABLE #tblIndexFindInDatabaseList
  841. (
  842. [dbID] int
  843. , hasIXs bit NOT NULL
  844. , scanStatus bit NULL
  845. );
  846. /* Retrieve the list of databases to loop, excluding Always On secondary replicas */
  847. SET @sqlcmd_CntTgt = 'SELECT [database_id], 0, 0 -- not yet scanned
  848. FROM master.sys.databases
  849. WHERE LOWER([name]) = ISNULL(LOWER(@dbScopeIN), LOWER([name]))
  850. AND LOWER([name]) NOT IN (''master'', ''tempdb'', ''model'', ''reportservertempdb'',''semanticsdb'') -- exclude system databases
  851. AND [state] = 0 -- must be ONLINE
  852. AND is_read_only = 0 -- cannot be READ_ONLY
  853. AND is_distributor = 0'
  854. IF @sqlmajorver >= 11 -- Except all local Always On secondary replicas
  855. BEGIN
  856. SET @sqlcmd_CntTgt = @sqlcmd_CntTgt + CHAR(10) + 'AND [database_id] NOT IN (SELECT dr.database_id FROM sys.dm_hadr_database_replica_states dr
  857. INNER JOIN sys.dm_hadr_availability_replica_states rs ON dr.group_id = rs.group_id
  858. INNER JOIN sys.databases d ON dr.database_id = d.database_id
  859. WHERE rs.role = 2 -- Is Secondary
  860. AND dr.is_local = 1
  861. AND rs.is_local = 1)'
  862. END
  863. SET @params_CntTgt = N'@dbScopeIN NVARCHAR(256)'
  864. INSERT INTO #tblIndexFindInDatabaseList
  865. EXECUTE sp_executesql @sqlcmd_CntTgt, @params_CntTgt, @dbScopeIN = @dbScope
  866. WHILE (SELECT COUNT(*) FROM #tblIndexFindInDatabaseList WHERE scanStatus = 0) > 0
  867. BEGIN
  868. SELECT TOP 1 @dbIDIX = [dbID] FROM #tblIndexFindInDatabaseList WHERE scanStatus = 0;
  869. SET @hasIXsCntsqlcmd = 'IF EXISTS (SELECT TOP 1 [index_id] from [' + DB_NAME(@dbIDIX) + '].sys.indexes AS si
  870. INNER JOIN [' + DB_NAME(@dbIDIX) + '].sys.objects so ON si.object_id = so.object_id
  871. WHERE so.is_ms_shipped = 0 AND [index_id] > 0 AND si.is_hypothetical = 0
  872. AND si.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + DB_NAME(@dbIDIX) + '].sys.internal_tables AS sit))
  873. OR
  874. EXISTS (SELECT TOP 1 [stats_id] from [' + DB_NAME(@dbIDIX) + '].sys.stats AS ss
  875. INNER JOIN [' + DB_NAME(@dbIDIX) + '].sys.objects so ON ss.[object_id] = so.[object_id]
  876. WHERE so.is_ms_shipped = 0
  877. AND ss.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + DB_NAME(@dbIDIX) + '].sys.internal_tables AS sit))
  878. BEGIN SET @hasIXsOUT = 1 END ELSE BEGIN SET @hasIXsOUT = 0 END'
  879. SET @hasIXsCntsqlcmdParams = '@hasIXsOUT int OUTPUT'
  880. EXECUTE sp_executesql @hasIXsCntsqlcmd, @hasIXsCntsqlcmdParams, @hasIXsOUT = @hasIXs OUTPUT
  881. UPDATE #tblIndexFindInDatabaseList
  882. SET hasIXs = @hasIXs, scanStatus = 1
  883. WHERE [dbID] = @dbIDIX
  884. END
  885. EXECUTE sp_executesql @sqlcmd_CntSrc, @params_CntSrc, @CountSrc_OUT = @CountSrc OUTPUT
  886. SELECT @CountTgt = COUNT([dbID]) FROM #tblIndexFindInDatabaseList WHERE hasIXs = 1
  887. IF @CountSrc <> @CountTgt -- current databases in working lists <> number of eligible databases in instance
  888. BEGIN
  889. SET @forceRescan = 1
  890. RAISERROR('Scope has changed. Forcing rescan...', 0, 42) WITH NOWAIT;
  891. END
  892. END
  893. IF @debugMode = 1
  894. RAISERROR('Starting up...', 0, 42) WITH NOWAIT;
  895. /* Declare variables */
  896. DECLARE @ver VARCHAR(10)
  897. , @objectID int
  898. , @dbID int
  899. , @dbName NVARCHAR(256)
  900. , @indexID int
  901. , @operationFlag bit -- 0 = Reorganize, 1 = Rebuild
  902. , @partitionCount bigint
  903. , @schemaName NVARCHAR(128)
  904. , @objectName NVARCHAR(256)
  905. , @indexName NVARCHAR(256)
  906. , @statsName NVARCHAR(256)
  907. , @statsschemaName NVARCHAR(128)
  908. , @statsobjectName NVARCHAR(256)
  909. , @stats_norecompute bit
  910. , @stats_isincremental bit
  911. , @is_primary_key bit
  912. , @fill_factor int
  913. , @is_disabled bit
  914. , @is_padded bit
  915. , @has_filter bit
  916. , @partitionNumber smallint
  917. , @maxpartitionNumber smallint
  918. , @minpartitionNumber smallint
  919. , @fragmentation float
  920. , @pageCount int
  921. , @sqlcommand NVARCHAR(4000)
  922. , @sqlcommand2 NVARCHAR(600)
  923. , @sqldisablecommand NVARCHAR(600)
  924. , @sqlprecommand NVARCHAR(600)
  925. , @rebuildcommand NVARCHAR(600)
  926. , @dateTimeStart DATETIME
  927. , @dateTimeEnd DATETIME
  928. , @containsColumnstore int
  929. , @CStore_SQL NVARCHAR(4000)
  930. , @CStore_SQL_Param NVARCHAR(1000)
  931. , @editionCheck bit
  932. , @debugMessage VARCHAR(2048)
  933. , @updateSQL NVARCHAR(4000)
  934. , @partitionSQL NVARCHAR(4000)
  935. , @partitionSQL_Param NVARCHAR(1000)
  936. , @rowmodctrSQL NVARCHAR(4000)
  937. , @rowmodctrSQL_Param NVARCHAR(1000)
  938. , @rowmodctr bigint
  939. , @record_count bigint
  940. , @range_scan_count bigint
  941. , @getStatSQL NVARCHAR(4000)
  942. , @getStatSQL_Param NVARCHAR(1000)
  943. , @statsID int
  944. , @ixtype tinyint -- 0 = Heap; 1 = Clustered; 2 = Nonclustered; 3 = XML; 4 = Spatial
  945. , @containsLOB int
  946. , @LOB_SQL NVARCHAR(4000)
  947. , @LOB_SQL_Param NVARCHAR(1000)
  948. , @indexDefrag_id int
  949. , @statsUpdate_id int
  950. , @statsObjectID int
  951. , @startDateTime DATETIME
  952. , @endDateTime DATETIME
  953. , @getIndexSQL NVARCHAR(4000)
  954. , @getIndexSQL_Param NVARCHAR(4000)
  955. , @allowPageLockSQL NVARCHAR(4000)
  956. , @allowPageLockSQL_Param NVARCHAR(4000)
  957. , @allowPageLocks bit
  958. , @dealMaxPartitionSQL NVARCHAR(4000)
  959. , @cpucount smallint
  960. , @tblNameFQN NVARCHAR(1000)
  961. , @TableScanSQL NVARCHAR(2000)
  962. , @ixCntSource int
  963. , @ixCntTarget int
  964. , @ixCntsqlcmd NVARCHAR(1000)
  965. , @ixCntsqlcmdParams NVARCHAR(100)
  966. , @ColumnStoreGetIXSQL NVARCHAR(2000)
  967. , @ColumnStoreGetIXSQL_Param NVARCHAR(1000)
  968. , @rows bigint
  969. , @rows_sampled bigint
  970. /* Initialize variables */
  971. SELECT @startDateTime = GETDATE(), @endDateTime = DATEADD(minute, @timeLimit, GETDATE()), @operationFlag = NULL, @ver = '1.6.4.1';
  972. /* Create temporary tables */
  973. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragDatabaseList'))
  974. DROP TABLE #tblIndexDefragDatabaseList;
  975. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragDatabaseList'))
  976. CREATE TABLE #tblIndexDefragDatabaseList
  977. (
  978. dbID int
  979. , dbName NVARCHAR(256)
  980. , scanStatus bit NULL
  981. );
  982. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragmaxPartitionList'))
  983. DROP TABLE #tblIndexDefragmaxPartitionList;
  984. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragmaxPartitionList'))
  985. CREATE TABLE #tblIndexDefragmaxPartitionList
  986. (
  987. objectID int
  988. , indexID int
  989. , maxPartition int
  990. );
  991. /* Create table for fragmentation scan per table, index and partition - slower but less chance of blocking*/
  992. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragScanWorking'))
  993. DROP TABLE #tblIndexDefragScanWorking;
  994. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragScanWorking'))
  995. CREATE TABLE #tblIndexDefragScanWorking
  996. (
  997. objectID int
  998. , indexID int
  999. , type tinyint
  1000. , partitionNumber int
  1001. , is_done bit
  1002. );
  1003. /* Find available processors*/
  1004. SELECT @cpucount = COUNT(*)
  1005. FROM sys.dm_os_schedulers
  1006. WHERE is_online = 1 AND scheduler_id < 255 AND status = 'VISIBLE ONLINE'
  1007. IF @maxDopRestriction IS NOT NULL AND @maxDopRestriction > @cpucount AND @cpucount <= 8
  1008. BEGIN
  1009. SET @maxDopRestriction = @cpucount
  1010. END
  1011. ELSE IF @maxDopRestriction IS NOT NULL AND ((@maxDopRestriction > @cpucount AND @cpucount > 8) OR @maxDopRestriction > 8)
  1012. BEGIN
  1013. SET @maxDopRestriction = 8;
  1014. END
  1015. /* Refer to http://msdn.microsoft.com/en-us/library/ms174396.aspx */
  1016. IF (SELECT SERVERPROPERTY('EditionID')) IN (1804890536, 1872460670, 610778273, -2117995310)
  1017. SET @editionCheck = 1 -- supports enterprise only features: online rebuilds, partitioned indexes and MaxDOP
  1018. ELSE
  1019. SET @editionCheck = 0; -- does not support enterprise only features: online rebuilds, partitioned indexes and MaxDOP
  1020. /* Output the parameters to work with */
  1021. IF @debugMode = 1
  1022. BEGIN
  1023. SELECT @debugMessage = CHAR(10) + 'Executing AdaptiveIndexDefrag v' + @ver + ' on ' + @@VERSION + '.
  1024. The selected parameters are:
  1025. Defragment indexes with fragmentation greater or equal to ' + CAST(@minFragmentation AS NVARCHAR(10)) + ';
  1026. Rebuild indexes with fragmentation greater than ' + CAST(@rebuildThreshold AS NVARCHAR(10)) + ';
  1027. Rebuild columnstore indexes with fragmentation greater than ' + CAST(@rebuildThreshold_cs AS NVARCHAR(10)) + ';
  1028. ' + CASE WHEN @disableNCIX = 1 THEN 'Non-clustered indexes will be disabled prior to rebuild;
  1029. ' 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 + ';
  1030. Commands' + CASE WHEN @Exec_Print = 1 THEN ' WILL' ELSE ' WILL NOT' END + ' be executed automatically;
  1031. Defragment indexes in ' + @defragSortOrder + ' order of the ' + UPPER(@defragOrderColumn) + ' value;
  1032. Time limit' + CASE WHEN @timeLimit IS NULL THEN ' was not specified;' ELSE ' was specified and is ' + CAST(@timeLimit AS NVARCHAR(10)) END + ' minutes;
  1033. ' + CASE WHEN @dbScope IS NULL THEN 'ALL databases' ELSE 'The ' + @dbScope + ' database' END + ' will be defragmented;
  1034. ' + CASE WHEN @tblName IS NULL THEN 'ALL tables' ELSE 'The ' + @tblName + ' table' END + ' will be defragmented;
  1035. ' + '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;
  1036. The scan will be performed in ' + @scanMode + ' mode;
  1037. LOBs will ' + CASE WHEN @dealLOB = 1 THEN 'NOT ' ELSE '' END + 'be compacted;
  1038. Limit defrags to indexes' + CASE WHEN @maxPageCount IS NULL THEN ' with more than ' + CAST(@minPageCount AS NVARCHAR(10)) ELSE
  1039. ' between ' + CAST(@minPageCount AS NVARCHAR(10)) + ' and ' + CAST(@maxPageCount AS NVARCHAR(10)) END + ' pages;
  1040. Indexes will be defragmented' + CASE WHEN @onlineRebuild = 0 OR @editionCheck = 0 THEN ' OFFLINE;' ELSE ' ONLINE;' END + '
  1041. Indexes will be sorted in' + CASE WHEN @sortInTempDB = 0 THEN ' the DATABASE;' ELSE ' TEMPDB;' END + '
  1042. Indexes will have' + CASE WHEN @fillfactor = 1 THEN ' its ORIGINAL' ELSE ' the DEFAULT' END + ' Fill Factor;' +
  1043. CASE WHEN @dealMaxPartition = 1 AND @editionCheck = 1 THEN '
  1044. The right-most populated partitions will be ignored;'
  1045. WHEN @dealMaxPartition = 0 AND @editionCheck = 1 THEN '
  1046. Only the right-most populated partitions will be considered if greater than ' + CAST(@minPageCount AS NVARCHAR(10)) + ' page(s);'
  1047. ELSE CHAR(10) + 'All partitions will be considered;' END +
  1048. 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 +
  1049. CASE WHEN @updateStats = 1 AND @statsSample IS NOT NULL THEN CHAR(10) + 'Statistics will be updated with ' + @statsSample + '.' ELSE '' END +
  1050. 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 + '.' +
  1051. CHAR(10) + 'Defragmentation will use ' + CASE WHEN @editionCheck = 0 OR @maxDopRestriction IS NULL THEN 'system defaults for processors;'
  1052. ELSE CAST(@maxDopRestriction AS VARCHAR(2)) + ' processors;' END +
  1053. 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;' +
  1054. CHAR(10) + 'From SQL Server 2014, lock timeout is set to ' + CONVERT(NVARCHAR(15), @onlinelocktimeout) + ' for online rebuilds;' +
  1055. 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;' +
  1056. CHAR(10) + CASE WHEN @printCmds = 1 THEN ' DO print' ELSE ' DO NOT print' END + ' the sql commands;' +
  1057. CHAR(10) + CASE WHEN @outputResults = 1 THEN ' DO output' ELSE ' DO NOT output' END + ' fragmentation levels;
  1058. Wait ' + @defragDelay + ' (hh:mm:ss) between index operations;
  1059. Execute in' + CASE WHEN @debugMode = 1 THEN ' DEBUG' ELSE ' SILENT' END + ' mode.' + CHAR(10);
  1060. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1061. END;
  1062. /* If we are scanning the database(s), do some pre-work */
  1063. 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)
  1064. 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)))
  1065. BEGIN
  1066. IF @debugMode = 1
  1067. RAISERROR('Listing databases...', 0, 42) WITH NOWAIT;
  1068. /* Retrieve the list of databases to loop, exclusing Always On secondary replicas */
  1069. DECLARE @sqlcmdAO2 NVARCHAR(4000), @paramsAO2 NVARCHAR(50)
  1070. IF @debugMode = 1 AND @sqlmajorver >= 11
  1071. RAISERROR('Retrieving list of databases to loop, excluding Always On secondary replicas...', 0, 42) WITH NOWAIT;
  1072. IF @debugMode = 1 AND @sqlmajorver < 11
  1073. RAISERROR('Retrieving list of databases to loop...', 0, 42) WITH NOWAIT;
  1074. SET @sqlcmdAO2 = 'SELECT [database_id], name, 0 -- not yet scanned for fragmentation
  1075. FROM master.sys.databases
  1076. WHERE LOWER([name]) = ISNULL(LOWER(@dbScopeIN), LOWER([name]))
  1077. AND LOWER([name]) NOT IN (''master'', ''tempdb'', ''model'', ''reportservertempdb'',''semanticsdb'') -- exclude system databases
  1078. AND [state] = 0 -- must be ONLINE
  1079. AND is_read_only = 0 -- cannot be READ_ONLY
  1080. AND is_distributor = 0'
  1081. IF @sqlmajorver >= 11 -- Except all local Always On secondary replicas
  1082. BEGIN
  1083. SET @sqlcmdAO2 = @sqlcmdAO2 + CHAR(10) + 'AND [database_id] NOT IN (SELECT dr.database_id FROM sys.dm_hadr_database_replica_states dr
  1084. INNER JOIN sys.dm_hadr_availability_replica_states rs ON dr.group_id = rs.group_id
  1085. INNER JOIN sys.databases d ON dr.database_id = d.database_id
  1086. WHERE rs.role = 2 -- Is Secondary
  1087. AND dr.is_local = 1
  1088. AND rs.is_local = 1)'
  1089. END
  1090. SET @paramsAO2 = N'@dbScopeIN NVARCHAR(256)'
  1091. INSERT INTO #tblIndexDefragDatabaseList
  1092. EXECUTE sp_executesql @sqlcmdAO2, @paramsAO2, @dbScopeIN = @dbScope
  1093. IF @debugMode = 1
  1094. RAISERROR('Cross checking with exceptions for today...', 0, 42) WITH NOWAIT;
  1095. /* Avoid scanning databases that have all its indexes in the exceptions table i.e, fully excluded */
  1096. WHILE (SELECT COUNT(*) FROM #tblIndexDefragDatabaseList WHERE scanStatus = 0) > 0
  1097. BEGIN
  1098. SELECT TOP 1 @dbID = dbID FROM #tblIndexDefragDatabaseList WHERE scanStatus = 0;
  1099. SELECT @ixCntSource = COUNT([indexName]) FROM dbo.tbl_AdaptiveIndexDefrag_Exceptions WHERE [dbID] = @dbID AND exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0
  1100. SET @ixCntsqlcmd = 'SELECT @ixCntTargetOUT = COUNT(si.index_id) FROM [' + DB_NAME(@dbID) + '].sys.indexes si
  1101. INNER JOIN [' + DB_NAME(@dbID) + '].sys.objects so ON si.object_id = so.object_id
  1102. WHERE so.is_ms_shipped = 0 AND si.index_id > 0 AND si.is_hypothetical = 0
  1103. 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
  1104. SET @ixCntsqlcmdParams = '@ixCntTargetOUT int OUTPUT'
  1105. EXECUTE sp_executesql @ixCntsqlcmd, @ixCntsqlcmdParams, @ixCntTargetOUT = @ixCntTarget OUTPUT
  1106. IF @ixCntSource = @ixCntTarget AND @ixCntSource > 0 -- All database objects are excluded, so skip database scanning
  1107. BEGIN
  1108. UPDATE #tblIndexDefragDatabaseList
  1109. SET scanStatus = NULL
  1110. WHERE dbID = @dbID;
  1111. IF @debugMode = 1
  1112. SELECT @debugMessage = ' Database ' + DB_NAME(@dbID) + ' is fully excluded from todays work.';
  1113. IF @debugMode = 1
  1114. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1115. END
  1116. IF @ixCntSource < @ixCntTarget AND @ixCntSource > 0 -- Only some database objects are excluded, so scan anyway and deal with exclusions on a granular level
  1117. BEGIN
  1118. UPDATE #tblIndexDefragDatabaseList
  1119. SET scanStatus = 1
  1120. WHERE dbID = @dbID;
  1121. IF @debugMode = 1
  1122. SELECT @debugMessage = ' Database ' + DB_NAME(@dbID) + ' is partially excluded from todays work.';
  1123. IF @debugMode = 1
  1124. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1125. END
  1126. IF @ixCntSource = 0 -- Database does not have excluded objects
  1127. BEGIN
  1128. UPDATE #tblIndexDefragDatabaseList
  1129. SET scanStatus = 1
  1130. WHERE dbID = @dbID;
  1131. END;
  1132. END;
  1133. /* Delete databases that are fully excluded for today */
  1134. DELETE FROM #tblIndexDefragDatabaseList
  1135. WHERE scanStatus IS NULL;
  1136. /* Reset status after cross check with exceptions */
  1137. UPDATE #tblIndexDefragDatabaseList
  1138. SET scanStatus = 0;
  1139. END
  1140. /* 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) */
  1141. 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)
  1142. 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)))
  1143. BEGIN
  1144. IF @debugMode = 1
  1145. RAISERROR('Preparing for new database scan...', 0, 42) WITH NOWAIT;
  1146. /* Truncate list of indexes and stats to prepare for a new scan */
  1147. TRUNCATE TABLE dbo.tbl_AdaptiveIndexDefrag_Working;
  1148. TRUNCATE TABLE dbo.tbl_AdaptiveIndexDefrag_Stats_Working;
  1149. END
  1150. ELSE
  1151. BEGIN
  1152. /* Print an error message if there are any indexes left to defragment according to the chosen criteria */
  1153. IF @debugMode = 1
  1154. RAISERROR('There are still fragmented indexes or out-of-date stats from last execution. Resuming...', 0, 42) WITH NOWAIT;
  1155. END
  1156. /* Scan the database(s) */
  1157. IF (SELECT COUNT(*) FROM dbo.tbl_AdaptiveIndexDefrag_Working) = 0
  1158. BEGIN
  1159. IF @debugMode = 1
  1160. RAISERROR('Scanning database(s)...', 0, 42) WITH NOWAIT;
  1161. IF @debugMode = 1
  1162. RAISERROR(' Looping through list of databases and checking for fragmentation...', 0, 42) WITH NOWAIT;
  1163. /* Loop through list of databases */
  1164. WHILE (SELECT COUNT(*) FROM #tblIndexDefragDatabaseList WHERE scanStatus = 0) > 0
  1165. BEGIN
  1166. SELECT TOP 1 @dbID = dbID FROM #tblIndexDefragDatabaseList WHERE scanStatus = 0;
  1167. IF @debugMode = 1
  1168. SELECT @debugMessage = ' Working on ' + DB_NAME(@dbID) + '...';
  1169. IF @debugMode = 1
  1170. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1171. IF @dbScope IS NOT NULL AND @tblName IS NOT NULL
  1172. SELECT @tblNameFQN = @dbScope + '.' + @tblName
  1173. /* Set partitioning rebuild options; requires Enterprise Edition */
  1174. IF @dealMaxPartition IS NOT NULL AND @editionCheck = 0
  1175. SET @dealMaxPartition = NULL;
  1176. /* Truncate list of tables, indexes and partitions to prepare for a new scan */
  1177. TRUNCATE TABLE #tblIndexDefragScanWorking;
  1178. IF @debugMode = 1
  1179. RAISERROR(' Building list of objects in database...', 0, 42) WITH NOWAIT;
  1180. SELECT @TableScanSQL = 'SELECT si.[object_id], si.index_id, si.type, sp.partition_number, 0
  1181. FROM [' + DB_NAME(@dbID) + '].sys.indexes si
  1182. INNER JOIN [' + DB_NAME(@dbID) + '].sys.partitions sp ON si.[object_id] = sp.[object_id] AND si.index_id = sp.index_id
  1183. INNER JOIN [' + DB_NAME(@dbID) + '].sys.tables AS mst ON mst.[object_id] = si.[object_id]
  1184. INNER JOIN [' + DB_NAME(@dbID) + '].sys.schemas AS t ON t.[schema_id] = mst.[schema_id]' +
  1185. 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 +
  1186. 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 + '
  1187. AND si.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + DB_NAME(@dbID) + '].sys.internal_tables AS sit)' +
  1188. CASE WHEN @dbScope IS NOT NULL AND @tblName IS NOT NULL THEN '
  1189. AND t.name + ''.'' + mst.name = ''' + @tblName + ''';' ELSE ';' END
  1190. INSERT INTO #tblIndexDefragScanWorking
  1191. EXEC sp_executesql @TableScanSQL;
  1192. /* Do we want to act on a subset of existing partitions? */
  1193. IF @dealMaxPartition = 1 OR @dealMaxPartition = 0
  1194. BEGIN
  1195. IF @debugMode = 1
  1196. RAISERROR(' Setting partition handling...', 0, 42) WITH NOWAIT;
  1197. 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;';
  1198. INSERT INTO #tblIndexDefragmaxPartitionList
  1199. EXEC sp_executesql @dealMaxPartitionSQL;
  1200. END;
  1201. /* We don't want to defrag the right-most populated partition, so delete any records for partitioned indexes where partition = MAX(partition) */
  1202. IF @dealMaxPartition = 1 AND @editionCheck = 1
  1203. BEGIN
  1204. IF @debugMode = 1
  1205. RAISERROR(' Ignoring right-most populated partition...', 0, 42) WITH NOWAIT;
  1206. DELETE ids
  1207. FROM #tblIndexDefragScanWorking AS ids
  1208. INNER JOIN #tblIndexDefragmaxPartitionList AS mpl ON ids.objectID = mpl.objectID AND ids.indexID = mpl.indexID AND ids.partitionNumber = mpl.maxPartition;
  1209. END;
  1210. /* We only want to defrag the right-most populated partition, so delete any records for partitioned indexes where partition <> MAX(partition) */
  1211. IF @dealMaxPartition = 0 AND @editionCheck = 1
  1212. BEGIN
  1213. IF @debugMode = 1
  1214. RAISERROR(' Setting only right-most populated partition...', 0, 42) WITH NOWAIT;
  1215. DELETE ids
  1216. FROM #tblIndexDefragScanWorking AS ids
  1217. INNER JOIN #tblIndexDefragmaxPartitionList AS mpl ON ids.objectID = mpl.objectID AND ids.indexID = mpl.indexID AND ids.partitionNumber <> mpl.maxPartition;
  1218. END;
  1219. /* Determine which indexes to defragment using user-defined parameters */
  1220. IF @debugMode = 1
  1221. RAISERROR(' Filtering indexes according to ixtypeOption parameter...', 0, 42) WITH NOWAIT;
  1222. IF @ixtypeOption IS NULL
  1223. BEGIN
  1224. DELETE FROM #tblIndexDefragScanWorking
  1225. WHERE [type] = 0; -- ignore heaps
  1226. END
  1227. ELSE IF @ixtypeOption = 1
  1228. BEGIN
  1229. DELETE FROM #tblIndexDefragScanWorking
  1230. WHERE [type] NOT IN (1,5); -- keep only clustered index
  1231. END
  1232. ELSE IF @ixtypeOption = 0
  1233. BEGIN
  1234. DELETE FROM #tblIndexDefragScanWorking
  1235. WHERE [type] NOT IN (2,6); -- keep only non-clustered indexes
  1236. END;
  1237. -- Get rowstore indexes to work on
  1238. IF @debugMode = 1
  1239. RAISERROR(' Getting rowstore indexes...', 0, 42) WITH NOWAIT;
  1240. WHILE (SELECT COUNT(*) FROM #tblIndexDefragScanWorking WHERE is_done = 0 AND [type] IN (1,2)) > 0
  1241. BEGIN
  1242. SELECT TOP 1 @objectID = objectID, @indexID = indexID, @partitionNumber = partitionNumber
  1243. FROM #tblIndexDefragScanWorking WHERE is_done = 0 AND type IN (1,2)
  1244. BEGIN TRY
  1245. IF @getBlobfrag = 1
  1246. BEGIN
  1247. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Working (dbID, dbName, objectID, indexID, partitionNumber, fragmentation, page_count, range_scan_count, record_count, scanDate)
  1248. 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]
  1249. FROM sys.dm_db_index_physical_stats(@dbID, @objectID, @indexID, @partitionNumber, @scanMode) AS ps
  1250. 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
  1251. WHERE avg_fragmentation_in_percent >= @minFragmentation
  1252. AND ps.page_count >= @minPageCount
  1253. AND ps.index_level = 0 -- leaf-level nodes only, supports @scanMode
  1254. AND ps.alloc_unit_type_desc = 'IN_ROW_DATA' -- exclude blobs
  1255. GROUP BY ps.database_id, QUOTENAME(DB_NAME(ps.database_id)), ps.partition_number, os.range_scan_count, ps.record_count
  1256. OPTION (MAXDOP 2);
  1257. END
  1258. ELSE IF @getBlobfrag = 0
  1259. BEGIN
  1260. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Working (dbID, dbName, objectID, indexID, partitionNumber, fragmentation, page_count, range_scan_count, record_count, scanDate)
  1261. 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]
  1262. FROM sys.dm_db_index_physical_stats(@dbID, @objectID, @indexID, @partitionNumber, @scanMode) AS ps
  1263. 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
  1264. WHERE avg_fragmentation_in_percent >= @minFragmentation
  1265. AND ps.page_count >= @minPageCount
  1266. AND ps.index_level = 0 -- leaf-level nodes only, supports @scanMode
  1267. GROUP BY ps.database_id, QUOTENAME(DB_NAME(ps.database_id)), ps.partition_number, os.range_scan_count, ps.record_count
  1268. OPTION (MAXDOP 2);
  1269. END
  1270. END TRY
  1271. BEGIN CATCH
  1272. IF @debugMode = 1
  1273. BEGIN
  1274. 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)) + ')'
  1275. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1276. --RAISERROR(' An error has occurred executing the pre-command! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 0, 42) WITH NOWAIT;
  1277. END
  1278. END CATCH
  1279. UPDATE #tblIndexDefragScanWorking
  1280. SET is_done = 1
  1281. WHERE objectID = @objectID AND indexID = @indexID AND partitionNumber = @partitionNumber
  1282. END;
  1283. -- Get columnstore indexes to work on
  1284. IF @debugMode = 1 AND @sqlmajorver >= 12
  1285. RAISERROR(' Getting columnstore indexes...', 0, 42) WITH NOWAIT;
  1286. IF @sqlmajorver >= 12
  1287. BEGIN
  1288. WHILE (SELECT COUNT(*) FROM #tblIndexDefragScanWorking WHERE is_done = 0 AND [type] IN (5,6)) > 0
  1289. BEGIN
  1290. SELECT TOP 1 @objectID = objectID, @indexID = indexID, @partitionNumber = partitionNumber
  1291. FROM #tblIndexDefragScanWorking WHERE is_done = 0 AND type IN (5,6)
  1292. BEGIN TRY
  1293. 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]
  1294. FROM sys.column_store_row_groups rg
  1295. WHERE rg.object_id = @objectID_In
  1296. AND rg.index_id = @indexID_In
  1297. AND rg.partition_number = @partitionNumber_In
  1298. AND rg.state = 3 -- Only COMPRESSED row groups
  1299. GROUP BY rg.object_id, rg.index_id, rg.partition_number
  1300. OPTION (MAXDOP 2)'
  1301. SET @ColumnStoreGetIXSQL_Param = N'@dbID_In int, @objectID_In int, @indexID_In int, @partitionNumber_In smallint';
  1302. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Working (dbID, dbName, objectID, indexID, partitionNumber, fragmentation, page_count, record_count, scanDate)
  1303. EXECUTE sp_executesql @ColumnStoreGetIXSQL, @ColumnStoreGetIXSQL_Param, @dbID_In = @dbID, @objectID_In = @objectID, @indexID_In = @indexID, @partitionNumber_In = @partitionNumber;
  1304. END TRY
  1305. BEGIN CATCH
  1306. IF @debugMode = 1
  1307. BEGIN
  1308. 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)) + ')'
  1309. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1310. --RAISERROR(' An error has occurred executing the pre-command! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 0, 42) WITH NOWAIT;
  1311. END
  1312. END CATCH
  1313. UPDATE #tblIndexDefragScanWorking
  1314. SET is_done = 1
  1315. WHERE objectID = @objectID AND indexID = @indexID AND partitionNumber = @partitionNumber
  1316. END
  1317. END;
  1318. IF @debugMode = 1
  1319. RAISERROR(' Looking up additional index information...', 0, 42) WITH NOWAIT;
  1320. /* Look up index status for various purposes */
  1321. SELECT @updateSQL = N'UPDATE ids
  1322. 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
  1323. FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Working ids
  1324. INNER JOIN [' + DB_NAME(@dbID) + '].sys.objects AS o ON ids.objectID = o.object_id
  1325. INNER JOIN [' + DB_NAME(@dbID) + '].sys.indexes AS i ON o.object_id = i.object_id AND ids.indexID = i.index_id
  1326. INNER JOIN [' + DB_NAME(@dbID) + '].sys.schemas AS s ON o.schema_id = s.schema_id
  1327. WHERE o.object_id = ids.objectID AND i.index_id = ids.indexID AND i.type > 0
  1328. AND o.object_id NOT IN (SELECT sit.object_id FROM [' + DB_NAME(@dbID) + '].sys.internal_tables AS sit)
  1329. AND ids.[dbID] = ' + CAST(@dbID AS NVARCHAR(10));
  1330. EXECUTE sp_executesql @updateSQL;
  1331. IF @scanMode = 'LIMITED'
  1332. BEGIN
  1333. SELECT @updateSQL = N'UPDATE ids
  1334. SET record_count = [rows]
  1335. FROM [' + DB_NAME() + '].dbo.tbl_AdaptiveIndexDefrag_Working ids
  1336. 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
  1337. WHERE ids.[dbID] = ' + CAST(@dbID AS NVARCHAR(10));
  1338. EXECUTE sp_executesql @updateSQL;
  1339. END
  1340. IF @debugMode = 1
  1341. RAISERROR(' Looking up additional statistic information...', 0, 42) WITH NOWAIT;
  1342. /* Look up stats information for various purposes */
  1343. IF @tblName IS NULL
  1344. BEGIN
  1345. SELECT @updateSQL = N'USE [' + DB_NAME(@dbID) + '];
  1346. 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 + '
  1347. 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
  1348. FROM sys.stats ss
  1349. INNER JOIN sys.objects so ON ss.[object_id] = so.[object_id]
  1350. INNER JOIN sys.schemas s ON so.[schema_id] = s.[schema_id]
  1351. LEFT JOIN sys.indexes si ON ss.[object_id] = si.[object_id] and ss.name = si.name
  1352. ' + 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 + '
  1353. WHERE is_ms_shipped = 0 ' + CASE WHEN @sqlmajorver >= 12 THEN 'AND ss.is_temporary = 0' ELSE '' END + '
  1354. AND so.[object_id] NOT IN (SELECT sit.[object_id] FROM sys.internal_tables AS sit)
  1355. AND so.[type] IN (''U'',''V'')
  1356. AND (si.[type] IS NULL OR si.[type] NOT IN (5,6,7))' -- Avoid error 35337
  1357. END
  1358. ELSE
  1359. BEGIN
  1360. DECLARE @tblNameOnly NVARCHAR(1000), @schemaNameOnly NVARCHAR(128)
  1361. SELECT @tblNameOnly = RIGHT(@tblName, LEN(@tblName) - CHARINDEX('.', @tblName, 1)), @schemaNameOnly = LEFT(@tblName, CHARINDEX('.', @tblName, 1) -1)
  1362. SELECT @updateSQL = N'USE [' + DB_NAME(@dbID) + '];
  1363. 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 + '
  1364. 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
  1365. FROM sys.stats ss
  1366. INNER JOIN sys.objects so ON ss.[object_id] = so.[object_id]
  1367. INNER JOIN sys.schemas s ON so.[schema_id] = s.[schema_id]
  1368. LEFT JOIN sys.indexes si ON ss.[object_id] = si.[object_id] and ss.name = si.name
  1369. ' + CASE WHEN @sqlmajorver >= 12 THEN 'CROSS APPLY sys.dm_db_stats_properties_internal(ss.[object_id], ss.stats_id) sp' ELSE '' END + '
  1370. WHERE is_ms_shipped = 0 ' + CASE WHEN @sqlmajorver >= 12 THEN 'AND ss.is_temporary = 0' ELSE '' END + '
  1371. AND so.[object_id] NOT IN (SELECT sit.[object_id] FROM sys.internal_tables AS sit)
  1372. AND s.name = ''' + @schemaNameOnly + '''
  1373. AND so.name = ''' + @tblNameOnly + '''
  1374. AND so.[type] IN (''U'',''V'')
  1375. AND (si.[type] IS NULL OR si.[type] NOT IN (5,6,7))' -- Avoid error 35337
  1376. END
  1377. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Stats_Working (dbID, dbName, objectID, statsID, partitionNumber, schemaName, objectName, statsName, [no_recompute], [is_incremental], scanDate)
  1378. EXECUTE sp_executesql @updateSQL;
  1379. /* Keep track of which databases have already been scanned */
  1380. UPDATE #tblIndexDefragDatabaseList
  1381. SET scanStatus = 1
  1382. WHERE dbID = @dbID;
  1383. END;
  1384. /* Delete any records for disabled (except those disabled by the defrag cycle itself) or hypothetical indexes */
  1385. IF @debugMode = 1
  1386. RAISERROR(' Listing and removing disabled indexes (except those disabled by the defrag cycle itself) or hypothetical indexes from loop...', 0, 42) WITH NOWAIT;
  1387. IF (SELECT COUNT(*) FROM dbo.tbl_AdaptiveIndexDefrag_Working AS ids WHERE ids.is_disabled = 1 OR ids.is_hypothetical = 1) > 0
  1388. DELETE ids
  1389. FROM dbo.tbl_AdaptiveIndexDefrag_Working AS ids
  1390. 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
  1391. WHERE ids.is_disabled = 1 OR ids.is_hypothetical = 1 AND ids_disable.indexID IS NULL;
  1392. IF @debugMode = 1
  1393. RAISERROR(' Updating Exception mask for any index that has a restriction on the days it CANNOT be defragmented...', 0, 42) WITH NOWAIT;
  1394. /* Update our Exception mask for any index that has a restriction on the days it CANNOT be defragmented
  1395. based on 1=Sunday, 2=Monday, 4=Tuesday, 8=Wednesday, 16=Thursday, 32=Friday, 64=Saturday, 127=AllWeek
  1396. */
  1397. UPDATE ids
  1398. SET ids.exclusionMask = ide.exclusionMask
  1399. FROM dbo.tbl_AdaptiveIndexDefrag_Working AS ids
  1400. INNER JOIN dbo.tbl_AdaptiveIndexDefrag_Exceptions AS ide ON ids.[dbID] = ide.[dbID] AND ids.objectID = ide.objectID AND ids.indexID = ide.indexID;
  1401. END;
  1402. IF @debugMode = 1
  1403. 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)!'
  1404. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  1405. WHERE defragDate IS NULL AND page_count BETWEEN @minPageCount AND ISNULL(@maxPageCount, page_count) AND exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0;
  1406. IF @debugMode = 1
  1407. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1408. IF @debugMode = 1
  1409. BEGIN
  1410. IF @updateStatsWhere = 1
  1411. BEGIN
  1412. 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)!'
  1413. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss
  1414. INNER JOIN dbo.tbl_AdaptiveIndexDefrag_Working ids ON ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID
  1415. 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;
  1416. END
  1417. ELSE
  1418. BEGIN
  1419. 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),'
  1420. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss
  1421. INNER JOIN dbo.tbl_AdaptiveIndexDefrag_Working ids ON ids.[dbID] = idss.[dbID] AND ids.objectID = idss.objectID
  1422. 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;
  1423. 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)!'
  1424. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss
  1425. WHERE idss.updateDate IS NULL
  1426. 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);
  1427. END
  1428. END
  1429. IF @debugMode = 1
  1430. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1431. IF @Exec_Print = 0 AND @printCmds = 1
  1432. BEGIN
  1433. RAISERROR(' Printing SQL statements...', 0, 42) WITH NOWAIT;
  1434. END;
  1435. /* Begin defragmentation loop */
  1436. 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
  1437. BEGIN
  1438. /* Check to see if we need to exit loop because of our time limit */
  1439. IF ISNULL(@endDateTime, GETDATE()) < GETDATE()
  1440. RAISERROR('Time limit has been exceeded for this maintenance window!', 16, 42) WITH NOWAIT;
  1441. IF @debugMode = 1
  1442. RAISERROR(' Selecting an index to defragment...', 0, 42) WITH NOWAIT;
  1443. /* Select the index with highest priority, based on the values submitted; Verify date constraint for this index in the Exception table */
  1444. SET @getIndexSQL = N'SELECT TOP 1 @objectID_Out = objectID, @indexID_Out = indexID, @dbID_Out = dbID
  1445. FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE defragDate IS NULL '
  1446. + CASE WHEN @Exec_Print = 0 THEN 'AND printStatus = 0 ' ELSE '' END + '
  1447. AND exclusionMask & POWER(2, DATEPART(weekday, GETDATE())-1) = 0
  1448. AND page_count BETWEEN @p_minPageCount AND ISNULL(@p_maxPageCount, page_count)
  1449. ORDER BY + ' + @defragOrderColumn + ' ' + @defragSortOrder;
  1450. SET @getIndexSQL_Param = N'@objectID_Out int OUTPUT, @indexID_Out int OUTPUT, @dbID_Out int OUTPUT, @p_minPageCount int, @p_maxPageCount int';
  1451. EXECUTE sp_executesql @getIndexSQL, @getIndexSQL_Param, @p_minPageCount = @minPageCount, @p_maxPageCount = @maxPageCount, @objectID_Out = @objectID OUTPUT, @indexID_Out = @indexID OUTPUT, @dbID_Out = @dbID OUTPUT;
  1452. IF @debugMode = 1
  1453. RAISERROR(' Getting partition count...', 0, 42) WITH NOWAIT;
  1454. /* Determine if the index is partitioned */
  1455. SELECT @partitionCount = MAX(partitionNumber)
  1456. FROM dbo.tbl_AdaptiveIndexDefrag_Working AS ids
  1457. WHERE objectID = @objectID AND indexID = @indexID AND dbID = @dbID
  1458. IF @debugMode = 1
  1459. RAISERROR(' Getting selected index information...', 0, 42) WITH NOWAIT;
  1460. /* Get object names and info */
  1461. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1462. BEGIN
  1463. 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
  1464. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  1465. 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));
  1466. END
  1467. ELSE
  1468. BEGIN
  1469. 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
  1470. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  1471. 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));
  1472. END
  1473. /* Determine maximum partition number for use with stats update*/
  1474. IF @updateStats = 1
  1475. BEGIN
  1476. SELECT @maxpartitionNumber = MAX(partitionNumber), @minpartitionNumber = MIN(partitionNumber)
  1477. FROM tbl_AdaptiveIndexDefrag_Working
  1478. WHERE objectID = @objectID AND indexID = @indexID AND dbID = @dbID;
  1479. END
  1480. IF @debugMode = 1
  1481. RAISERROR(' Checking if any LOBs exist...', 0, 42) WITH NOWAIT;
  1482. SET @containsLOB = 0
  1483. /* Determine if the index contains LOBs, with info from sys.types */
  1484. IF @ixtype = 2 AND @sqlmajorver < 11 -- Nonclustered and LOBs in INCLUDED columns? Up to SQL 2008R2
  1485. BEGIN
  1486. SELECT @LOB_SQL = 'SELECT @containsLOB_OUT = COUNT(*) FROM ' + @dbName + '.sys.columns c WITH (NOLOCK)
  1487. INNER JOIN ' + @dbName + '.sys.index_columns ic WITH (NOLOCK) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
  1488. INNER JOIN ' + @dbName + '.sys.indexes i WITH (NOLOCK) ON i.[object_id] = ic.[object_id] and i.index_id = ic.index_id
  1489. WHERE max_length = -1 AND ic.is_included_column = 1
  1490. AND i.object_id = ' + CAST(@objectID AS NVARCHAR(10)) + ' AND i.index_id = ' + CAST(@indexID AS NVARCHAR(10)) + ';'
  1491. /* max_length = -1 for VARBINARY(MAX), VARCHAR(MAX), NVARCHAR(MAX), XML */
  1492. ,@LOB_SQL_Param = '@containsLOB_OUT int OUTPUT';
  1493. EXECUTE sp_executesql @LOB_SQL, @LOB_SQL_Param, @containsLOB_OUT = @containsLOB OUTPUT;
  1494. IF @debugMode = 1 AND @containsLOB > 0 AND @onlineRebuild = 1
  1495. RAISERROR(' Online rebuild not possible on indexes with LOBs in INCLUDED columns...', 0, 42) WITH NOWAIT;
  1496. END
  1497. IF @ixtype = 1 -- Clustered and has LOBs in table?
  1498. BEGIN
  1499. SELECT @LOB_SQL = 'SELECT @containsLOB_OUT = COUNT(*) FROM ' + @dbName + '.sys.columns c WITH (NOLOCK)
  1500. INNER JOIN ' + @dbName + '.sys.indexes i WITH (NOLOCK) ON c.[object_id] = i.[object_id]
  1501. WHERE system_type_id IN (34, 35, 99) ' + CASE WHEN @sqlmajorver < 11 THEN 'OR max_length = -1 ' ELSE '' END +
  1502. 'AND i.object_id = ' + CAST(@objectID AS NVARCHAR(10)) + ' AND i.index_id = ' + CAST(@indexID AS NVARCHAR(10)) + ';'
  1503. /* system_type_id = 34 for IMAGE, 35 for TEXT, 99 for NTEXT,
  1504. max_length = -1 for VARBINARY(MAX), VARCHAR(MAX), NVARCHAR(MAX), XML */
  1505. ,@LOB_SQL_Param = '@containsLOB_OUT int OUTPUT';
  1506. EXECUTE sp_executesql @LOB_SQL, @LOB_SQL_Param, @containsLOB_OUT = @containsLOB OUTPUT;
  1507. IF @debugMode = 1 AND @containsLOB > 0 AND @onlineRebuild = 1
  1508. RAISERROR(' Online rebuild not possible on clustered index when certain LOBs exist in table...', 0, 42) WITH NOWAIT;
  1509. END
  1510. IF @debugMode = 1 AND (@sqlmajorver >= 11 OR @ixtype IN (5,6))
  1511. RAISERROR(' Checking for Columnstore index...', 0, 42) WITH NOWAIT;
  1512. SET @containsColumnstore = 0
  1513. IF @ixtype NOT IN (5,6) -- Not already in the scope of a Columnstore index
  1514. AND @sqlmajorver >= 11 -- Parent table has Columnstore indexes?
  1515. BEGIN
  1516. 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);'
  1517. ,@CStore_SQL_Param = '@containsColumnstore_OUT int OUTPUT';
  1518. EXECUTE sp_executesql @CStore_SQL, @CStore_SQL_Param, @containsColumnstore_OUT = @containsColumnstore OUTPUT;
  1519. IF @debugMode = 1 AND @containsColumnstore > 0 AND @onlineRebuild = 1
  1520. RAISERROR(' Online rebuild not possible when parent table has Columnstore index...', 0, 42) WITH NOWAIT;
  1521. END
  1522. IF @ixtype IN (5,6)
  1523. BEGIN
  1524. SET @containsColumnstore = 1
  1525. IF @debugMode = 1 AND @containsColumnstore > 0 AND @onlineRebuild = 1
  1526. RAISERROR(' Online rebuild not possible on Columnstore indexes...', 0, 42) WITH NOWAIT;
  1527. END
  1528. IF @debugMode = 1
  1529. RAISERROR(' Checking if index does not allow page locks...', 0, 42) WITH NOWAIT;
  1530. /* 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*/
  1531. IF @forceRescan = 0
  1532. BEGIN
  1533. 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)) + ';'
  1534. ,@allowPageLockSQL_Param = '@allowPageLocks_OUT bit OUTPUT';
  1535. EXECUTE sp_executesql @allowPageLockSQL, @allowPageLockSQL_Param, @allowPageLocks_OUT = @allowPageLocks OUTPUT;
  1536. END
  1537. ELSE
  1538. BEGIN
  1539. SELECT @allowPageLocks = [allow_page_locks] FROM dbo.tbl_AdaptiveIndexDefrag_Working WHERE objectID = @objectID AND indexID = @indexID AND [dbID] = @dbID
  1540. END
  1541. IF @debugMode = 1 AND @allowPageLocks = 0
  1542. RAISERROR(' Index does not allow page locks...', 0, 42) WITH NOWAIT;
  1543. IF @debugMode = 1
  1544. BEGIN
  1545. SELECT @debugMessage = ' Found ' + CONVERT(NVARCHAR(10), @fragmentation) + ' percent fragmentation on index ' + @indexName + '...';
  1546. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1547. END
  1548. IF @debugMode = 1
  1549. RAISERROR(' Building SQL statements...', 0, 42) WITH NOWAIT;
  1550. /* If there's not a lot of fragmentation, or if we have a LOB, we should reorganize.
  1551. Filtered indexes or indexes that do not allow page locks should always rebuild. */
  1552. IF (@fragmentation < @rebuildThreshold AND @ixtype IN (1,2) AND @has_filter = 0 AND @allowPageLocks = 1)
  1553. OR (@fragmentation < @rebuildThreshold_cs AND @ixtype IN (5,6))
  1554. BEGIN
  1555. SET @operationFlag = 0
  1556. /* Set Reorg command */
  1557. SET @sqlcommand = N'ALTER INDEX ' + @indexName + N' ON ' + @dbName + N'.' + @schemaName + N'.' + @objectName + N' REORGANIZE';
  1558. /* Set partition reorg options; requires Enterprise Edition; valid only if more than one partition exists */
  1559. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1560. SET @sqlcommand = @sqlcommand + N' PARTITION = ' + CAST(@partitionNumber AS NVARCHAR(10));
  1561. /* Set LOB reorg options; valid only if no more than one partition exists */
  1562. IF @dealLOB = 1 AND @partitionCount = 1 AND @ixtype IN (1,2)
  1563. SET @sqlcommand = @sqlcommand + N' WITH (LOB_COMPACTION = OFF)';
  1564. IF @dealLOB = 0 AND @partitionCount = 1 AND @ixtype IN (1,2)
  1565. SET @sqlcommand = @sqlcommand + N' WITH (LOB_COMPACTION = ON)';
  1566. /* Set Columnstore reorg option to compress all rowgroups, and not just closed ones */
  1567. IF @sqlmajorver >= 12 AND @dealROWG = 1 AND @ixtype IN (5,6)
  1568. SET @sqlcommand = @sqlcommand + N' WITH (COMPRESS_ALL_ROW_GROUPS = ON)';
  1569. SET @sqlcommand = @sqlcommand + N';';
  1570. END
  1571. /* If the index is heavily fragmented and doesn't contain any partitions,
  1572. or if the index does not allow page locks, or if it is a filtered index, rebuild it */
  1573. ELSE IF (@fragmentation >= @rebuildThreshold AND @ixtype IN (1,2))
  1574. OR (@fragmentation >= @rebuildThreshold_cs AND @ixtype IN (5,6))
  1575. OR @has_filter = 1 OR @allowPageLocks = 0
  1576. BEGIN
  1577. SET @rebuildcommand = N' REBUILD'
  1578. SET @operationFlag = 1
  1579. /* Set partition rebuild options; requires Enterprise Edition; valid only if more than one partition exists */
  1580. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1581. SET @rebuildcommand = @rebuildcommand + N' PARTITION = ' + CAST(@partitionNumber AS NVARCHAR(10));
  1582. --ELSE IF @dealMaxPartition IS NULL AND @editionCheck = 1 AND @partitionCount > 1
  1583. --SET @rebuildcommand = @rebuildcommand + N' PARTITION = ALL';
  1584. /* Disallow disabling indexes on partitioned tables when defraging a subset of existing partitions */
  1585. IF @dealMaxPartition IS NOT NULL AND @partitionCount > 1
  1586. SET @disableNCIX = 0
  1587. /* Set defrag options*/
  1588. SET @rebuildcommand = @rebuildcommand + N' WITH ('
  1589. /* Set index pad options; not compatible with partition operations*/
  1590. IF @is_padded = 1 AND (@dealMaxPartition IS NULL OR (@dealMaxPartition IS NOT NULL AND @partitionCount = 1))
  1591. SET @rebuildcommand = @rebuildcommand + N'PAD_INDEX = ON, '
  1592. /* Set online rebuild options; requires Enterprise Edition; not compatible with partition operations, Columnstore indexes in table and XML or Spatial indexes.
  1593. Up to SQL Server 2008R2, not compatible with clustered indexes with LOB columnns in table or non-clustered indexes with LOBs in INCLUDED columns.
  1594. In SQL Server 2012, not compatible with clustered indexes with LOB columnns in table.*/
  1595. IF @sqlmajorver <= 11 AND @onlineRebuild = 1 AND @editionCheck = 1
  1596. AND @ixtype IN (1,2) AND @containsLOB = 0
  1597. AND (@dealMaxPartition IS NULL OR (@dealMaxPartition IS NOT NULL AND @partitionCount = 1))
  1598. SET @rebuildcommand = @rebuildcommand + N'ONLINE = ON, ';
  1599. /* Set online rebuild options; requires Enterprise Edition; not compatible with partition operations, Columnstore indexes in table and XML or Spatial indexes.
  1600. In SQL Server 2014, not compatible with clustered indexes with LOB columnns in table, but compatible with partition operations.
  1601. Also, we can use Lock Priority with online indexing.*/
  1602. IF @sqlmajorver > 11 AND @onlineRebuild = 1 AND @editionCheck = 1
  1603. AND @ixtype IN (1,2) AND @containsLOB = 0
  1604. 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 + ')), '
  1605. /* Set fill factor operation preferences; not compatible with partition operations and Columnstore indexes*/
  1606. IF @fillfactor = 1 AND (@dealMaxPartition IS NULL OR (@dealMaxPartition IS NOT NULL AND @partitionCount = 1)) AND @ixtype IN (1,2)
  1607. SET @rebuildcommand = @rebuildcommand + N'FILLFACTOR = ' + CONVERT(NVARCHAR, CASE WHEN @fill_factor = 0 THEN 100 ELSE @fill_factor END) + N', ';
  1608. IF @fillfactor = 0 AND (@dealMaxPartition IS NULL OR (@dealMaxPartition IS NOT NULL AND @partitionCount = 1)) AND @ixtype IN (1,2)
  1609. SET @rebuildcommand = @rebuildcommand + N'FILLFACTOR = 100, ';
  1610. /* Set sort operation preferences */
  1611. IF @sortInTempDB = 1 AND @ixtype IN (1,2)
  1612. SET @rebuildcommand = @rebuildcommand + N'SORT_IN_TEMPDB = ON, ';
  1613. IF @sortInTempDB = 0 AND @ixtype IN (1,2)
  1614. SET @rebuildcommand = @rebuildcommand + N'SORT_IN_TEMPDB = OFF, ';
  1615. /* Set NO_RECOMPUTE preference */
  1616. IF @ix_statsnorecompute = 1 AND @ixtype IN (1,2)
  1617. SET @sqlcommand = @sqlcommand + N' STATISTICS_NORECOMPUTE = ON, ';
  1618. IF @ix_statsnorecompute = 0 AND @ixtype IN (1,2)
  1619. SET @sqlcommand = @sqlcommand + N' STATISTICS_NORECOMPUTE = OFF, ';
  1620. /* Set processor restriction options; requires Enterprise Edition */
  1621. IF @maxDopRestriction IS NOT NULL AND @editionCheck = 1
  1622. SET @rebuildcommand = @rebuildcommand + N'MAXDOP = ' + CAST(@maxDopRestriction AS VARCHAR(2)) + N');';
  1623. ELSE
  1624. SET @rebuildcommand = @rebuildcommand + N');';
  1625. IF @rebuildcommand LIKE '% WITH ();'
  1626. SET @rebuildcommand = REPLACE(@rebuildcommand, ' WITH ()', '')
  1627. /* Set NCIX disable command, except for clustered index*/
  1628. SET @sqldisablecommand = NULL
  1629. IF @disableNCIX = 1 AND @ixtype = 2 AND @is_primary_key = 0
  1630. BEGIN
  1631. SET @sqldisablecommand = N'ALTER INDEX ' + @indexName + N' ON ' + @dbName + N'.' + @schemaName + N'.' + @objectName + ' DISABLE;';
  1632. END
  1633. /* Set update statistics command for index only, before rebuild, as rebuild performance is dependent on statistics (only working on non-partitioned tables)
  1634. http://blogs.msdn.com/b/psssql/archive/2009/03/18/be-aware-of-parallel-index-creation-performance-issues.aspx */
  1635. SET @sqlprecommand = NULL
  1636. /* Is stat incremental? */
  1637. SELECT TOP 1 @stats_isincremental = [is_incremental] FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1638. WHERE dbName = @dbName AND schemaName = @schemaName AND objectName = @objectName AND statsName = @indexName;
  1639. IF (@sqlmajorver < 13 OR @partitionCount = 1) AND @sqldisablecommand IS NULL AND @ixtype IN (1,2)
  1640. BEGIN
  1641. SET @sqlprecommand = N'UPDATE STATISTICS ' + @dbName + N'.' + @schemaName + N'.' + @objectName + N' (' + @indexName + N')'
  1642. SET @sqlprecommand = @sqlprecommand + N'; '
  1643. END
  1644. ELSE IF @sqlmajorver >= 13 AND @partitionCount > 1 AND @stats_isincremental = 1 AND @sqldisablecommand IS NULL AND @ixtype IN (1,2)
  1645. BEGIN
  1646. SET @sqlprecommand = N'UPDATE STATISTICS ' + @dbName + N'.' + @schemaName + N'.' + @objectName + N' (' + @indexName + N') WITH RESAMPLE ON PARTITIONS(' + CONVERT(NVARCHAR(10), @partitionNumber) + N')'
  1647. SET @sqlprecommand = @sqlprecommand + N'; '
  1648. END
  1649. /* Set Rebuild command */
  1650. SET @sqlcommand = N'ALTER INDEX ' + @indexName + N' ON ' + @dbName + N'.' + @schemaName + N'.' + @objectName + REPLACE(@rebuildcommand,', )', ')');
  1651. /* For offline rebuilds, set lock timeout if not default */
  1652. IF @onlineRebuild = 0 AND @offlinelocktimeout > -1 AND @offlinelocktimeout IS NOT NULL
  1653. SET @sqlcommand = 'SET LOCK_TIMEOUT ' + CONVERT(NVARCHAR(15), @offlinelocktimeout) + '; ' + @sqlcommand
  1654. END
  1655. ELSE
  1656. BEGIN
  1657. /* Print an error message if any indexes happen to not meet the criteria above */
  1658. IF @debugMode = 1
  1659. BEGIN
  1660. SET @debugMessage = 'We are unable to defrag index ' + @indexName + N' on table ' + @dbName + N'.' + @schemaName + N'.' + @objectName
  1661. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1662. END
  1663. END;
  1664. IF @operationFlag = 0 AND @sqlprecommand IS NOT NULL
  1665. SET @sqlprecommand = NULL
  1666. IF @operationFlag = 0 AND @sqldisablecommand IS NOT NULL
  1667. SET @sqldisablecommand = NULL
  1668. /* Are we executing the SQL? If so, do it */
  1669. IF @Exec_Print = 1
  1670. BEGIN
  1671. /* Get the time for logging purposes */
  1672. SET @dateTimeStart = GETDATE();
  1673. /* Start log actions */
  1674. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1675. BEGIN
  1676. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_log (dbID, dbName, objectID, objectName, indexID, indexName, partitionNumber, fragmentation, page_count, range_scan_count, fill_factor, dateTimeStart, sqlStatement)
  1677. SELECT @dbID, @dbName, @objectID, @objectName, @indexID, @indexName, @partitionNumber, @fragmentation, @pageCount, @range_scan_count, @fill_factor, @dateTimeStart, ISNULL(@sqlprecommand, '') + @sqlcommand;
  1678. END
  1679. ELSE
  1680. BEGIN
  1681. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_log (dbID, dbName, objectID, objectName, indexID, indexName, partitionNumber, fragmentation, page_count, range_scan_count, fill_factor, dateTimeStart, sqlStatement)
  1682. SELECT @dbID, @dbName, @objectID, @objectName, @indexID, @indexName, 1, @fragmentation, @pageCount, @range_scan_count, @fill_factor, @dateTimeStart, ISNULL(@sqlprecommand, '') + @sqlcommand;
  1683. END
  1684. SET @indexDefrag_id = SCOPE_IDENTITY();
  1685. IF @sqlprecommand IS NULL AND @sqldisablecommand IS NULL
  1686. BEGIN
  1687. SET @debugMessage = ' ' + @sqlcommand;
  1688. END
  1689. ELSE IF @sqlprecommand IS NOT NULL AND @sqldisablecommand IS NULL
  1690. BEGIN
  1691. SET @debugMessage = ' ' + @sqlprecommand + CHAR(10) + ' ' + @sqlcommand;
  1692. END;
  1693. ELSE IF @sqlprecommand IS NULL AND @sqldisablecommand IS NOT NULL
  1694. BEGIN
  1695. SET @debugMessage = ' ' + @sqldisablecommand + CHAR(10) + ' ' + @sqlcommand;
  1696. END;
  1697. ELSE IF @sqlprecommand IS NOT NULL AND @sqldisablecommand IS NOT NULL
  1698. BEGIN
  1699. SET @debugMessage = ' ' + @sqldisablecommand + CHAR(10) + ' ' + @sqlprecommand + CHAR(10) + ' ' + @sqlcommand;
  1700. END;
  1701. /* Print the commands we'll be executing, if specified to do so */
  1702. IF (@debugMode = 1 OR @printCmds = 1) AND @sqlcommand IS NOT NULL
  1703. BEGIN
  1704. RAISERROR(' Printing SQL statements...', 0, 42) WITH NOWAIT;
  1705. SET @debugMessage = ' Executing: ' + CHAR(10) + @debugMessage;
  1706. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1707. END;
  1708. /* Execute default update stats on index only. With better stats, index rebuild process will generally have better performance */
  1709. IF @operationFlag = 1
  1710. BEGIN
  1711. BEGIN TRY
  1712. EXECUTE sp_executesql @sqlprecommand;
  1713. SET @sqlprecommand = NULL
  1714. SET @dateTimeEnd = GETDATE();
  1715. /* Update log with completion time */
  1716. UPDATE dbo.tbl_AdaptiveIndexDefrag_log
  1717. SET dateTimeEnd = @dateTimeEnd, durationSeconds = DATEDIFF(second, @dateTimeStart, @dateTimeEnd)
  1718. WHERE indexDefrag_id = @indexDefrag_id AND dateTimeEnd IS NULL;
  1719. /* If rebuilding, update statistics log with completion time */
  1720. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1721. BEGIN
  1722. 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)
  1723. SELECT @dbID, @dbName, @objectID, @objectName, statsID, statsName, @partitionNumber, -1, -1, -1, [no_recompute], @dateTimeStart, @dateTimeEnd, DATEDIFF(second, @dateTimeStart, @dateTimeEnd), @sqlcommand
  1724. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1725. WHERE objectID = @objectID AND dbID = @dbID
  1726. AND statsName = @indexName
  1727. AND ((@Exec_Print = 1 AND updateDate IS NULL) OR (@Exec_Print = 0 AND updateDate IS NULL AND printStatus = 0));
  1728. END
  1729. ELSE
  1730. BEGIN
  1731. 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)
  1732. SELECT @dbID, @dbName, @objectID, @objectName, statsID, statsName, 1, -1, -1, -1, [no_recompute], @dateTimeStart, @dateTimeEnd, DATEDIFF(second, @dateTimeStart, @dateTimeEnd), @sqlcommand
  1733. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1734. WHERE objectID = @objectID AND dbID = @dbID
  1735. AND statsName = @indexName
  1736. AND ((@Exec_Print = 1 AND updateDate IS NULL) OR (@Exec_Print = 0 AND updateDate IS NULL AND printStatus = 0));
  1737. END
  1738. END TRY
  1739. BEGIN CATCH
  1740. /* Update log with error message */
  1741. UPDATE dbo.tbl_AdaptiveIndexDefrag_log
  1742. 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)) + ')'
  1743. WHERE indexDefrag_id = @indexDefrag_id AND dateTimeEnd IS NULL;
  1744. IF @debugMode = 1
  1745. BEGIN
  1746. 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)) + ')'
  1747. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1748. --RAISERROR(' An error has occurred executing the pre-command! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 0, 42) WITH NOWAIT;
  1749. END
  1750. END CATCH
  1751. END;
  1752. /* Execute NCIX disable command */
  1753. IF @operationFlag = 1 AND @disableNCIX = 1 AND @indexID > 1 AND (@sqldisablecommand IS NOT NULL OR LEN(@sqldisablecommand) > 0)
  1754. BEGIN
  1755. BEGIN TRY
  1756. EXECUTE sp_executesql @sqldisablecommand;
  1757. /* Insert into working table for disabled state control */
  1758. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_IxDisableStatus (dbID, objectID, indexID, [is_disabled], dateTimeChange)
  1759. SELECT @dbID, @objectID, @indexID, 1, GETDATE()
  1760. END TRY
  1761. BEGIN CATCH
  1762. /* Delete from working table for disabled state control */
  1763. DELETE FROM dbo.tbl_AdaptiveIndexDefrag_IxDisableStatus
  1764. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID;
  1765. IF @debugMode = 1
  1766. BEGIN
  1767. 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)) + ')'
  1768. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1769. --RAISERROR(' An error has occurred executing the disable index command! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 0, 42) WITH NOWAIT;
  1770. END
  1771. END CATCH
  1772. END;
  1773. /* Execute defrag! */
  1774. BEGIN TRY
  1775. EXECUTE sp_executesql @sqlcommand;
  1776. SET @dateTimeEnd = GETDATE();
  1777. UPDATE dbo.tbl_AdaptiveIndexDefrag_log
  1778. /* Update log with completion time */
  1779. SET dateTimeEnd = @dateTimeEnd, durationSeconds = DATEDIFF(second, @dateTimeStart, @dateTimeEnd)
  1780. WHERE indexDefrag_id = @indexDefrag_id AND dateTimeEnd IS NULL;
  1781. IF @operationFlag = 1 AND @disableNCIX = 1 AND @indexID > 1
  1782. BEGIN
  1783. /* Delete from working table for disabled state control */
  1784. DELETE FROM dbo.tbl_AdaptiveIndexDefrag_IxDisableStatus
  1785. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID;
  1786. END;
  1787. END TRY
  1788. BEGIN CATCH
  1789. /* Update log with error message */
  1790. UPDATE dbo.tbl_AdaptiveIndexDefrag_log
  1791. 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)) + ')'
  1792. WHERE indexDefrag_id = @indexDefrag_id AND dateTimeEnd IS NULL;
  1793. IF @debugMode = 1
  1794. BEGIN
  1795. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing this command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  1796. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1797. --RAISERROR(' An error has occurred executing this command! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 0, 42) WITH NOWAIT;
  1798. END
  1799. END CATCH
  1800. /* Update working table and resume loop */
  1801. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1802. BEGIN
  1803. UPDATE dbo.tbl_AdaptiveIndexDefrag_Working
  1804. SET defragDate = ISNULL(@dateTimeEnd, GETDATE()), printStatus = 1
  1805. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID AND partitionNumber = @partitionNumber;
  1806. END
  1807. ELSE
  1808. BEGIN
  1809. UPDATE dbo.tbl_AdaptiveIndexDefrag_Working
  1810. SET defragDate = ISNULL(@dateTimeEnd, GETDATE()), printStatus = 1
  1811. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID;
  1812. END
  1813. IF @operationFlag = 1
  1814. BEGIN
  1815. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1816. SET updateDate = ISNULL(@dateTimeEnd, GETDATE()), printStatus = 1
  1817. WHERE objectID = @objectID AND dbID = @dbID AND statsName = @indexName;
  1818. END
  1819. /* Just a little breather for the server */
  1820. WAITFOR DELAY @defragDelay;
  1821. END;
  1822. ELSE IF @Exec_Print = 0
  1823. BEGIN
  1824. IF @operationFlag = 0 AND @sqlprecommand IS NOT NULL
  1825. SET @sqlprecommand = NULL
  1826. IF @sqlprecommand IS NULL AND (@sqldisablecommand IS NULL OR @sqldisablecommand = '')
  1827. BEGIN
  1828. SET @debugMessage = ' ' + @sqlcommand;
  1829. END
  1830. ELSE IF @sqlprecommand IS NOT NULL AND (@sqldisablecommand IS NULL OR @sqldisablecommand = '')
  1831. BEGIN
  1832. SET @debugMessage = ' ' + @sqlprecommand + CHAR(10) + ' ' + @sqlcommand;
  1833. END;
  1834. ELSE IF @sqlprecommand IS NULL AND (@sqldisablecommand IS NOT NULL OR LEN(@sqldisablecommand) > 0)
  1835. BEGIN
  1836. SET @debugMessage = ' ' + @sqldisablecommand + CHAR(10) + ' ' + @sqlcommand;
  1837. END;
  1838. ELSE IF @sqlprecommand IS NOT NULL AND (@sqldisablecommand IS NOT NULL OR LEN(@sqldisablecommand) > 0)
  1839. BEGIN
  1840. SET @debugMessage = ' ' + @sqldisablecommand + CHAR(10) + ' ' + @sqlprecommand + CHAR(10) + ' ' + @sqlcommand;
  1841. END;
  1842. /* Print the commands we're executing if specified to do so */
  1843. IF (@debugMode = 1 OR @printCmds = 1) AND @sqlcommand IS NOT NULL
  1844. BEGIN
  1845. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1846. END
  1847. /* Update working table and resume loop */
  1848. IF @partitionCount > 1 AND @dealMaxPartition IS NOT NULL AND @editionCheck = 1
  1849. BEGIN
  1850. UPDATE dbo.tbl_AdaptiveIndexDefrag_Working
  1851. SET printStatus = 1
  1852. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID AND partitionNumber = @partitionNumber;
  1853. END
  1854. ELSE
  1855. BEGIN
  1856. UPDATE dbo.tbl_AdaptiveIndexDefrag_Working
  1857. SET printStatus = 1
  1858. WHERE dbID = @dbID AND objectID = @objectID AND indexID = @indexID;
  1859. END
  1860. IF @operationFlag = 1
  1861. BEGIN
  1862. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1863. SET printStatus = 1
  1864. WHERE objectID = @objectID AND dbID = @dbID AND statsName = @indexName;
  1865. END;
  1866. END;
  1867. IF @operationFlag = 0 AND @updateStats = 1 -- When reorganizing, update stats afterwards
  1868. AND @updateStatsWhere = 0 AND @ixtype NOT IN (5,6,7)
  1869. BEGIN
  1870. IF @debugMode = 1
  1871. RAISERROR(' Updating index related statistics using finer thresholds (if any)...', 0, 42) WITH NOWAIT;
  1872. /* Handling index related statistics */
  1873. IF @debugMode = 1
  1874. RAISERROR(' Selecting a statistic to update...', 0, 42) WITH NOWAIT;
  1875. /* Select the stat */
  1876. BEGIN TRY
  1877. 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)';
  1878. SET @getStatSQL_Param = N'@statsID_Out int OUTPUT'
  1879. EXECUTE sp_executesql @getStatSQL, @getStatSQL_Param, @statsID_Out = @statsID OUTPUT;
  1880. END TRY
  1881. BEGIN CATCH
  1882. IF @debugMode = 1
  1883. BEGIN
  1884. 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)) + ')'
  1885. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1886. END
  1887. END CATCH
  1888. IF @debugMode = 1
  1889. RAISERROR(' Getting information on selected statistic...', 0, 42) WITH NOWAIT;
  1890. /* Get object name and auto update setting */
  1891. SELECT TOP 1 @statsName = statsName, @partitionNumber = partitionNumber, @stats_norecompute = [no_recompute], @stats_isincremental = [is_incremental]
  1892. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  1893. WHERE objectID = @objectID AND statsID = @statsID AND [dbID] = @dbID;
  1894. IF @debugMode = 1
  1895. BEGIN
  1896. SET @debugMessage = ' Determining modification row counter for statistic ' + @statsName + ' on table or view ' + @objectName + ' of DB ' + @dbName + '...';
  1897. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1898. END;
  1899. /* Determine modification row counter to ascertain if update stats is required */
  1900. IF ((@sqlmajorver = 12 AND @sqlbuild >= 5000) OR (@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13) AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE')
  1901. BEGIN
  1902. IF @debugMode = 1
  1903. RAISERROR(' Using sys.dm_db_incremental_stats_properties DMF...', 0, 42) WITH NOWAIT;
  1904. 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;'
  1905. END
  1906. ELSE IF ((@sqlmajorver = 12 AND @sqlbuild < 5000) OR (@sqlmajorver = 13 AND @sqlbuild < 4000)) AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE')
  1907. BEGIN
  1908. IF @debugMode = 1
  1909. RAISERROR(' Using sys.dm_db_stats_properties_internal DMF...', 0, 42) WITH NOWAIT;
  1910. 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;'
  1911. END
  1912. 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')
  1913. BEGIN
  1914. IF @debugMode = 1
  1915. RAISERROR(' Using sys.dm_db_stats_properties DMF...', 0, 42) WITH NOWAIT;
  1916. 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)) + ');'
  1917. END
  1918. ELSE
  1919. BEGIN
  1920. IF @debugMode = 1
  1921. RAISERROR(' Using sys.sysindexes...', 0, 42) WITH NOWAIT;
  1922. 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;'
  1923. END
  1924. SET @rowmodctrSQL_Param = N'@partitionNumber_In smallint, @rowmodctr_Out bigint OUTPUT, @rows_Out bigint OUTPUT, @rows_sampled_Out bigint OUTPUT'
  1925. BEGIN TRY
  1926. EXECUTE sp_executesql @rowmodctrSQL, @rowmodctrSQL_Param, @partitionNumber_In = @partitionNumber, @rowmodctr_Out = @rowmodctr OUTPUT, @rows_Out = @rows OUTPUT, @rows_sampled_Out = @rows_sampled OUTPUT;
  1927. SET @rowmodctr = (SELECT ISNULL(@rowmodctr, 0));
  1928. END TRY
  1929. BEGIN CATCH
  1930. IF @debugMode = 1
  1931. BEGIN
  1932. 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)) + ')'
  1933. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1934. END
  1935. END CATCH
  1936. IF @rows IS NOT NULL AND @rows > 0
  1937. SET @record_count = @rows
  1938. IF @debugMode = 1
  1939. BEGIN
  1940. 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 + '...';
  1941. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1942. END
  1943. /* Because we are reorganizing, we will update statistics if they have changed since last update with same threshold as TF2371.
  1944. Default rules for auto update stats are:
  1945. If the cardinality for a table is greater than 6, but less than or equal to 500, update status every 500 modifications.
  1946. If the cardinality for a table is greater than 500, update statistics when (500 + 20 percent of the table) changes have occurred.
  1947. Reference: http://support.microsoft.com/kb/195565
  1948. */
  1949. IF (
  1950. (@record_count BETWEEN 6 AND 500 AND @rowmodctr >= 500) OR -- like the default
  1951. (@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
  1952. (@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
  1953. (@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
  1954. (@record_count >= 1000001 AND (@rowmodctr >= (@record_count*5)/100 + 500 OR @rowmodctr >= SQRT(@record_count*1000))) -- 500 + 5 percent or simulate TF 2371
  1955. )
  1956. BEGIN
  1957. SET @sqlcommand2 = N'UPDATE STATISTICS ' + @dbName + N'.'+ @schemaName + N'.' + @objectName + N' (' + @statsName + N')'
  1958. IF UPPER(@statsSample) = 'FULLSCAN' AND (@partitionNumber = 1 OR @partitionNumber = @maxpartitionNumber)
  1959. SET @sqlcommand2 = @sqlcommand2 + N' WITH FULLSCAN'
  1960. ELSE IF UPPER(@statsSample) = 'RESAMPLE'
  1961. SET @sqlcommand2 = @sqlcommand2 + N' WITH RESAMPLE'
  1962. IF @partitionCount > 1 AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE') AND UPPER(@sqlcommand2) LIKE '%WITH%'
  1963. SET @sqlcommand2 = @sqlcommand2 + N' ON PARTITIONS(' + CONVERT(NVARCHAR(10), @partitionNumber) + N');'
  1964. ELSE IF @partitionCount > 1 AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE') AND UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  1965. SET @sqlcommand2 = @sqlcommand2 + N' WITH RESAMPLE ON PARTITIONS(' + CONVERT(NVARCHAR(10), @partitionNumber) + N')'
  1966. IF @stats_norecompute = 1 AND UPPER(@sqlcommand2) LIKE '%WITH%'
  1967. SET @sqlcommand2 = @sqlcommand2 + N' ,NORECOMPUTE'
  1968. ELSE IF @stats_norecompute = 1 AND @sqlcommand2 NOT LIKE '%WITH%'
  1969. SET @sqlcommand2 = @sqlcommand2 + N' WITH NORECOMPUTE'
  1970. /* For list of incremental stats unsupported scenarios check https://msdn.microsoft.com/en-us/library/ms187348.aspx */
  1971. IF @partitionCount > 1 AND @statsIncremental = 1 AND @has_filter = 0
  1972. BEGIN
  1973. IF UPPER(@sqlcommand2) LIKE '%WITH%'
  1974. SET @sqlcommand2 = @sqlcommand2 + N' ,INCREMENTAL = ON'
  1975. ELSE IF UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  1976. SET @sqlcommand2 = @sqlcommand2 + N'WITH INCREMENTAL = ON'
  1977. END
  1978. ELSE IF @statsIncremental = 0
  1979. BEGIN
  1980. IF UPPER(@sqlcommand2) LIKE '%WITH%'
  1981. SET @sqlcommand2 = @sqlcommand2 + N', INCREMENTAL = OFF'
  1982. ELSE IF UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  1983. SET @sqlcommand2 = @sqlcommand2 + N'WITH INCREMENTAL = OFF'
  1984. END
  1985. SET @sqlcommand2 = @sqlcommand2 + N';'
  1986. END
  1987. ELSE
  1988. BEGIN
  1989. SET @sqlcommand2 = NULL
  1990. END
  1991. /* Are we executing the SQL? If so, do it */
  1992. IF @Exec_Print = 1 AND @sqlcommand2 IS NOT NULL
  1993. BEGIN
  1994. SET @debugMessage = ' ' + @sqlcommand2;
  1995. /* Print the commands we'll be executing, if specified to do so */
  1996. IF (@printCmds = 1 OR @debugMode = 1)
  1997. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  1998. /* Get the time for logging purposes */
  1999. SET @dateTimeStart = GETDATE();
  2000. /* Log actions */
  2001. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Stats_log (dbID, dbName, objectID, objectName, statsID, statsName, [partitionNumber], [rows], rows_sampled, modification_counter, [no_recompute], dateTimeStart, sqlStatement)
  2002. SELECT @dbID, @dbName, @objectID, @objectName, @statsID, @statsName, @partitionNumber, @rows, @rows_sampled, @rowmodctr, @stats_norecompute, @dateTimeStart, @sqlcommand2;
  2003. SET @statsUpdate_id = SCOPE_IDENTITY();
  2004. /* Wrap execution attempt in a TRY/CATCH and log any errors that occur */
  2005. IF @operationFlag = 0
  2006. BEGIN
  2007. BEGIN TRY
  2008. /* Execute update! */
  2009. EXECUTE sp_executesql @sqlcommand2;
  2010. SET @dateTimeEnd = GETDATE();
  2011. SET @sqlcommand2 = NULL
  2012. /* Update log with completion time */
  2013. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2014. SET dateTimeEnd = @dateTimeEnd, durationSeconds = DATEDIFF(second, @dateTimeStart, @dateTimeEnd)
  2015. WHERE statsUpdate_id = @statsUpdate_id AND partitionNumber = @partitionNumber AND dateTimeEnd IS NULL;
  2016. /* Update working table */
  2017. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2018. SET updateDate = GETDATE(), printStatus = 1
  2019. WHERE dbID = @dbID AND objectID = @objectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2020. END TRY
  2021. BEGIN CATCH
  2022. /* Update log with error message */
  2023. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2024. 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)) + ')'
  2025. WHERE statsUpdate_id = @statsUpdate_id AND partitionNumber = @partitionNumber AND dateTimeEnd IS NULL;
  2026. /* Update working table */
  2027. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2028. SET updateDate = GETDATE(), printStatus = 1
  2029. WHERE dbID = @dbID AND objectID = @objectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2030. IF @debugMode = 1
  2031. BEGIN
  2032. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing this command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  2033. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2034. --RAISERROR(' An error has occurred executing this command. Please review the tbl_AdaptiveIndexDefrag_Stats_log table for details.', 0, 42) WITH NOWAIT;
  2035. END
  2036. END CATCH
  2037. END
  2038. END
  2039. ELSE IF @Exec_Print = 1 AND @sqlcommand2 IS NULL
  2040. BEGIN
  2041. IF @debugMode = 1
  2042. BEGIN
  2043. 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 + '...';
  2044. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2045. END
  2046. IF @printCmds = 1 AND @debugMode = 0
  2047. BEGIN
  2048. 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 + '...';
  2049. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2050. END
  2051. /* Update working table */
  2052. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2053. SET updateDate = GETDATE(), printStatus = 1
  2054. WHERE dbID = @dbID AND objectID = @objectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2055. END
  2056. ELSE IF @Exec_Print = 0
  2057. BEGIN
  2058. IF @debugMode = 1 AND @sqlcommand2 IS NULL
  2059. BEGIN
  2060. 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 + '...';
  2061. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2062. END
  2063. /* Print the commands we're executing if specified to do so */
  2064. IF (@printCmds = 1 OR @debugMode = 1) AND @sqlcommand2 IS NOT NULL
  2065. BEGIN
  2066. SET @debugMessage = ' ' + @sqlcommand2;
  2067. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2068. END
  2069. IF @printCmds = 1 AND @debugMode = 0 AND @sqlcommand2 IS NULL
  2070. BEGIN
  2071. 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 + '...';
  2072. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2073. END
  2074. /* Update working table */
  2075. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2076. SET printStatus = 1
  2077. WHERE dbID = @dbID AND objectID = @objectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2078. END
  2079. END
  2080. END;
  2081. /* Handling all the other statistics not covered before*/
  2082. IF @updateStats = 1 -- When reorganizing, update stats afterwards
  2083. AND @updateStatsWhere = 0 -- @updateStatsWhere = 0 then table-wide statistics;
  2084. 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
  2085. BEGIN
  2086. IF @debugMode = 1
  2087. RAISERROR(' Updating all other unhandled statistics using finer thresholds (if any)...', 0, 42) WITH NOWAIT;
  2088. 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
  2089. BEGIN
  2090. /* Check to see if we need to exit loop because of our time limit */
  2091. IF ISNULL(@endDateTime, GETDATE()) < GETDATE()
  2092. RAISERROR('Time limit has been exceeded for this maintenance window!', 16, 42) WITH NOWAIT;
  2093. IF @debugMode = 1
  2094. RAISERROR(' Selecting a statistic to update...', 0, 42) WITH NOWAIT;
  2095. /* Select the stat */
  2096. IF @Exec_Print = 1
  2097. BEGIN
  2098. SELECT TOP 1 @statsID = idss.statsID, @dbID = idss.dbID, @statsObjectID = idss.objectID, @dbName = idss.dbName, @statsobjectName = idss.objectName, @statsschemaName = idss.schemaName, @partitionNumber = idss.partitionNumber
  2099. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss
  2100. 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)
  2101. END
  2102. ELSE IF @Exec_Print = 0
  2103. BEGIN
  2104. SELECT TOP 1 @statsID = idss.statsID, @dbID = idss.dbID, @statsObjectID = idss.objectID, @dbName = idss.dbName, @statsobjectName = idss.objectName, @statsschemaName = idss.schemaName, @partitionNumber = idss.partitionNumber
  2105. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working idss
  2106. 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)
  2107. END
  2108. /* Get stat associated table record count */
  2109. BEGIN TRY
  2110. 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'
  2111. SET @getStatSQL_Param = N'@statsID_In int, @dbID_In int, @statsObjectID_In int, @record_count_Out bigint OUTPUT'
  2112. EXECUTE sp_executesql @getStatSQL, @getStatSQL_Param, @statsID_In = @statsID, @dbID_In = @dbID, @statsObjectID_In = @statsObjectID, @record_count_Out = @record_count OUTPUT;
  2113. END TRY
  2114. BEGIN CATCH
  2115. IF @debugMode = 1
  2116. BEGIN
  2117. 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)) + ')'
  2118. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2119. END
  2120. END CATCH
  2121. IF @debugMode = 1
  2122. RAISERROR(' Getting information on selected statistic...', 0, 42) WITH NOWAIT;
  2123. /* Get object name and auto update setting */
  2124. SELECT TOP 1 @statsName = statsName, @stats_norecompute = [no_recompute], @stats_isincremental = [is_incremental]
  2125. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2126. WHERE objectID = @statsObjectID AND statsID = @statsID AND [dbID] = @dbID AND partitionNumber = @partitionNumber;
  2127. IF @debugMode = 1
  2128. BEGIN
  2129. SET @debugMessage = ' Determining modification row counter for statistic ' + @statsName + ' on table or view ' + @statsobjectName + ' of DB ' + @dbName + '...';
  2130. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2131. END
  2132. /* Determine modification row counter to ascertain if update stats is required */
  2133. IF ((@sqlmajorver = 12 AND @sqlbuild >= 5000) OR (@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13) AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE')
  2134. BEGIN
  2135. IF @debugMode = 1
  2136. RAISERROR(' Using sys.dm_db_incremental_stats_properties DMF...', 0, 42) WITH NOWAIT;
  2137. 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;'
  2138. END
  2139. ELSE IF ((@sqlmajorver = 12 AND @sqlbuild < 5000) OR (@sqlmajorver = 13 AND @sqlbuild < 4000)) AND @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE')
  2140. BEGIN
  2141. IF @debugMode = 1
  2142. RAISERROR(' Using sys.dm_db_stats_properties_internal DMF...', 0, 42) WITH NOWAIT;
  2143. 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;'
  2144. END
  2145. 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')
  2146. BEGIN
  2147. IF @debugMode = 1
  2148. RAISERROR(' Using sys.dm_db_stats_properties DMF...', 0, 42) WITH NOWAIT;
  2149. 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)) + ');'
  2150. END
  2151. ELSE
  2152. BEGIN
  2153. IF @debugMode = 1
  2154. RAISERROR(' Using sys.sysindexes...', 0, 42) WITH NOWAIT;
  2155. 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;'
  2156. END
  2157. SET @rowmodctrSQL_Param = N'@partitionNumber_In smallint, @rowmodctr_Out bigint OUTPUT, @rows_Out bigint OUTPUT, @rows_sampled_Out bigint OUTPUT'
  2158. BEGIN TRY
  2159. EXECUTE sp_executesql @rowmodctrSQL, @rowmodctrSQL_Param, @partitionNumber_In = @partitionNumber, @rowmodctr_Out = @rowmodctr OUTPUT, @rows_Out = @rows OUTPUT, @rows_sampled_Out = @rows_sampled OUTPUT;
  2160. SET @rowmodctr = (SELECT ISNULL(@rowmodctr, 0));
  2161. END TRY
  2162. BEGIN CATCH
  2163. IF @debugMode = 1
  2164. BEGIN
  2165. 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)) + ')'
  2166. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2167. END
  2168. END CATCH
  2169. IF @rows IS NOT NULL AND @rows > 0
  2170. SET @record_count = @rows
  2171. IF @debugMode = 1
  2172. BEGIN
  2173. 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 + '...';
  2174. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2175. --select @debugMessage
  2176. END
  2177. /* 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.
  2178. Default rules for auto update stats are:
  2179. If the cardinality for a table is greater than 6, but less than or equal to 500, update status every 500 modifications.
  2180. If the cardinality for a table is greater than 500, update statistics when (500 + 20 percent of the table) changes have occurred.
  2181. */
  2182. IF (
  2183. (@record_count BETWEEN 6 AND 500 AND @rowmodctr >= 500) OR -- like the default
  2184. (@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
  2185. (@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
  2186. (@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
  2187. (@record_count >= 1000001 AND (@rowmodctr >= (@record_count*5)/100 + 500 OR @rowmodctr >= SQRT(@record_count*1000))) -- 500 + 5 percent or simulate TF 2371
  2188. )
  2189. BEGIN
  2190. SET @sqlcommand2 = N'UPDATE STATISTICS ' + @dbName + N'.' + @statsschemaName + N'.' + @statsobjectName + N' (' + @statsName + N')'
  2191. IF UPPER(@statsSample) = 'FULLSCAN' AND (@partitionNumber = 1 OR @partitionNumber = @maxpartitionNumber)
  2192. SET @sqlcommand2 = @sqlcommand2 + N' WITH FULLSCAN'
  2193. ELSE IF UPPER(@statsSample) = 'RESAMPLE'
  2194. SET @sqlcommand2 = @sqlcommand2 + N' WITH RESAMPLE'
  2195. IF @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE') AND UPPER(@sqlcommand2) LIKE '%WITH%'
  2196. SET @sqlcommand2 = @sqlcommand2 + N' ON PARTITIONS(' + CONVERT(NVARCHAR(10), @partitionNumber) + N');'
  2197. ELSE IF @stats_isincremental = 1 AND (@statsSample IS NULL OR UPPER(@statsSample) = 'RESAMPLE') AND UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  2198. SET @sqlcommand2 = @sqlcommand2 + N' WITH RESAMPLE ON PARTITIONS(' + CONVERT(NVARCHAR(10), @partitionNumber) + N')'
  2199. IF @stats_norecompute = 1 AND UPPER(@sqlcommand2) LIKE '%WITH%'
  2200. SET @sqlcommand2 = @sqlcommand2 + N' ,NORECOMPUTE'
  2201. ELSE IF @stats_norecompute = 1 AND UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  2202. SET @sqlcommand2 = @sqlcommand2 + N' WITH NORECOMPUTE'
  2203. /* For list of incremental stats unsupported scenarios check https://msdn.microsoft.com/en-us/library/ms187348.aspx */
  2204. IF @partitionCount > 1 AND @statsIncremental = 1 AND @has_filter = 0
  2205. BEGIN
  2206. IF UPPER(@sqlcommand2) LIKE '%WITH%'
  2207. SET @sqlcommand2 = @sqlcommand2 + N' ,INCREMENTAL = ON'
  2208. ELSE IF UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  2209. SET @sqlcommand2 = @sqlcommand2 + N'WITH INCREMENTAL = ON'
  2210. END
  2211. ELSE IF @statsIncremental = 0
  2212. BEGIN
  2213. IF UPPER(@sqlcommand2) LIKE '%WITH%'
  2214. SET @sqlcommand2 = @sqlcommand2 + N', INCREMENTAL = OFF'
  2215. ELSE IF UPPER(@sqlcommand2) NOT LIKE '%WITH%'
  2216. SET @sqlcommand2 = @sqlcommand2 + N'WITH INCREMENTAL = OFF'
  2217. END
  2218. SET @sqlcommand2 = @sqlcommand2 + N';'
  2219. END
  2220. ELSE
  2221. BEGIN
  2222. SET @sqlcommand2 = NULL
  2223. END;
  2224. /* Are we executing the SQL? If so, do it */
  2225. IF @Exec_Print = 1 AND @sqlcommand2 IS NOT NULL
  2226. BEGIN
  2227. SET @debugMessage = ' ' + @sqlcommand2;
  2228. /* Print the commands we're executing if specified to do so */
  2229. IF (@printCmds = 1 OR @debugMode = 1)
  2230. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2231. /* Get the time for logging purposes */
  2232. SET @dateTimeStart = GETDATE();
  2233. /* Log actions */
  2234. INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Stats_log (dbID, dbName, objectID, objectName, statsID, statsName, [partitionNumber], [rows], rows_sampled, modification_counter, [no_recompute], dateTimeStart, sqlStatement)
  2235. SELECT @dbID, @dbName, @objectID, @objectName, @statsID, @statsName, @partitionNumber, @rows, @rows_sampled, @rowmodctr, @stats_norecompute, @dateTimeStart, @sqlcommand2;
  2236. SET @statsUpdate_id = SCOPE_IDENTITY();
  2237. /* Wrap execution attempt in a TRY/CATCH and log any errors that occur */
  2238. BEGIN TRY
  2239. /* Execute update! */
  2240. EXECUTE sp_executesql @sqlcommand2;
  2241. SET @dateTimeEnd = GETDATE();
  2242. SET @sqlcommand2 = NULL
  2243. /* Update log with completion time */
  2244. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2245. SET dateTimeEnd = @dateTimeEnd, durationSeconds = DATEDIFF(second, @dateTimeStart, @dateTimeEnd)
  2246. WHERE statsUpdate_id = @statsUpdate_id AND partitionNumber = @partitionNumber AND dateTimeEnd IS NULL;
  2247. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2248. SET updateDate = GETDATE(), printStatus = 1
  2249. WHERE dbID = @dbID AND objectID = @statsObjectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2250. END TRY
  2251. BEGIN CATCH
  2252. /* Update log with error message */
  2253. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2254. 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)) + ')'
  2255. WHERE statsUpdate_id = @statsUpdate_id AND partitionNumber = @partitionNumber AND dateTimeEnd IS NULL;
  2256. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2257. SET updateDate = GETDATE(), printStatus = 1
  2258. WHERE dbID = @dbID AND objectID = @statsObjectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2259. IF @debugMode = 1
  2260. BEGIN
  2261. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred executing this command. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  2262. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2263. --RAISERROR(' An error has occurred executing this command. Please review the tbl_AdaptiveIndexDefrag_Stats_log table for details.', 0, 42) WITH NOWAIT;
  2264. END
  2265. END CATCH
  2266. END
  2267. ELSE IF @Exec_Print = 1 AND @sqlcommand2 IS NULL
  2268. BEGIN
  2269. IF @debugMode = 1
  2270. BEGIN
  2271. 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 + '...';
  2272. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2273. END
  2274. IF @printCmds = 1 AND @debugMode = 0
  2275. BEGIN
  2276. 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 + '...';
  2277. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2278. END
  2279. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2280. SET updateDate = GETDATE(), printStatus = 1
  2281. WHERE dbID = @dbID AND objectID = @statsObjectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2282. END
  2283. ELSE IF @Exec_Print = 0
  2284. BEGIN
  2285. IF @debugMode = 1 AND @sqlcommand2 IS NULL
  2286. BEGIN
  2287. 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 + '...';
  2288. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2289. END
  2290. /* Print the commands we're executing if specified to do so */
  2291. IF (@printCmds = 1 OR @debugMode = 1) AND @sqlcommand2 IS NOT NULL
  2292. BEGIN
  2293. SET @debugMessage = ' ' + @sqlcommand2;
  2294. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2295. END
  2296. IF @printCmds = 1 AND @debugMode = 0 AND @sqlcommand2 IS NULL
  2297. BEGIN
  2298. 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 + '...';
  2299. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2300. END
  2301. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2302. SET printStatus = 1
  2303. WHERE dbID = @dbID AND objectID = @statsObjectID AND statsID = @statsID AND partitionNumber = @partitionNumber;
  2304. END
  2305. END
  2306. IF (@printCmds = 1 OR @debugMode = 1)
  2307. PRINT ' No remaining statistics to update...';
  2308. END
  2309. ELSE
  2310. BEGIN
  2311. IF (@printCmds = 1 OR @debugMode = 1)
  2312. PRINT ' No remaining statistics to update...';
  2313. END
  2314. /* Output results? */
  2315. IF @outputResults = 1 AND @Exec_Print = 1
  2316. BEGIN
  2317. IF (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Working WHERE defragDate >= @startDateTime) > 0
  2318. OR (SELECT COUNT(*) FROM tbl_AdaptiveIndexDefrag_Stats_Working WHERE updateDate >= @startDateTime) > 0
  2319. BEGIN
  2320. IF @debugMode = 1
  2321. RAISERROR(' Displaying a summary of our actions...', 0, 42) WITH NOWAIT;
  2322. SELECT [dbName], objectName, indexName, partitionNumber, CONVERT(decimal(9,2),fragmentation) AS fragmentation, page_count, fill_factor, range_scan_count, defragDate
  2323. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2324. WHERE defragDate >= @startDateTime
  2325. ORDER BY defragDate;
  2326. SELECT [dbName], [statsName], partitionNumber, [no_recompute], [is_incremental], updateDate
  2327. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2328. WHERE updateDate >= @startDateTime
  2329. ORDER BY updateDate;
  2330. IF @debugMode = 1 AND (SELECT COUNT(*) FROM dbo.tbl_AdaptiveIndexDefrag_log WHERE errorMessage IS NOT NULL AND dateTimeStart >= @startDateTime) > 0
  2331. BEGIN
  2332. RAISERROR('Displaying a summary of all errors...', 0, 42) WITH NOWAIT;
  2333. SELECT dbName, objectName, indexName, partitionNumber, dateTimeStart, dateTimeEnd, sqlStatement, errorMessage
  2334. FROM dbo.tbl_AdaptiveIndexDefrag_log
  2335. WHERE errorMessage IS NOT NULL AND dateTimeStart >= @startDateTime
  2336. ORDER BY dateTimeStart;
  2337. END
  2338. IF @debugMode = 1
  2339. RAISERROR(' Displaying some statistical information about this defragmentation run...', 0, 42) WITH NOWAIT;
  2340. SELECT TOP 10 'Longest time' AS Comment, dbName, objectName, indexName, partitionNumber, dateTimeStart, dateTimeEnd, durationSeconds
  2341. FROM dbo.tbl_AdaptiveIndexDefrag_log
  2342. WHERE dateTimeStart >= @startDateTime
  2343. ORDER BY durationSeconds DESC;
  2344. END
  2345. END;
  2346. END TRY
  2347. BEGIN CATCH
  2348. SET @debugMessage = ' Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ' has occurred. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')'
  2349. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2350. END CATCH;
  2351. /* Reset printStatus */
  2352. IF @debugMode = 1
  2353. RAISERROR(' Reseting working table statuses.', 0, 42) WITH NOWAIT;
  2354. UPDATE dbo.tbl_AdaptiveIndexDefrag_Working
  2355. SET printStatus = 0;
  2356. UPDATE dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2357. SET printStatus = 0;
  2358. /* Drop all temp tables */
  2359. IF @debugMode = 1
  2360. RAISERROR(' Droping temporary objects', 0, 42) WITH NOWAIT;
  2361. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragDatabaseList'))
  2362. DROP TABLE #tblIndexDefragDatabaseList;
  2363. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragmaxPartitionList'))
  2364. DROP TABLE #tblIndexDefragmaxPartitionList;
  2365. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexDefragScanWorking'))
  2366. DROP TABLE #tblIndexDefragScanWorking;
  2367. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIndexFindInDatabaseList'))
  2368. DROP TABLE #tblIndexFindInDatabaseList;
  2369. IF @debugMode = 1
  2370. RAISERROR('All done!', 0, 42) WITH NOWAIT;
  2371. IF @Exec_Print = 0
  2372. BEGIN
  2373. IF @ignoreDropObj = 0
  2374. BEGIN
  2375. IF (SELECT COUNT([errorMessage]) FROM dbo.vw_LastRun_Log) > 0 AND @ignoreDropObj = 0
  2376. BEGIN
  2377. RAISERROR('Defrag job found execution errors! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 16, 42) WITH NOWAIT;
  2378. RETURN -1
  2379. END
  2380. ELSE
  2381. BEGIN
  2382. RETURN 0
  2383. END
  2384. END
  2385. ELSE
  2386. BEGIN
  2387. IF (SELECT COUNT([errorMessage]) FROM dbo.vw_LastRun_Log WHERE [errorMessage] NOT LIKE 'Table%does not exist%') > 0
  2388. BEGIN
  2389. RAISERROR('Defrag job found execution errors! Please review the tbl_AdaptiveIndexDefrag_log table for details.', 16, 42) WITH NOWAIT;
  2390. RETURN -1
  2391. END
  2392. ELSE
  2393. BEGIN
  2394. RETURN 0
  2395. END
  2396. END
  2397. END
  2398. END
  2399. GO
  2400. --EXEC sys.sp_MS_marksystemobject 'usp_AdaptiveIndexDefrag'
  2401. --GO
  2402. PRINT 'Procedure usp_AdaptiveIndexDefrag created';
  2403. GO
  2404. ------------------------------------------------------------------------------------------------------------------------------
  2405. CREATE VIEW vw_ErrLst30Days
  2406. AS
  2407. SELECT TOP 100 PERCENT dbName, objectName, indexName, partitionNumber, NULL AS statsName, dateTimeStart, dateTimeEnd, sqlStatement, errorMessage
  2408. FROM dbo.tbl_AdaptiveIndexDefrag_log
  2409. WHERE errorMessage IS NOT NULL AND dateTimeStart >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2410. UNION ALL
  2411. SELECT TOP 100 PERCENT dbName, objectName, NULL AS indexName, NULL AS partitionNumber, statsName, dateTimeStart, dateTimeEnd, sqlStatement, errorMessage
  2412. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2413. WHERE errorMessage IS NOT NULL AND dateTimeStart >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2414. ORDER BY dateTimeStart;
  2415. GO
  2416. CREATE VIEW vw_ErrLst24Hrs
  2417. AS
  2418. SELECT TOP 100 PERCENT dbName, objectName, indexName, partitionNumber, NULL AS statsName, dateTimeStart, dateTimeEnd, sqlStatement, errorMessage
  2419. FROM dbo.tbl_AdaptiveIndexDefrag_log
  2420. WHERE errorMessage IS NOT NULL AND dateTimeStart >= DATEADD(hh, -24, GETDATE())
  2421. UNION ALL
  2422. SELECT TOP 100 PERCENT dbName, objectName, NULL AS indexName, NULL AS partitionNumber, statsName, dateTimeStart, dateTimeEnd, sqlStatement, errorMessage
  2423. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2424. WHERE errorMessage IS NOT NULL AND dateTimeStart >= DATEADD(hh, -24, GETDATE())
  2425. ORDER BY dateTimeStart;
  2426. GO
  2427. CREATE VIEW vw_AvgTimeLst30Days
  2428. AS
  2429. SELECT TOP 100 PERCENT 'Longest time' AS Comment, dbName, objectName, indexName, partitionNumber, AVG(durationSeconds) AS Avg_durationSeconds
  2430. FROM dbo.tbl_AdaptiveIndexDefrag_log
  2431. WHERE dateTimeStart >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2432. GROUP BY dbName, objectName, indexName, partitionNumber
  2433. ORDER BY AVG(durationSeconds) DESC, dbName, objectName, indexName, partitionNumber;
  2434. GO
  2435. CREATE VIEW vw_AvgFragLst30Days
  2436. AS
  2437. SELECT TOP 100 PERCENT 'Most fragmented' AS Comment, dbName, objectName, indexName, partitionNumber, CONVERT(decimal(9,2),AVG(fragmentation)) AS Avg_fragmentation
  2438. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2439. WHERE defragDate >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2440. GROUP BY dbName, objectName, indexName, partitionNumber
  2441. ORDER BY AVG(fragmentation) DESC, dbName, objectName, indexName, partitionNumber;
  2442. GO
  2443. CREATE VIEW vw_AvgLargestLst30Days
  2444. AS
  2445. SELECT TOP 100 PERCENT 'Largest' AS Comment, dbName, objectName, indexName, partitionNumber, AVG(page_count)*8 AS Avg_size_KB, fill_factor
  2446. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2447. WHERE defragDate >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2448. GROUP BY dbName, objectName, indexName, partitionNumber, fill_factor
  2449. ORDER BY AVG(page_count) DESC, dbName, objectName, indexName, partitionNumber
  2450. GO
  2451. CREATE VIEW vw_AvgMostUsedLst30Days
  2452. AS
  2453. SELECT TOP 100 PERCENT 'Most used' AS Comment, dbName, objectName, indexName, partitionNumber, AVG(range_scan_count) AS Avg_range_scan_count
  2454. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2455. WHERE defragDate >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -30)
  2456. GROUP BY dbName, objectName, indexName, partitionNumber
  2457. ORDER BY AVG(range_scan_count) DESC;
  2458. GO
  2459. CREATE VIEW vw_LastRun_Log
  2460. AS
  2461. SELECT TOP 100 percent [dbName]
  2462. ,[objectName]
  2463. ,[indexName]
  2464. , NULL AS [statsName]
  2465. ,[partitionNumber]
  2466. ,[fragmentation]
  2467. ,[page_count]
  2468. ,[range_scan_count]
  2469. ,[dateTimeStart]
  2470. ,[dateTimeEnd]
  2471. ,[durationSeconds]
  2472. ,CASE WHEN [sqlStatement] LIKE '%REORGANIZE%' THEN 'Reorg' ELSE 'Rebuild' END AS [Operation]
  2473. ,[errorMessage]
  2474. FROM dbo.tbl_AdaptiveIndexDefrag_log ixlog
  2475. CROSS APPLY (SELECT TOP 1 minIxDate = CASE WHEN defragDate IS NULL THEN CONVERT(DATETIME, CONVERT(NVARCHAR, scanDate, 112))
  2476. ELSE CONVERT(DATETIME, CONVERT(NVARCHAR, defragDate, 112)) END
  2477. FROM [dbo].[tbl_AdaptiveIndexDefrag_Working]
  2478. ORDER BY defragDate ASC, scanDate ASC) AS minDateIxCte
  2479. WHERE dateTimeStart >= minIxDate
  2480. UNION ALL
  2481. SELECT TOP 100 percent [dbName]
  2482. ,[objectName]
  2483. ,NULL AS [indexName]
  2484. ,[statsName]
  2485. ,NULL AS [partitionNumber]
  2486. ,NULL AS [fragmentation]
  2487. ,NULL AS [page_count]
  2488. ,NULL AS [range_scan_count]
  2489. ,[dateTimeStart]
  2490. ,[dateTimeEnd]
  2491. ,[durationSeconds]
  2492. ,'UpdateStats' AS [Operation]
  2493. ,[errorMessage]
  2494. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_log statlog
  2495. CROSS APPLY (SELECT TOP 1 minStatDate = CASE WHEN updateDate IS NULL THEN CONVERT(DATETIME, CONVERT(NVARCHAR, scanDate, 112))
  2496. ELSE CONVERT(DATETIME, CONVERT(NVARCHAR, updateDate, 112)) END
  2497. FROM [dbo].[tbl_AdaptiveIndexDefrag_Stats_Working]
  2498. ORDER BY updateDate ASC, scanDate ASC) AS minDateStatCte
  2499. WHERE dateTimeStart >= minStatDate
  2500. ORDER BY dateTimeEnd ASC
  2501. GO
  2502. PRINT 'Reporting views created';
  2503. GO
  2504. ------------------------------------------------------------------------------------------------------------------------------
  2505. CREATE PROCEDURE usp_AdaptiveIndexDefrag_PurgeLogs @daystokeep smallint = 90
  2506. AS
  2507. /*
  2508. usp_AdaptiveIndexDefrag_PurgeLogs.sql - [email protected] (http://blogs.msdn.com/b/blogdoezequiel/)
  2509. Purge log tables to avoid indefinite growth.
  2510. Default is data older than 90 days.
  2511. Change @daystokeep as you deem fit.
  2512. */
  2513. SET NOCOUNT ON;
  2514. SET DATEFORMAT ymd;
  2515. DELETE FROM dbo.tbl_AdaptiveIndexDefrag_log
  2516. WHERE dateTimeStart <= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -@daystokeep);
  2517. DELETE FROM dbo.tbl_AdaptiveIndexDefrag_Stats_log
  2518. WHERE dateTimeStart <= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -@daystokeep);
  2519. GO
  2520. --EXEC sys.sp_MS_marksystemobject 'usp_AdaptiveIndexDefrag_PurgeLogs'
  2521. --GO
  2522. PRINT 'Procedure usp_AdaptiveIndexDefrag_PurgeLogs created (Default purge is 90 days old)';
  2523. GO
  2524. ------------------------------------------------------------------------------------------------------------------------------
  2525. CREATE PROCEDURE usp_AdaptiveIndexDefrag_CurrentExecStats @dbname NVARCHAR(255) = NULL
  2526. AS
  2527. /*
  2528. usp_AdaptiveIndexDefrag_CurrentExecStats.sql - [email protected] (http://blogs.msdn.com/b/blogdoezequiel/)
  2529. Allows monitoring of what has been done so far in the defrag loop.
  2530. Use @dbname to monitor a specific database
  2531. Example:
  2532. EXEC usp_AdaptiveIndexDefrag_CurrentExecStats @dbname = 'AdventureWorks2008R2'
  2533. */
  2534. SET NOCOUNT ON;
  2535. IF @dbname IS NULL
  2536. BEGIN
  2537. WITH cte1 ([Database_Name], Total_indexes) AS (SELECT [dbName], COUNT(indexID) AS Total_Indexes FROM dbo.tbl_AdaptiveIndexDefrag_Working GROUP BY [dbName]),
  2538. 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]),
  2539. cte3 ([Database_Name], Total_statistics) AS (SELECT [dbName], COUNT(statsID) AS Total_statistics FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working GROUP BY [dbName]),
  2540. 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])
  2541. SELECT cte1.[Database_Name], SUM(cte1.Total_indexes) AS Total_indexes, SUM(ISNULL(cte2.Defraged_Indexes, 0)) AS Defraged_Indexes,
  2542. SUM(cte3.Total_statistics) AS Total_statistics, SUM(ISNULL(cte4.Updated_statistics, 0)) AS Updated_statistics
  2543. FROM cte1 INNER JOIN cte3 ON cte1.Database_Name = cte3.Database_Name
  2544. LEFT JOIN cte2 ON cte1.Database_Name = cte2.Database_Name
  2545. LEFT JOIN cte4 ON cte1.Database_Name = cte4.Database_Name
  2546. GROUP BY cte1.[Database_Name];
  2547. SELECT 'Index' AS [Type], 'Done' AS [Result], dbName, objectName, indexName
  2548. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2549. WHERE defragDate IS NOT NULL OR printStatus = 1
  2550. UNION ALL
  2551. SELECT 'Index' AS [Type], 'To do' AS [Result], dbName, objectName, indexName
  2552. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2553. WHERE defragDate IS NULL AND printStatus = 0
  2554. ORDER BY 2, dbName, objectName, indexName;
  2555. SELECT 'Statistic' AS [Type], 'Done' AS [Result], dbName, objectName, statsName
  2556. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2557. WHERE updateDate IS NOT NULL OR printStatus = 1
  2558. UNION ALL
  2559. SELECT 'Statistic' AS [Type], 'To do' AS [Result], dbName, objectName, statsName
  2560. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2561. WHERE updateDate IS NULL AND printStatus = 0
  2562. ORDER BY 2, dbName, objectName, statsName;
  2563. END
  2564. ELSE
  2565. BEGIN
  2566. 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]),
  2567. 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]),
  2568. 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]),
  2569. 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])
  2570. SELECT cte1.[Database_Name], SUM(cte1.Total_indexes) AS Total_indexes, SUM(ISNULL(cte2.Defraged_Indexes, 0)) AS Defraged_Indexes,
  2571. SUM(cte3.Total_statistics) AS Total_statistics, SUM(ISNULL(cte4.Updated_statistics, 0)) AS Updated_statistics
  2572. FROM cte1 INNER JOIN cte3 ON cte1.Database_Name = cte3.Database_Name
  2573. LEFT JOIN cte2 ON cte1.Database_Name = cte2.Database_Name
  2574. LEFT JOIN cte4 ON cte1.Database_Name = cte4.Database_Name
  2575. GROUP BY cte1.[Database_Name];
  2576. SELECT 'Index' AS [Type], 'Done' AS [Result], dbName, objectName, indexName, partitionNumber
  2577. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2578. WHERE [dbName] = QUOTENAME(@dbname) AND (defragDate IS NOT NULL OR printStatus = 1)
  2579. UNION ALL
  2580. SELECT 'Index' AS [Type], 'To do' AS [Result], dbName, objectName, indexName, partitionNumber
  2581. FROM dbo.tbl_AdaptiveIndexDefrag_Working
  2582. WHERE [dbName] = QUOTENAME(@dbname) AND defragDate IS NULL AND printStatus = 0
  2583. ORDER BY 2, dbName, objectName, indexName;
  2584. SELECT 'Statistic' AS [Type], 'Done' AS [Result], dbName, objectName, statsName
  2585. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2586. WHERE [dbName] = QUOTENAME(@dbname) AND ([updateDate] IS NOT NULL OR printStatus = 1)
  2587. UNION ALL
  2588. SELECT 'Statistic' AS [Type], 'To do' AS [Result], dbName, objectName, statsName
  2589. FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working
  2590. WHERE [dbName] = QUOTENAME(@dbname) AND [updateDate] IS NULL AND printStatus = 0
  2591. ORDER BY 2, dbName, objectName, statsName;
  2592. END
  2593. GO
  2594. --EXEC sys.sp_MS_marksystemobject 'usp_AdaptiveIndexDefrag_CurrentExecStats'
  2595. --GO
  2596. PRINT 'Procedure usp_AdaptiveIndexDefrag_CurrentExecStats created (Use this to monitor defrag loop progress)';
  2597. GO
  2598. ------------------------------------------------------------------------------------------------------------------------------
  2599. CREATE PROCEDURE usp_AdaptiveIndexDefrag_Exceptions @exceptionMask_DB NVARCHAR(255) = NULL,
  2600. @exceptionMask_days NVARCHAR(27) = NULL,
  2601. @exceptionMask_tables NVARCHAR(500) = NULL,
  2602. @exceptionMask_indexes NVARCHAR(500) = NULL
  2603. AS
  2604. /*
  2605. usp_AdaptiveIndexDefrag_Exceptions.sql - [email protected] (http://blogs.msdn.com/b/blogdoezequiel/)
  2606. To insert info into the Exceptions table, use the following guidelines:
  2607. For @exceptionMask_DB, enter only one database name at a time.
  2608. For @exceptionMask_days, enter weekdays in short form, between commas.
  2609. * NOTE: Keep only the weekdays you DO NOT WANT to ALLOW defrag. *
  2610. Order is not mandatory, but weekday short names are important AS IS ('Sun,Mon,Tue,Wed,Thu,Fri,Sat').
  2611. * NOTE: If you WANT to NEVER allow defrag, set as NULL or leave blank *
  2612. For @exceptionMask_tables (optional) enter table names separated by commas ('table_name_1, table_name_2, table_name_3').
  2613. For @exceptionMask_indexes (optional) enter index names separated by commas ('index_name_1, index_name_2, index_name_3').
  2614. If you want to exclude all indexes in a given table, enter its name but don't add index names.
  2615. Example:
  2616. EXEC usp_AdaptiveIndexDefrag_Exceptions @exceptionMask_DB = 'AdventureWorks2008R2',
  2617. @exceptionMask_days = 'Mon,Wed',
  2618. @exceptionMask_tables = 'Employee',
  2619. @exceptionMask_indexes = 'AK_Employee_LoginID'
  2620. */
  2621. SET NOCOUNT ON;
  2622. IF @exceptionMask_DB IS NULL OR QUOTENAME(@exceptionMask_DB) NOT IN (SELECT QUOTENAME(name) FROM master.sys.sysdatabases)
  2623. RAISERROR('Syntax error. Please input a valid database name.', 15, 42) WITH NOWAIT;
  2624. IF @exceptionMask_days IS NOT NULL AND
  2625. (@exceptionMask_days NOT LIKE '___' AND
  2626. @exceptionMask_days NOT LIKE '___,___' AND
  2627. @exceptionMask_days NOT LIKE '___,___,___' AND
  2628. @exceptionMask_days NOT LIKE '___,___,___,___' AND
  2629. @exceptionMask_days NOT LIKE '___,___,___,___,___' AND
  2630. @exceptionMask_days NOT LIKE '___,___,___,___,___,___' AND
  2631. @exceptionMask_days NOT LIKE '___,___,___,___,___,___,___')
  2632. RAISERROR('Syntax error. Please input weekdays in short form, between commas, or leave NULL to always exclude.', 15, 42) WITH NOWAIT;
  2633. IF @exceptionMask_days LIKE '[___,___,___,___,___,___,___]'
  2634. RAISERROR('Warning. You chose to permanently exclude a table and/or index from being defragmented.', 0, 42) WITH NOWAIT;
  2635. IF @exceptionMask_tables IS NOT NULL AND @exceptionMask_tables LIKE '%.%'
  2636. RAISERROR('Syntax error. Please do not input schema with table name(s).', 15, 42) WITH NOWAIT;
  2637. DECLARE @debugMessage NVARCHAR(4000), @sqlcmd NVARCHAR(4000), @sqlmajorver int
  2638. /* Find sql server version */
  2639. SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  2640. BEGIN TRY
  2641. --Always exclude from defrag?
  2642. IF @exceptionMask_days IS NULL OR @exceptionMask_days = ''
  2643. BEGIN
  2644. SET @exceptionMask_days = 127
  2645. END
  2646. ELSE
  2647. BEGIN
  2648. -- 1=Sunday, 2=Monday, 4=Tuesday, 8=Wednesday, 16=Thursday, 32=Friday, 64=Saturday, 127=AllWeek
  2649. 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);
  2650. END
  2651. --Just get everything as it should be
  2652. SET @exceptionMask_tables = CHAR(39) + REPLACE(REPLACE(@exceptionMask_tables, ' ', ''),',', CHAR(39) + ',' + CHAR(39)) + CHAR(39)
  2653. SET @exceptionMask_indexes = CHAR(39) + REPLACE(REPLACE(@exceptionMask_indexes, ' ', ''),',', CHAR(39) + ',' + CHAR(39)) + CHAR(39)
  2654. --Get the exceptions insert command
  2655. IF @sqlmajorver > 9
  2656. BEGIN
  2657. SELECT @sqlcmd = 'MERGE dbo.tbl_AdaptiveIndexDefrag_Exceptions AS target
  2658. USING (SELECT ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB)) + ' AS dbID, si.[object_id] AS objectID, si.index_id AS indexID,
  2659. ''' + @exceptionMask_DB + ''' AS dbName, OBJECT_NAME(si.[object_id], ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB)) + ') AS objectName, si.[name] AS indexName,
  2660. ' + CONVERT(NVARCHAR,@exceptionMask_days) + ' AS exclusionMask
  2661. FROM ' + QUOTENAME(@exceptionMask_DB) + '.sys.indexes si
  2662. INNER JOIN ' + QUOTENAME(@exceptionMask_DB) + '.sys.objects so ON si.object_id = so.object_id
  2663. WHERE so.is_ms_shipped = 0 AND si.index_id > 0 AND si.is_hypothetical = 0
  2664. AND si.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + @exceptionMask_DB + '].sys.internal_tables AS sit)' -- Exclude Heaps, Internal and Hypothetical objects
  2665. + 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
  2666. + CASE WHEN @exceptionMask_indexes IS NOT NULL THEN ' AND si.[name] IN (' + @exceptionMask_indexes + ')' ELSE '' END
  2667. + ') AS source
  2668. ON (target.[dbID] = source.[dbID] AND target.objectID = source.objectID AND target.indexID = source.indexID)
  2669. WHEN MATCHED THEN
  2670. UPDATE SET exclusionMask = source.exclusionMask
  2671. WHEN NOT MATCHED THEN
  2672. INSERT (dbID, objectID, indexID, dbName, objectName, indexName, exclusionMask)
  2673. VALUES (source.dbID, source.objectID, source.indexID, source.dbName, source.objectName, source.indexName, source.exclusionMask);';
  2674. END
  2675. ELSE
  2676. BEGIN
  2677. SELECT @sqlcmd = 'DELETE FROM dbo.tbl_AdaptiveIndexDefrag_Exceptions
  2678. WHERE dbID = ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB))
  2679. + CASE WHEN @exceptionMask_tables IS NOT NULL THEN ' AND [objectName] IN (' + @exceptionMask_tables + ')' ELSE '' END
  2680. + CASE WHEN @exceptionMask_indexes IS NOT NULL THEN ' AND [indexName] IN (' + @exceptionMask_indexes + ');' ELSE ';' END +
  2681. 'INSERT INTO dbo.tbl_AdaptiveIndexDefrag_Exceptions
  2682. SELECT ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB)) + ' AS dbID, si.[object_id] AS objectID, si.index_id AS indexID,
  2683. ''' + @exceptionMask_DB + ''' AS dbName, OBJECT_NAME(si.[object_id], ' + CONVERT(NVARCHAR,DB_ID(@exceptionMask_DB)) + ') AS objectName, si.[name] AS indexName,
  2684. ' + CONVERT(NVARCHAR,@exceptionMask_days) + ' AS exclusionMask
  2685. FROM ' + QUOTENAME(@exceptionMask_DB) + '.sys.indexes si
  2686. INNER JOIN ' + QUOTENAME(@exceptionMask_DB) + '.sys.objects so ON si.object_id = so.object_id
  2687. WHERE so.is_ms_shipped = 0 AND si.index_id > 0 AND si.is_hypothetical = 0
  2688. AND si.[object_id] NOT IN (SELECT sit.[object_id] FROM [' + @exceptionMask_DB + '].sys.internal_tables AS sit)' -- Exclude Heaps, Internal and Hypothetical objects
  2689. + 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
  2690. + CASE WHEN @exceptionMask_indexes IS NOT NULL THEN ' AND si.[name] IN (' + @exceptionMask_indexes + ')' ELSE '' END;
  2691. END;
  2692. EXEC sp_executesql @sqlcmd;
  2693. END TRY
  2694. BEGIN CATCH
  2695. SET @debugMessage = 'Error ' + CONVERT(NVARCHAR(20),ERROR_NUMBER()) + ': ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS NVARCHAR(10)) + ')';
  2696. RAISERROR(@debugMessage, 0, 42) WITH NOWAIT;
  2697. END CATCH;
  2698. GO
  2699. --EXEC sys.sp_MS_marksystemobject 'usp_AdaptiveIndexDefrag_Exceptions'
  2700. --GO
  2701. 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)';
  2702. PRINT 'All done!'
  2703. GO