2_usp_AdaptiveIndexDefrag.sql 169 KB

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