usp_AdaptiveIndexDefrag.sql 194 KB

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