usp_AdaptiveIndexDefrag.sql 195 KB

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