2_usp_AdaptiveIndexDefrag.sql 172 KB

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