usp_AdaptiveIndexDefrag.sql 194 KB

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