2_usp_AdaptiveIndexDefrag.sql 169 KB

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