2_usp_AdaptiveIndexDefrag.sql 174 KB

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