usp_AdaptiveIndexDefrag.sql 172 KB

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