Check_BP_Servers.sql 777 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142
  1. USE [master]
  2. GO
  3. DECLARE @custompath NVARCHAR(500), @allow_xpcmdshell bit, @ptochecks bit, @duration tinyint, @logdetail bit, @diskfrag bit, @ixfrag bit, @ixfragscanmode VARCHAR(8), @bpool_consumer bit, @gen_scripts bit, @dbScope VARCHAR(256), @spn_check bit
  4. /* Best Practices Check - [email protected] (http://aka.ms/BPCheck; http://aka.ms/sqlinsights)
  5. READ ME - Important options for executing BPCheck
  6. Set @duration to the number of seconds between data collection points regarding perf counters, waits and latches.
  7. Duration must be between 10s and 255s (4m 15s), with a default of 90s.
  8. Set @ptochecks to OFF if you want to skip more performance tuning and optimization oriented checks.
  9. Uncomment @custompath below and set the custom desired path for .ps1 files.
  10. If not, default location for .ps1 files is the Log folder.
  11. Set @allow_xpcmdshell to OFF if you want to skip checks that are dependant on xp_cmdshell.
  12. Note that original server setting for xp_cmdshell would be left unchanged if tests were allowed.
  13. Set @spn_check to OFF if you want to skip SPN checks.
  14. Set @diskfrag to ON if you want to check for disk physical fragmentation.
  15. Can take some time in large disks. Requires elevated privileges.
  16. Set @ixfrag to ON if you want to check for index fragmentation.
  17. Can take some time to collect data depending on number of databases and indexes, as well as the scan mode chosen in @ixfragscanmode.
  18. Set @ixfragscanmode to the scanning mode you prefer.
  19. More detail on scanning modes available at http://msdn.microsoft.com/en-us/library/ms188917.aspx
  20. Set @logdetail to OFF if you want to get just the summary info on issues in the Errorlog, rather than the full detail.
  21. Set @bpool_consumer to OFF if you want to list what are the Buffer Pool Consumers from Buffer Descriptors.
  22. Mind that it may take some time in servers with large caches.
  23. Set @gen_scripts to ON if you want to generate index related scripts.
  24. These include drops for Duplicate, Redundant, Hypothetical and Rarely Used indexes, as well as creation statements for FK and Missing Indexes.
  25. Set @dbScope to the appropriate list of database IDs if there's a need to have a specific scope for database specific checks.
  26. Valid input should be numeric value(s) between single quotes, as follows: '1,6,15,123'
  27. Leave NULL for all databases
  28. */
  29. SET @duration = 90
  30. SET @ptochecks = 1 --(1 = ON; 0 = OFF)
  31. --SET @custompath = 'C:\<temp_location>'
  32. SET @allow_xpcmdshell = 1 --(1 = ON; 0 = OFF)
  33. SET @spn_check = 0 --(1 = ON; 0 = OFF)
  34. SET @diskfrag = 1 --(1 = ON; 0 = OFF)
  35. SET @ixfrag = 1 --(1 = ON; 0 = OFF)
  36. SET @ixfragscanmode = 'LIMITED' --(Valid inputs are DEFAULT, NULL, LIMITED, SAMPLED, or DETAILED. The default (NULL) is LIMITED)
  37. SET @logdetail = 0 --(1 = ON; 0 = OFF)
  38. SET @bpool_consumer = 1 --(1 = ON; 0 = OFF)
  39. SET @gen_scripts = 0 --(1 = ON; 0 = OFF)
  40. SET @dbScope = NULL --(NULL = All DBs)
  41. /*
  42. DESCRIPTION: This script checks for skews in the most common best practices from SQL Server 2005 onwards.
  43. DISCLAIMER:
  44. This code is not supported under any Microsoft standard support program or service.
  45. This code and information are provided "AS IS" without warranty of any kind, either expressed or implied.
  46. The entire risk arising out of the use or performance of the script and documentation remains with you.
  47. Furthermore, Microsoft or the author shall not be liable for any damages you may sustain by using this information, whether direct,
  48. indirect, special, incidental or consequential, including, without limitation, damages for loss of business profits, business interruption, loss of business information
  49. or other pecuniary loss even if it has been advised of the possibility of such damages.
  50. Read all the implementation and usage notes thoroughly.
  51. v1 - 28-07-2011 - Initial release
  52. v1.1 - 28-01-2012 - Added some SQL 2012 support.
  53. v1.2 - 08-03-2012 - Added information to Database Information subsection;
  54. Added I/O stall in excess of 50% in database files subsection.
  55. v1.2.1 - 20-03-2012 - Added redundant index subsection;
  56. Added more SQL 2012 support;
  57. Changed database loop method.
  58. v1.2.2 - 22-03-2012 - Added check for Direct Catalog Updates.
  59. v1.2.3 - 05-04-2012 - Added unused index subsection;
  60. Fixed some collation issues.
  61. v1.2.4 - 07-04-2012 - Split in separate listings the unused indexes from rarely used indexes;
  62. Split in separate listings the real duplicates from possibly redundant indexes.
  63. v1.2.5 - 08-04-2012 - Added power plan check, by Aaron Bertrand (http://www.mssqltips.com/tip.asp?tip=2225&ctc).
  64. v1.2.6 - 13-04-2012 - Added NTFS block size check;
  65. Fixed issue in Data and Log locations check.
  66. v1.2.7 - 16-04-2012 - Added Errorlog based checks section.
  67. v1.2.8 - 21-04-2012 - Fixed issue with NTFS block size check;
  68. Added Replication Components installation check;
  69. Scan for Startup Procs checks for Replication Components installation.
  70. v1.2.9 - 04-05-2012 - Fixed issues when running on SQL Server 2005;
  71. COM object creation was revised.
  72. v1.3 - 08-05-2012 - Added support for customizing save location for .ps1 files;
  73. Default location is the Log folder. Optionally, uncomment line where @custompath is set and insert the desired path.
  74. v1.3.2 - 09-05-2012 - Added descriptive column to Database_Options test, to clear what are the Non-optimal_Settings for each database;
  75. Corrected bug with powershell files default save location, in case default location has changed since SQL Server install.
  76. v1.3.3 - 31-05-2012 - Fixed issue with DBCC CHECKDB test and offline databases.
  77. v1.3.4 - 03-06-2012 - Added more system configuration checks.
  78. v1.3.5 - 07-06-2012 - Added suspect pages check;
  79. Added more permissions checks in pre-requisites section;
  80. Added search for Errors in Errorlog checks.
  81. v1.3.6 - 08-06-2012 - Revised support for account checks in SQL 2012.
  82. v1.3.7 - 14-06-2012 - Fixed issue with large Object_Names;
  83. Fixed issue with Powershell 3.0 script;
  84. Data and log in same volume only lists affected objects now;
  85. Fixed blocking issue with hypothetical objects drop statements;
  86. Added duplicate indexes drop statements (all but the 1st of duplicates);
  87. Added tempDB in same location as user DBs check;
  88. Added backup checks.
  89. v1.3.8 - 19-06-2012 - Fixed issue with Errorlog based checks;
  90. Fixed issue with Data and Log locations.
  91. v1.3.9 - 05-07-2012 - Fixed issue with CPUs vs. MaxDOP check.
  92. v1.4.0 - 10-07-2012 - Added LPIM check;
  93. Added info to trace flags subsection.
  94. v1.4.1 - 18-07-2012 - Added information to CPUs vs. MaxDOP check.
  95. Added information about all backups since last Full (Database, File or Partial).
  96. v1.4.2 - 02-08-2012 - Added Processor Affinity information to instance info.
  97. v1.4.3 - 19-09-2012 - Fixed issue with large integer in DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled) subsection.
  98. v1.4.4 - 23-09-2012 - Added events to monitor to SQL Agent alerts for severe errors subsection;
  99. Added comment column for specific errors foun in Errorlog based checks subsection.
  100. v1.4.5 - 24-09-2012 - Fixed issue with Errorlog based checks subsection search.
  101. v1.4.6 - 17-10-2012 - Fixed issue with large percentages in Stall IO check.
  102. v1.4.7 - 24-10-2012 - Fixed issue with Data files and Logs in same physical volume check, where data and fulltext on the same volume raised an issue;
  103. Fixed issue with Service Accounts and Status check where LocalSystem would not raise issues;
  104. Widened search for Redundant Indexes.
  105. v1.4.8 - 01-11-2012 - Added generation of drop statements for existing Rarely Used indexes.
  106. v1.5.0 - 11-11-2012 - Fixed cpu affinity shows all zeros when auto affinity was used;
  107. Fixed issue with duplicate indexes check introduced with v1.4.8;
  108. Fixed issue with Errorlog based checks subsection search where no comments where shown;
  109. Added aggregates to CPU information subsection;
  110. Simplified logic in CPU Affinity in NUMA architecture subsection;
  111. Added checks to Server Memory information subsection;
  112. Added checks to System configurations subsection;
  113. Added a Deprecated features subsection;
  114. Changed perf counters collection method in Perf counters subsection;
  115. Added more counters to Perf counters subsection.
  116. v1.5.1 - 11-11-2012 - Fixed perf counters collection collecting from default instances only.
  117. v1.5.2 - 15-11-2012 - Fixed issue with long mountpoint paths;
  118. Fixed issue with Backup checks subsection;
  119. Added output from sys.messages to Errorlog based checks.
  120. v1.5.4 - 18-11-2012 - Added sql server process trimming to Errorlog based checks;
  121. Added more checks to System configurations subsection;
  122. Added HA information subsection;
  123. Added optimal nr of VLFs and log size to VLF subsection, based on current findings;
  124. Added even file number check for tempDB;
  125. Added minimum file number check for tempDB when < 4;
  126. Added summary to Errorlog based checks;
  127. Added column about IFI status in autogrow sections;
  128. Added further info to VLF section.
  129. v1.5.5 - 19-11-2012 - Added info to Instance Information subsection;
  130. Added Processor Summary subsection aggregating all CPU information;
  131. Added RM task output notifications;
  132. Format binary affinity mask by node for better reading.
  133. v1.5.6 - 24-11-2012 - Changed collection for several tests that can be supported by DMVs on SQL Server 2008 R2 SP1 and above (was implemented for SQL Server 2012 only);
  134. Added checks and information to Server Memory subsection.
  135. v1.5.7 - 10-12-2012 - Changed collection for Index checks to cope with large database names;
  136. Added support for collection through SQLDiag custom collector.
  137. v1.5.9 - 30-12-2012 - Added schema to index script generation;
  138. Fixed conversion issue with Max Worker Threads option;
  139. Added extended pagefile checks;
  140. Added Replication error checks;
  141. Added check for Indexes with large keys (> 900 bytes).
  142. v1.6.1 - 21-01-2013 - Fixed issue with SQL Server 2005 in Server Memory subsection;
  143. Fixed conversion issues with large msticks values;
  144. Fixed issue with Memory reference values.
  145. v1.6.2 - 02-02-2013 - Fixed issues with case sensitive collations;
  146. Expanded search for redundant indexes;
  147. Expanded system configuration checks;
  148. Added Plan use ratio checks;
  149. Added Hints usage check;
  150. Added Linked servers information;
  151. Added AlwaysOn/Mirroring automatic page repairs check;
  152. Added check for user DBs with Auto_Update_Statistics_Asynch enabled and Auto_Update_Statistics disabled;
  153. Extended I/O Stall checks to verify I/O latencies.
  154. v1.6.3 - 13-02-2013 - Added option to skip PS based tests where activating xp_cmdshell is strictly forbidden (See Readme at the top).
  155. v1.6.4 - 18-02-2013 - Added Buffer Node to performance counters collection;
  156. Added information to RM Notifications section;
  157. Added Cached Query Plans issues checks (Top 25 by CPU, IO and Recompiles with plan warnings);
  158. Added Object Naming Convention checks
  159. v1.6.5 - 27-02-2013 - Added check for databases that need to run DBCC CHECKDB (...) WITH DATA_PURITY;
  160. Added Waits and Latches information;
  161. Added check for statistics that need to be updated;
  162. Optimized performance counters collection;
  163. Extended performance counters collection to 90s;
  164. Removed alternate keys from search for Unused and Rarely used indexes;
  165. Added parameter to enable/disable performance tuning and optimization oriented checks;
  166. Added parameter to enable/disable best practices oriented checks;
  167. v1.6.6 - 05-03-2013 - Removed MS Shipped objects from duplicate and redundant indexes check;
  168. Added search for tables with no indexes, tables with no clustered indexes and tables with more indexes than columns.
  169. v1.6.7 - 01-04-2013 - Fixed issue with AlwaysOn/Mirroring automatic page repair subsection in SQL 2008R2 or below;
  170. Fixed issue with Cached Query Plans issues subsection in SQL 2008R2 RTM;
  171. Added more database files information;
  172. Fixed false positives with DBs Autogrowth > 1GB check;
  173. Added check for TF834 (Large Page Support for BP) when Column Store Indexes are used;
  174. Fixed false positives with Power plan subsection.
  175. v1.6.8.1 - 03-04-2013 - Added min server memory setting checks;
  176. Added information to Errorlog checks;
  177. Fixed false negatives with "Data files and Logs / tempDB and user Databases in same volume" checks when PS is not available;
  178. Added check for tempDB Files with different autogrow setting.
  179. v1.6.9 - 11-04-2013 - Added Worker threads exhaustion check;
  180. Added support for sys.dm_db_stats_properties in Statistics update subsection, if on SQL 2008R2 SP2 or SQL 2012 SP1 or higher.
  181. Made changes to latch checks;
  182. Fixed false positives with Indexes with large keys (> 900 bytes) subsection.
  183. v1.7.0.2 - 07-05-2013 - Fixed Statistics update subsection for SQL 2005;
  184. Changed Errorlog aggregates;
  185. Added Historical Latches without BUFFER class;
  186. Added page file size check for WS2003;
  187. Added information to "Tables with more Indexes than Columns" check.
  188. v1.7.1 - 10-05-2013 - Added "Tables with partition misaligned indexes" check.
  189. v1.7.2 - 18-05-2013 - Added windows service pack level to machine information section;
  190. Changed information available in "Database_File_Information", namely pages calculated in MB;
  191. Added Enterprise features usage information per database;
  192. Added batch performance counters (SQL Server 2012);
  193. Rewrote all database loops.
  194. v1.7.3 - 24-05-2013 - "Query Plan Warnings" check now ignores workload in master and mssqlsystemresource databases;
  195. Fixed issue with running BPchecks without PTOChecks.
  196. v1.7.4 - 01-06-2013 - Added FK with no indexes check;
  197. Fixed issue with Statistics update check in prior to 2008R2 SP2 and 2012 SP1.
  198. v1.7.5 - 25-06-2013 - Added information to Enterprise features usage subsection;
  199. Split Unused indexes section into Unused_Indexes_With_Updates and Unused_Indexes_No_Updates;
  200. Extended Objects naming conventions checks;
  201. Added Disabled indexes subsection;
  202. Added indexes with low fill factor subsection;
  203. Added Non-unique clustered indexes subsection;
  204. Fixed issue with Cached Query Plans issues subsection.
  205. v1.7.6 - 20-07-2013 - Added check for AlwaysOn AG replication status per database (http://support.microsoft.com/kb/2857849);
  206. Fixed issue with large values in I/O Stall subsection;
  207. Added search parameters to Objects naming conventions subsection.
  208. v1.7.6.1-24-07-2013 - Fixed issue with Objects naming conventions checks.
  209. v1.7.6.2-30-07-2013 - Fixed issue with Objects naming conventions checks.
  210. v1.7.7 - 05-09-2013 - Added Missing Indexes output (most relevant - score based - use at you own discretion);
  211. Changed Processor Usage info from 1h to 2h.
  212. v1.7.8 - 21-09-2013 - Changed system database exclusion choices;
  213. Added information to User DBs with non-default options subsection;
  214. VLF section shows added information only on databases failing threshold.
  215. v1.7.9 - 09-10-2013 - Fixed issue with false positives in Purity Check;
  216. Added logic to exclude standard names of MS shipped databases from database design related checks;
  217. Added performance counters to collection.
  218. v1.8 - 25-10-2013 - Added blocking chains (over 5s);
  219. Added monitoring duration as parameter;
  220. Added more file related info to Autogrowth checks;
  221. Fixed CPU Affinity bit mask issue on 16 CPU+ servers;
  222. Extended password checks;
  223. Extended logic to exclude MS shipped databases, based on notable schema objects.
  224. v1.8.0.1 - 28-10-2013 - Fixed issues with logic to exclude MS shipped databases.
  225. v1.8.1 - 03-11-2013 - Added owner info to Database Information subsection;
  226. Fixed issue where no warning was raised for DBs that never had a Log Backup, but had Full/Diff Backups in Full or Bulk-logged RM;
  227. Added Statistics sampling < 25 pct check on SQL 2008R2 SP2 / SQL 2012 and above;
  228. Added Pending I/O Requests check;
  229. Added info to Windows Version and Architecture subsection;
  230. Added spinlocks info;
  231. Added Clustered Indexes with GUIDs in key checks;
  232. Extended trace flag checks.
  233. v1.8.2.1 - 11-11-2013 - Removed cursor from VLF checks;
  234. Added checks to System Configurations;
  235. Added checks to TempDB subsection;
  236. Fixed index statement generation in Foreign Keys with no Index subsection;
  237. Fixed issue with Statistics update subsection up to SQL 2008R2 SP2;
  238. Fixed duplicate key issue in Pending I/O Requests check;
  239. Fixed duplicate entries in redundant indexes of Missing Indexes checks;
  240. Fixed syntax issue in Foreign Keys with no Index subsection.
  241. v1.8.2.2 - 14-11-2013 - Added Dynamics GP database exclusions;
  242. Fixed syntax issue in System Configurations checks.
  243. v1.8.3 - 19-12-2013 - Fixed presentation issue in Pending I/O Requests subsection;
  244. Fixed conversion issue in Statistics Update subsection.
  245. v1.8.4 - 13-01-2014 - Fixed issue with database exclusions;
  246. Fixed issue with Service Accounts section in WS2003;
  247. Removed unwarranted information from DBCC CHECKDB, Direct Catalog Updates and Data Purity subsection.
  248. v1.8.4.1 - 06-02-2014- Added Service Accounts and SPN registration checks;
  249. Fixed issue with Redundant index checks on servers with CS collations.
  250. v1.8.5 - 21-02-2014 - Added LowMemoryThreshold and OOM information to Server Memory subsection;
  251. Extended Min Server Memory checks to Server Memory subsection;
  252. Added DBs with Sparse files checks;
  253. Added System health error checks;
  254. Added Resource Governor information;
  255. Added logdetail parameter to control listing the detail of all relevant Errorlog entries - which can sometimes bloat the output file to several hundred MBs;
  256. Fixed blocking chains (over 5s) showing on SP_SERVER_DIAGNOSTICS_SLEEP wait;
  257. Fixed backup size conversion issue;
  258. Fixed false positives in log backup checks;
  259. Fixed tempDB file size check and Database file information subsections based in sys.master_files may cause issues not to be reported;
  260. Fixed arithmetic overflow error in Statistics update check.
  261. v1.8.6 - 14-03-2014 - Duplicate script generation includes logic to account for PK when several IXs are unique;
  262. Optimized database discovery cycle;
  263. Fixed execution issue in AG DBs when no connections are allowed to the databases in the secondary replica, and the databases are not available for read access.
  264. v1.8.7 - 01-04-2014 - Fixed issue in Hypothetical objects drop script generation;
  265. Fixed issue in several subsections when offline DBs exist;
  266. Fixed issue introduced in v1.8.6 version where some checks would skip user DBs;
  267. Added information on clock hand notifications to Server Memory subsection;
  268. Added thresholds to some Performance Counters -> this does NOT replace a longer perf counter data collection and analysis.
  269. v1.8.7.1 - 03-04-2014 - Added Service Pack Supportability check;
  270. Fixed overflow issue in clock hand notifications;
  271. Fixed issue with clock hand notifications and SQL 2005.
  272. v1.8.8 - 23-04-2014 - Changed Pagefile free space check;
  273. Fixed missing index script creation of covering indexes;
  274. Fixed divide by zero errors in perf counters;
  275. Fixed issue with statistics checks in DBs with cmpt level 80;
  276. Fixed tempDB data file size issue - check was ok, but listed information might not be accurate;
  277. Added category column to all outputs (preparation for future developments).
  278. v1.8.9 - 09-05-2014 - Detailed categorization of memory related waits;
  279. Detailed MaxMem recommendation output;
  280. Added recommended MaxDOP value to Parallelism_MaxDOP check output;
  281. Fixed issue with No_Full_Backups check.
  282. v1.9 - 04-06-2014 - Refined search for duplicate and redundant indexes;
  283. Added partition misalign test (offset < 64KB);
  284. Added Buffer Pool Extension info subsection.
  285. v1.9.1 - 09-06-2014 - Fixed issue with duplicate and redundant index script generation.
  286. v1.9.2 - 13-06-2014 - Fixed calculation in page file checks;
  287. Added process paged out check (besides existing based in errorlog search).
  288. v1.9.3 - 08-07-2014 - Fixed backup checks reporting wrong size;
  289. Changed backup chain based checks to ignore copy_only backups;
  290. Updated Service Pack Supportability check;
  291. Added Cluster Quorum Model check;
  292. Added Cluster QFE node equality check.
  293. v1.9.4 - 16-07-2014 - Added Backups and Database files in same location check;
  294. Enhanced Hints Usage check with info from sql modules;
  295. Fixed Objects naming conventions checks not reporting issues.
  296. v1.9.5 - 17-09-2014 - Changed Hypothetical object search scope to all DBs, including MS shipped;
  297. Changed missing index check to include all missing by order of score, but still generating script only when score >= 100000;
  298. Added features to Enterprise features check;
  299. Expanded TF checks.
  300. v1.9.6.1 - 20-10-2014 - Fixed hypothetical statistics search;
  301. Fixed Parallelism_MaxDOP check on large NUMA nodes and specific MaxDOP settings;
  302. Fixed Cluster Quorum Model false positive when PS is not available;
  303. Changed Powershell availability verification to single step;
  304. Added user objects in master check;
  305. Added logon triggers information;
  306. Added database triggers information;
  307. Added Database file autogrows last 72h information;
  308. Added Cluster NIC Binding order check;
  309. Added Disk Fragmentation Analysis (only if running with elevated privs and enabled with variable @diskfrag);
  310. Added Index Fragmentation Analysis (only if enabled with variable @ixfrag);
  311. Fixed trace flag checks recommending trace flags that did not apply to server hardware.
  312. v1.9.6.2 - 23-10-2014 - Fixed false positive on Cluster NIC Binding order check;
  313. v1.9.6.3 - 25-10-2014 - Fixed syntax error on Cluster NIC Binding order check;
  314. v1.9.7 - 12-11-2014 - Changed Cluster Quorum Model check output;
  315. Fixed conversion issue with Buffer Pool Consumers section;
  316. Fixed issue on server that has only AG secondary replicas;
  317. Added model information to Machine Information section;
  318. Added @bpool_consumer option to skip listing Buffer Pool Consumers;
  319. Added @gen_scripts option to skip generating scripts (disabled by default);
  320. Added listing of which duplicate indexes are eligible for deletion;
  321. Added search for which of the duplicate indexes that are eligible for deletion are hard coded in sql modules.
  322. v1.9.8 - 10-12-2014 - Fixed issue with Cluster NIC Binding order subsection on case sensitive instances;
  323. Fixed issue with Database file autogrows last 72h subsection on case sensitive instances;
  324. Fixed issues with PS based checks running in PS v1;
  325. Fixed illegal characters issue in XML conversion;
  326. Fixed syntax error in SQL 2014 Memory Consumers from In-Memory OLTP Engine.
  327. v1.9.8.1 - 16-12-2014 - Fixed issues in Enterprise features usage subsection on SQL 2012 and AlwaysOn in use.
  328. v1.9.9 - 30-01-2015 - Fixed conversion issue in Plan_use_ratio check;
  329. Added HADR info to Database Information subsection;
  330. Added NUMA info to Server Memory subsection.
  331. v1.9.9.1 - 06-02-2015 - Fixed NUMA info collection issue up to SQL 2008R2 introduced in v1.9.9.
  332. v1.9.9.2 - 13-02-2015 - Fixed NUMA info collection issue on SQL 2012 and above introduced in v1.9.9;
  333. Added support to scope only specific databases by ID.
  334. v1.9.9.3 - 15-03-2015 - Fixed some information in "Database Information" section not being collected, introduced in v1.9.9.2.
  335. v1.9.9.5 - 11-04-2015 - Fixed System health error checks conversion error;
  336. Extended Memory Allocations from Memory Clerks checks;
  337. Extended logic to exclude MS shipped databases;
  338. Fixed overflow error in Blocking Chains check if larger than Integer supports;
  339. Fixed insert error in Pending I/O Requests check.
  340. v2.0.0 - 22-04-2015 - Added Declarative Referential Integrity - Untrusted Constraints checks;
  341. Added XTP Index Health Analysis;
  342. Added CCI Index Health Analysis: pseudo-fragmentation for CCI is the ratio of deleted_rows to total_rows;
  343. Renamed "Index Fragmentation Analysis" to "Index Health Analysis" subsection;
  344. Added storage analysis for In-Memory OLTP Engine in Database Information subsection;
  345. Fixed sp_server_diagnostics showing up as blocked session with long blocking time;
  346. Extended AO cluster information;
  347. Database filter now always includes sys DBs.
  348. v2.0.1 - 23-04-2015 - Fixed issue with SQL 2012 in Index Health analysis.
  349. v2.0.2 - 14-05-2015 - Added Default data collections (check for default trace, blackbox trace, SystemHealth xEvent session, sp_server_diagnostics xEvent session);
  350. Extended Objects naming conventions checks to functions;
  351. Added info on Inefficient Plans by CPU and Read I/O;
  352. Improved search for hypothetical objects;
  353. Added script generation to fix issues from Declarative Referential Integrity - Untrusted Constraints checks.
  354. v2.0.2.1 - 18-05-2015 - Fixed Declarative Referential Integrity script generation.
  355. v2.0.3 - 10-09-2015 - Added information about current PMO to Global Trace Flags check when 8048 may be missing.
  356. v2.0.3.1 - 11-09-2015 - Fixed PMO check up to 2008R2.
  357. v2.1 - 9/30/2016 - Fixed issue with LPIM check in SQL Server 2005;
  358. Tuned Memory Allocations from In-Memory OLTP Engine checks;
  359. Tuned I/O stall checks to separate overall stall time from avg latency tests;
  360. Fixed issue with DBs Autogrowth > 1GB check missing files if IFI is enabled;
  361. Updated Cached Query Plans section with new DMV columns;
  362. Workaround for windows version not correct under W10/WS2016;
  363. Added Disk space information;
  364. Added overall support for SQL Server 2012 SP3, 2014 SP2 and 2016 in multiple checks;
  365. Added plans with Inefficient Memory Use to Performance checks.
  366. v2.1.1 - 10/01/2016 - Fixed issues with Database Information subsection in SQL 2005 to 2008R2.
  367. v2.1.2 - 10/25/2016 - Added incremental stats as default to Database Options check;
  368. Added W10 Aniversary Edition to OS versions;
  369. Fixed Indexing per Table subsection accounting for hypotheical indexes.
  370. v2.1.3 - 10/26/2016 - Fixed conversion issue with Account checks;
  371. Fixed negative CPU usage in avg cpu usage last 2h check.
  372. v2.1.4 - 11/08/2016 - Fixed autogrows in last 72h shown in MB instead of KB.
  373. v2.1.5 - 11/17/2016 - Added support for SQLS erver 2016 SP1 (Enterprise_features_usage, LPIM and IFI checks).
  374. PURPOSE: Checks SQL Server in scope for some of most common skewed Best Practices. Valid from SQL Server 2005 onwards.
  375. - Contains the following information:
  376. |- Uptime
  377. |- Windows Version and Architecture
  378. |- Disk space
  379. |- HA Information
  380. |- Linked servers info
  381. |- Instance info
  382. |- Resource Governor info
  383. |- Logon triggers
  384. |- Database Information
  385. |- Database file autogrows last 72h
  386. |- Database triggers
  387. |- Enterprise features usage
  388. |- Backups
  389. |- System Configuration
  390. - And performs the following checks (* means only when @ptochecks is ON):
  391. |- Processor
  392. |- Number of available Processors for this instance vs. MaxDOP setting
  393. |- Processor Affinity in NUMA architecture
  394. |- Additional Processor information
  395. |- Processor utilization rate in the last 2 hours *
  396. |- Memory
  397. |- Server Memory
  398. |- RM Task *
  399. |- Clock hands *
  400. |- Buffer Pool Consumers from Buffer Descriptors *
  401. |- Memory Allocations from Memory Clerks *
  402. |- Memory Consumers from In-Memory OLTP Engine *
  403. |- Memory Allocations from In-Memory OLTP Engine *
  404. |- OOM
  405. |- LPIM
  406. |- Pagefile
  407. |- Pagefile
  408. |- I/O
  409. |- I/O Stall subsection (wait for 5s) *
  410. |- Pending disk I/O Requests subsection (wait for a max of 5s) *
  411. |- Server
  412. |- Power plan
  413. |- NTFS block size in volumes that hold database files <> 64KB
  414. |- Disk Fragmentation Analysis (if enabled)
  415. |- Cluster Quorum Model
  416. |- Cluster QFE node equality
  417. |- Cluster NIC Binding order
  418. |- Service Accounts
  419. |- Service Accounts Status
  420. |- Service Accounts and SPN registration
  421. |- Instance
  422. |- Recommended build check
  423. |- Backups
  424. |- Global trace flags
  425. |- System configurations
  426. |- IFI
  427. |- Full Text Configurations
  428. |- Deprecated features *
  429. |- Default data collections (default trace, blackbox trace, SystemHealth xEvent session, sp_server_diagnostics xEvent session)
  430. |- Database and tempDB
  431. |- User objects in master
  432. |- DBs with collation <> master
  433. |- DBs with skewed compatibility level
  434. |- User DBs with non-default options
  435. |- DBs with Sparse files
  436. |- DBs Autogrow in percentage
  437. |- DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled)
  438. |- VLF
  439. |- Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware)
  440. |- tempDB data file configurations
  441. |- tempDB Files autogrow of equal size
  442. |- Performance
  443. |- Perf counters, Waits and Latches (wait for 90s) *
  444. |- Worker thread exhaustion *
  445. |- Blocking Chains *
  446. |- Plan use ratio *
  447. |- Hints usage *
  448. |- Cached Query Plans issues *
  449. |- Inefficient Query Plans *
  450. |- Declarative Referential Integrity - Untrusted Constraints *
  451. |- Indexes and Statistics
  452. |- Statistics update *
  453. |- Statistics sampling *
  454. |- Hypothetical objects *
  455. |- Row Index Fragmentation Analysis (if enabled) *
  456. |- CS Index Health Analysis (if enabled) *
  457. |- XTP Index Health Analysis (if enabled) *
  458. |- Duplicate or Redundant indexes *
  459. |- Unused and rarely used indexes *
  460. |- Indexes with large keys (> 900 bytes) *
  461. |- Indexes with fill factor < 80 pct *
  462. |- Disabled indexes *
  463. |- Non-unique clustered indexes *
  464. |- Clustered Indexes with GUIDs in key *
  465. |- Foreign Keys with no Index *
  466. |- Indexing per Table *
  467. |- Missing Indexes *
  468. |- Naming Convention
  469. |- Objects naming conventions
  470. |- Security
  471. |- Password check
  472. |- Maintenance and Monitoring
  473. |- SQL Agent alerts for severe errors
  474. |- DBCC CHECKDB, Direct Catalog Updates and Data Purity
  475. |- AlwaysOn/Mirroring automatic page repair
  476. |- Suspect pages
  477. |- Replication Errors
  478. |- Errorlog based checks
  479. |- System health checks
  480. DISCLAIMER:
  481. This code and information are provided "AS IS" without warranty of any kind, either expressed or implied.
  482. Furthermore, the author or Microsoft shall not be liable for any damages you may sustain by using this information, whether direct, indirect, special, incidental or consequential, even if it has been advised of the possibility of such damages.
  483. IMPORTANT pre-requisites:
  484. - Only a sysadmin/local host admin will be able to perform all checks.
  485. - If you want to perform all checks under non-sysadmin credentials, then that login must be:
  486. Member of serveradmin server role or have the ALTER SETTINGS server permission;
  487. Member of MSDB SQLAgentOperatorRole role, or have SELECT permission on the sysalerts table in MSDB;
  488. Granted EXECUTE permissions on the following extended sprocs to run checks: sp_OACreate, sp_OADestroy, sp_OAGetErrorInfo, xp_enumerrorlogs, xp_fileexist and xp_regenumvalues;
  489. Granted EXECUTE permissions on xp_msver;
  490. Granted the VIEW SERVER STATE permission;
  491. Granted the VIEW DATABASE STATE permission;
  492. Granted EXECUTE permissions on xp_cmdshell or a xp_cmdshell proxy account should exist to run checks that access disk or OS security configurations.
  493. Member of securityadmin role, or have EXECUTE permissions on sp_readerrorlog.
  494. Otherwise some checks will be bypassed and warnings will be shown.
  495. - Powershell must be installed to run checks that access disk configurations, as well as allow execution of remote signed or unsigned scripts.
  496. */
  497. SET NOCOUNT ON;
  498. SET ANSI_WARNINGS ON;
  499. SET QUOTED_IDENTIFIER ON;
  500. SET DATEFORMAT mdy;
  501. RAISERROR (N'Starting Pre-requisites section', 10, 1) WITH NOWAIT
  502. --------------------------------------------------------------------------------------------------------------------------------
  503. -- Pre-requisites section
  504. --------------------------------------------------------------------------------------------------------------------------------
  505. DECLARE @sqlcmd NVARCHAR(max), @params NVARCHAR(500), @sqlmajorver int
  506. /*
  507. Reference: SERVERPROPERTY for sql major, minor and build versions supported after:
  508. @sqlmajorver >= 13 OR (@sqlmajorver = 12 AND @sqlbuild >= 2556 AND @sqlbuild < 4100) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427)
  509. */
  510. SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  511. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 0)
  512. BEGIN
  513. RAISERROR('[WARNING: Only a sysadmin can run ALL the checks]', 16, 1, N'sysadmin')
  514. --RETURN
  515. END;
  516. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 0)
  517. BEGIN
  518. DECLARE @pid int, @pname sysname, @msdbpid int, @masterpid int
  519. DECLARE @permstbl TABLE ([name] sysname);
  520. DECLARE @permstbl_msdb TABLE ([id] tinyint IDENTITY(1,1), [perm] tinyint)
  521. SET @params = '@msdbpid_in int'
  522. SELECT @pid = principal_id, @pname=name FROM master.sys.server_principals (NOLOCK) WHERE sid = SUSER_SID()
  523. SELECT @masterpid = principal_id FROM master.sys.database_principals (NOLOCK) WHERE sid = SUSER_SID()
  524. SELECT @msdbpid = principal_id FROM msdb.sys.database_principals (NOLOCK) WHERE sid = SUSER_SID()
  525. -- Perms 1
  526. IF (ISNULL(IS_SRVROLEMEMBER(N'serveradmin'), 0) <> 1) AND ((SELECT COUNT(l.name)
  527. FROM master.sys.server_permissions p (NOLOCK) INNER JOIN master.sys.server_principals l (NOLOCK)
  528. ON p.grantee_principal_id = l.principal_id
  529. AND p.class = 100 -- Server
  530. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  531. AND l.is_disabled = 0
  532. AND p.permission_name = 'ALTER SETTINGS'
  533. AND QUOTENAME(l.name) = QUOTENAME(@pname)) = 0)
  534. BEGIN
  535. RAISERROR('[WARNING: If not sysadmin, then you must be a member of serveradmin server role or have the ALTER SETTINGS server permission]', 16, 1, N'serveradmin')
  536. RETURN
  537. END
  538. ELSE IF (ISNULL(IS_SRVROLEMEMBER(N'serveradmin'), 0) <> 1) AND ((SELECT COUNT(l.name)
  539. FROM master.sys.server_permissions p (NOLOCK) INNER JOIN sys.server_principals l (NOLOCK)
  540. ON p.grantee_principal_id = l.principal_id
  541. AND p.class = 100 -- Server
  542. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  543. AND l.is_disabled = 0
  544. AND p.permission_name = 'VIEW SERVER STATE'
  545. AND QUOTENAME(l.name) = QUOTENAME(@pname)) = 0)
  546. BEGIN
  547. RAISERROR('[WARNING: If not sysadmin, then you must be a member of serveradmin server role or granted the VIEW SERVER STATE permission]', 16, 1, N'serveradmin')
  548. RETURN
  549. END
  550. -- Perms 2
  551. INSERT INTO @permstbl
  552. SELECT a.name
  553. FROM master.sys.all_objects a (NOLOCK) INNER JOIN master.sys.database_permissions b (NOLOCK) ON a.[OBJECT_ID] = b.major_id
  554. WHERE a.type IN ('P', 'X') AND b.grantee_principal_id <>0
  555. AND b.grantee_principal_id <>2
  556. AND b.grantee_principal_id = @masterpid;
  557. INSERT INTO @permstbl_msdb ([perm])
  558. EXECUTE sp_executesql N'USE msdb; SELECT COUNT([name])
  559. FROM msdb.sys.sysusers (NOLOCK) WHERE [uid] IN (SELECT [groupuid]
  560. FROM msdb.sys.sysmembers (NOLOCK) WHERE [memberuid] = @msdbpid_in)
  561. AND [name] = ''SQLAgentOperatorRole''', @params, @msdbpid_in = @msdbpid;
  562. INSERT INTO @permstbl_msdb ([perm])
  563. EXECUTE sp_executesql N'USE msdb; SELECT COUNT(dp.grantee_principal_id)
  564. FROM msdb.sys.tables AS tbl (NOLOCK)
  565. INNER JOIN msdb.sys.database_permissions AS dp (NOLOCK) ON dp.major_id=tbl.object_id AND dp.class=1
  566. INNER JOIN msdb.sys.database_principals AS grantor_principal (NOLOCK) ON grantor_principal.principal_id = dp.grantor_principal_id
  567. INNER JOIN msdb.sys.database_principals AS grantee_principal (NOLOCK) ON grantee_principal.principal_id = dp.grantee_principal_id
  568. WHERE dp.state = ''G''
  569. AND dp.grantee_principal_id = @msdbpid_in
  570. AND dp.type = ''SL''', @params, @msdbpid_in = @msdbpid;
  571. IF (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 1) = 0 AND (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 2) = 0
  572. BEGIN
  573. RAISERROR('[WARNING: If not sysadmin, then you must be a member of MSDB SQLAgentOperatorRole role, or have SELECT permission on the sysalerts table in MSDB to run full scope of checks]', 16, 1, N'msdbperms')
  574. --RETURN
  575. END
  576. ELSE IF (ISNULL(IS_SRVROLEMEMBER(N'securityadmin'), 0) <> 1) AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_enumerrorlogs') = 0 OR (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_readerrorlog') = 0 OR (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_readerrorlog') = 0)
  577. BEGIN
  578. RAISERROR('[WARNING: If not sysadmin, then you must be a member of the securityadmin server role, or have EXECUTE permission on the following extended sprocs to run full scope of checks: xp_enumerrorlogs, xp_readerrorlog, sp_readerrorlog]', 16, 1, N'secperms')
  579. --RETURN
  580. END
  581. ELSE IF (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') = 0 OR (SELECT COUNT(credential_id) FROM master.sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') = 0
  582. BEGIN
  583. RAISERROR('[WARNING: If not sysadmin, then you must be granted EXECUTE permissions on xp_cmdshell and a xp_cmdshell proxy account should exist to run full scope of checks]', 16, 1, N'xp_cmdshellproxy')
  584. --RETURN
  585. END
  586. ELSE IF (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') = 0 OR
  587. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') = 0 OR
  588. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') = 0 OR
  589. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') = 0 OR
  590. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') = 0 OR
  591. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 0 OR
  592. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 0 OR
  593. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_servicecontrol') = 0
  594. BEGIN
  595. RAISERROR('[WARNING: Must be a granted EXECUTE permissions on the following extended sprocs to run full scope of checks: sp_OACreate, sp_OADestroy, sp_OAGetErrorInfo, xp_fileexist, xp_regread, xp_instance_regread, xp_servicecontrol and xp_regenumvalues]', 16, 1, N'extended_sprocs')
  596. --RETURN
  597. END
  598. ELSE IF (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_msver') = 0 AND @sqlmajorver < 11
  599. BEGIN
  600. RAISERROR('[WARNING: Must be granted EXECUTE permissions on xp_msver to run full scope of checks]', 16, 1, N'extended_sprocs')
  601. --RETURN
  602. END
  603. END;
  604. -- Declare Global Variables
  605. DECLARE @UpTime VARCHAR(12),@StartDate DATETIME
  606. DECLARE @agt smallint, @ole smallint, @sao smallint, @xcmd smallint
  607. DECLARE @ErrorSeverity int, @ErrorState int, @ErrorMessage NVARCHAR(4000)
  608. DECLARE @CMD NVARCHAR(4000)
  609. DECLARE @path NVARCHAR(2048)
  610. DECLARE @sqlminorver int, @sqlbuild int, @clustered bit, @winver VARCHAR(5), @server VARCHAR(128), @instancename NVARCHAR(128), @arch smallint, @winsp VARCHAR(25), @SystemManufacturer VARCHAR(128)
  611. DECLARE @existout int, @FSO int, @FS int, @OLEResult int, @FileID int
  612. DECLARE @FileName VARCHAR(200), @Text1 VARCHAR(2000), @CMD2 VARCHAR(100)
  613. DECLARE @src VARCHAR(255), @desc VARCHAR(255), @psavail VARCHAR(20), @psver tinyint
  614. DECLARE @dbid int, @dbname VARCHAR(1000)
  615. SELECT @instancename = CONVERT(VARCHAR(128),SERVERPROPERTY('InstanceName'))
  616. SELECT @server = RTRIM(CONVERT(VARCHAR(128), SERVERPROPERTY('MachineName')))
  617. --SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  618. SELECT @sqlminorver = CONVERT(int, (@@microsoftversion / 0x10000) & 0xff);
  619. SELECT @sqlbuild = CONVERT(int, @@microsoftversion & 0xffff);
  620. SELECT @clustered = CONVERT(bit,ISNULL(SERVERPROPERTY('IsClustered'),0))
  621. -- Test Powershell policy
  622. IF @allow_xpcmdshell = 1
  623. BEGIN
  624. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  625. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  626. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  627. AND (SELECT COUNT(l.name)
  628. FROM sys.server_permissions p JOIN sys.server_principals l
  629. ON p.grantee_principal_id = l.principal_id
  630. AND p.class = 100 -- Server
  631. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  632. AND l.is_disabled = 0
  633. AND p.permission_name = 'ALTER SETTINGS'
  634. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  635. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  636. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  637. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0)))
  638. BEGIN
  639. DECLARE @pstbl_avail TABLE ([KeyExist] int)
  640. BEGIN TRY
  641. INSERT INTO @pstbl_avail
  642. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\PowerShell\1' -- check if Powershell is installed
  643. END TRY
  644. BEGIN CATCH
  645. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  646. SELECT @ErrorMessage = 'Could not determine if Powershell is installed - Error raised in TRY block. ' + ERROR_MESSAGE()
  647. RAISERROR (@ErrorMessage, 16, 1);
  648. END CATCH
  649. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  650. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  651. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  652. RAISERROR ('|-Configuration options set for Powershell enablement verification', 10, 1) WITH NOWAIT
  653. IF @sao = 0
  654. BEGIN
  655. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  656. END
  657. IF @xcmd = 0
  658. BEGIN
  659. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  660. END
  661. IF @ole = 0
  662. BEGIN
  663. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  664. END
  665. IF (SELECT [KeyExist] FROM @pstbl_avail) = 1
  666. BEGIN
  667. DECLARE @psavail_output TABLE ([PS_OUTPUT] VARCHAR(2048));
  668. INSERT INTO @psavail_output
  669. EXEC master.dbo.xp_cmdshell N'%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Get-ExecutionPolicy"'
  670. SELECT @psavail = [PS_OUTPUT] FROM @psavail_output WHERE [PS_OUTPUT] IS NOT NULL;
  671. END
  672. ELSE
  673. BEGIN
  674. RAISERROR (' [WARNING: Powershell is not installed. Install WinRM to proceed with PS based checks]',16,1);
  675. END
  676. IF (@psavail IS NOT NULL AND @psavail NOT IN ('RemoteSigned','Unrestricted'))
  677. RAISERROR (' [WARNING: Execution of Powershell scripts is disabled on this system.
  678. To change the execution policy, type the following command in Powershell console: Set-ExecutionPolicy RemoteSigned
  679. The Set-ExecutionPolicy cmdlet enables you to determine which Windows PowerShell scripts (if any) will be allowed to run on your computer. Windows PowerShell has four different execution policies:
  680. Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  681. AllSigned - Only scripts signed by a trusted publisher can be run.
  682. RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  683. |- REQUIRED by BP Check
  684. Unrestricted - No restrictions; all Windows PowerShell scripts can be run.]',16,1);
  685. IF (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  686. BEGIN
  687. RAISERROR ('|- [INFORMATION: Powershell is installed and enabled for script execution]', 10, 1) WITH NOWAIT
  688. DECLARE @psver_output TABLE ([PS_OUTPUT] VARCHAR(1024));
  689. INSERT INTO @psver_output
  690. EXEC master.dbo.xp_cmdshell N'%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Get-Host | Format-Table -Property Version"'
  691. -- Gets PS version, as commands issued to PS v1 do not support -File
  692. SELECT @psver = ISNULL(LEFT([PS_OUTPUT],1),2) FROM @psver_output WHERE [PS_OUTPUT] IS NOT NULL AND ISNUMERIC(LEFT([PS_OUTPUT],1)) = 1;
  693. SET @ErrorMessage = '|- [INFORMATION: Installed Powershell is version ' + CONVERT(CHAR(1), @psver) + ']'
  694. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  695. END;
  696. IF @xcmd = 0
  697. BEGIN
  698. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  699. END
  700. IF @ole = 0
  701. BEGIN
  702. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  703. END
  704. IF @sao = 0
  705. BEGIN
  706. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  707. END;
  708. END
  709. ELSE
  710. BEGIN
  711. RAISERROR(' [WARNING: Missing permissions for Powershell enablement verification]', 16, 1, N'sysadmin')
  712. --RETURN
  713. END
  714. END;
  715. --------------------------------------------------------------------------------------------------------------------------------
  716. -- Information section
  717. --------------------------------------------------------------------------------------------------------------------------------
  718. RAISERROR (N'Starting Information section', 10, 1) WITH NOWAIT
  719. --------------------------------------------------------------------------------------------------------------------------------
  720. -- Uptime subsection
  721. --------------------------------------------------------------------------------------------------------------------------------
  722. RAISERROR (N'|-Starting Uptime', 10, 1) WITH NOWAIT
  723. IF @sqlmajorver < 10
  724. BEGIN
  725. SET @sqlcmd = N'SELECT @UpTimeOUT = DATEDIFF(mi, login_time, GETDATE()), @StartDateOUT = login_time FROM master..sysprocesses (NOLOCK) WHERE spid = 1';
  726. END
  727. ELSE
  728. BEGIN
  729. SET @sqlcmd = N'SELECT @UpTimeOUT = DATEDIFF(mi,sqlserver_start_time,GETDATE()), @StartDateOUT = sqlserver_start_time FROM sys.dm_os_sys_info (NOLOCK)';
  730. END
  731. SET @params = N'@UpTimeOUT VARCHAR(12) OUTPUT, @StartDateOUT DATETIME OUTPUT';
  732. EXECUTE sp_executesql @sqlcmd, @params, @UpTimeOUT=@UpTime OUTPUT, @StartDateOUT=@StartDate OUTPUT;
  733. SELECT 'Information' AS [Category], 'Uptime' AS [Information], GETDATE() AS [Current_Time], @StartDate AS Last_Startup, CONVERT(VARCHAR(4),@UpTime/60/24) + 'd ' + CONVERT(VARCHAR(4),@UpTime/60%24) + 'hr ' + CONVERT(VARCHAR(4),@UpTime%60) + 'min' AS Uptime
  734. --------------------------------------------------------------------------------------------------------------------------------
  735. -- Windows Version and Architecture subsection
  736. --------------------------------------------------------------------------------------------------------------------------------
  737. RAISERROR (N'|-Starting Windows Version and Architecture', 10, 1) WITH NOWAIT
  738. IF @sqlmajorver >= 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  739. BEGIN
  740. SET @sqlcmd = N'SELECT @winverOUT = CASE WHEN windows_release IN (''6.3'',''10.0'') AND (@@VERSION LIKE ''%Build 10586%'' OR @@VERSION LIKE ''%Build 14393%'')THEN ''10.0'' ELSE windows_release END, @winspOUT = windows_service_pack_level, @archOUT = CASE WHEN @@VERSION LIKE ''%<X64>%'' THEN 64 WHEN @@VERSION LIKE ''%<IA64>%'' THEN 128 ELSE 32 END FROM sys.dm_os_windows_info (NOLOCK)';
  741. SET @params = N'@winverOUT VARCHAR(5) OUTPUT, @winspOUT VARCHAR(25) OUTPUT, @archOUT smallint OUTPUT';
  742. EXECUTE sp_executesql @sqlcmd, @params, @winverOUT=@winver OUTPUT, @winspOUT=@winsp OUTPUT, @archOUT=@arch OUTPUT;
  743. END
  744. ELSE
  745. BEGIN
  746. BEGIN TRY
  747. DECLARE @str VARCHAR(500), @str2 VARCHAR(500), @str3 VARCHAR(500)
  748. DECLARE @sysinfo TABLE (id int,
  749. [Name] NVARCHAR(256),
  750. Internal_Value bigint,
  751. Character_Value NVARCHAR(256));
  752. INSERT INTO @sysinfo
  753. EXEC xp_msver;
  754. SELECT @winver = LEFT(Character_Value, CHARINDEX(' ', Character_Value)-1) -- 5.2 is WS2003; 6.0 is WS2008; 6.1 is WS2008R2; 6.2 is WS2012, 6.3 is WS2012R2
  755. FROM @sysinfo
  756. WHERE [Name] LIKE 'WindowsVersion%';
  757. SELECT @arch = CASE WHEN RTRIM(Character_Value) LIKE '%x64%' OR RTRIM(Character_Value) LIKE '%AMD64%' THEN 64
  758. WHEN RTRIM(Character_Value) LIKE '%x86%' OR RTRIM(Character_Value) LIKE '%32%' THEN 32
  759. WHEN RTRIM(Character_Value) LIKE '%IA64%' THEN 128 END
  760. FROM @sysinfo
  761. WHERE [Name] LIKE 'Platform%';
  762. SET @str = (SELECT @@VERSION)
  763. SELECT @str2 = RIGHT(@str, LEN(@str)-CHARINDEX('Windows',@str) + 1)
  764. SELECT @str3 = RIGHT(@str2, LEN(@str2)-CHARINDEX(': ',@str2))
  765. SELECT @winsp = LTRIM(LEFT(@str3, CHARINDEX(')',@str3) -1))
  766. END TRY
  767. BEGIN CATCH
  768. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  769. SELECT @ErrorMessage = 'Windows Version and Architecture subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  770. RAISERROR (@ErrorMessage, 16, 1);
  771. END CATCH
  772. END;
  773. DECLARE @machineinfo TABLE ([Value] NVARCHAR(256), [Data] NVARCHAR(256))
  774. INSERT INTO @machineinfo
  775. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemManufacturer';
  776. INSERT INTO @machineinfo
  777. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemProductName';
  778. INSERT INTO @machineinfo
  779. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemFamily';
  780. INSERT INTO @machineinfo
  781. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSVendor';
  782. INSERT INTO @machineinfo
  783. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSVersion';
  784. INSERT INTO @machineinfo
  785. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSReleaseDate';
  786. INSERT INTO @machineinfo
  787. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\CentralProcessor\0','ProcessorNameString';
  788. SELECT @SystemManufacturer = [Data] FROM @machineinfo WHERE [Value] = 'SystemManufacturer';
  789. SELECT 'Information' AS [Category], 'Machine' AS [Information],
  790. CASE @winver WHEN '5.2' THEN 'XP/WS2003'
  791. WHEN '6.0' THEN 'Vista/WS2008'
  792. WHEN '6.1' THEN 'W7/WS2008R2'
  793. WHEN '6.2' THEN 'W8/WS2012'
  794. WHEN '6.3' THEN 'W8.1/WS2012R2'
  795. WHEN '10.0' THEN 'W10/WS2016'
  796. END AS [Windows_Version],
  797. @winsp AS [Service_Pack_Level],
  798. @arch AS [Architecture],
  799. SERVERPROPERTY('MachineName') AS [Machine_Name],
  800. SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [NetBIOS_Name],
  801. @SystemManufacturer AS [System_Manufacturer],
  802. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'SystemFamily') AS [System_Family],
  803. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'SystemProductName') AS [System_ProductName],
  804. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSVendor') AS [BIOS_Vendor],
  805. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSVersion') AS [BIOS_Version],
  806. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSReleaseDate') AS [BIOS_Release_Date],
  807. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'ProcessorNameString') AS [Processor_Name];
  808. --------------------------------------------------------------------------------------------------------------------------------
  809. -- Disk space subsection
  810. --------------------------------------------------------------------------------------------------------------------------------
  811. RAISERROR (N'|-Starting Disk space', 10, 1) WITH NOWAIT
  812. SELECT DISTINCT 'Information' AS [Category], 'Disk_Space' AS [Information], vs.logical_volume_name,
  813. vs.volume_mount_point, vs.file_system_type, CONVERT(int,vs.total_bytes/1048576.0) AS TotalSpace_MB,
  814. CONVERT(int,vs.available_bytes/1048576.0) AS FreeSpace_MB, vs.is_compressed
  815. FROM sys.master_files mf
  816. CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) vs
  817. ORDER BY FreeSpace_MB ASC;
  818. --------------------------------------------------------------------------------------------------------------------------------
  819. -- HA Information subsection
  820. --------------------------------------------------------------------------------------------------------------------------------
  821. RAISERROR (N'|-Starting HA Information', 10, 1) WITH NOWAIT
  822. IF @clustered = 1
  823. BEGIN
  824. IF @sqlmajorver < 11
  825. BEGIN
  826. EXEC ('SELECT ''Information'' AS [Category], ''Cluster'' AS [Information], NodeName AS node_name FROM sys.dm_os_cluster_nodes (NOLOCK)')
  827. END
  828. ELSE
  829. BEGIN
  830. EXEC ('SELECT ''Information'' AS [Category], ''Cluster'' AS [Information], NodeName AS node_name, status_description, is_current_owner FROM sys.dm_os_cluster_nodes (NOLOCK)')
  831. END
  832. SELECT 'Information' AS [Category], 'Cluster' AS [Information], DriveName AS cluster_shared_drives FROM sys.dm_io_cluster_shared_drives (NOLOCK)
  833. END
  834. ELSE
  835. BEGIN
  836. SELECT 'Information' AS [Category], 'Cluster' AS [Information], 'NOT_CLUSTERED' AS [Status]
  837. END;
  838. IF @sqlmajorver > 10
  839. BEGIN
  840. DECLARE @IsHadrEnabled tinyint, @HadrManagerStatus tinyint
  841. SELECT @IsHadrEnabled = CONVERT(tinyint, SERVERPROPERTY('IsHadrEnabled'))
  842. SELECT @HadrManagerStatus = CONVERT(tinyint, SERVERPROPERTY('HadrManagerStatus'))
  843. SELECT 'Information' AS [Category], 'AlwaysOn_AG' AS [Information],
  844. CASE @IsHadrEnabled WHEN 0 THEN 'Disabled'
  845. WHEN 1 THEN 'Enabled' END AS [AlwaysOn_Availability_Groups],
  846. CASE WHEN @IsHadrEnabled = 1 THEN
  847. CASE @HadrManagerStatus WHEN 0 THEN '[Not started, pending communication]'
  848. WHEN 1 THEN '[Started and running]'
  849. WHEN 2 THEN '[Not started and failed]'
  850. END
  851. END AS [Status];
  852. IF @IsHadrEnabled = 1
  853. BEGIN
  854. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster)
  855. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster' AS [Information], cluster_name, quorum_type_desc, quorum_state_desc
  856. FROM sys.dm_hadr_cluster;
  857. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster_members)
  858. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster_Members' AS [Information], member_name, member_type_desc, member_state_desc, number_of_quorum_votes
  859. FROM sys.dm_hadr_cluster_members;
  860. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster_networks)
  861. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster_Networks' AS [Information], member_name, network_subnet_ip, network_subnet_ipv4_mask, is_public, is_ipv4
  862. FROM sys.dm_hadr_cluster_networks;
  863. END;
  864. IF @ptochecks = 1 AND @IsHadrEnabled = 1
  865. BEGIN
  866. -- Note: If low_water_mark_for_ghosts number is not increasing over time, it implies that ghost cleanup might not happen.
  867. SELECT 'Information' AS [Category], 'AlwaysOn_Replicas' AS [Information], database_id, group_id, replica_id, group_database_id, is_local, synchronization_state_desc,
  868. is_commit_participant, synchronization_health_desc, database_state_desc, is_suspended, suspend_reason_desc, last_sent_time, last_received_time, last_hardened_time,
  869. last_redone_time, log_send_queue_size, log_send_rate, redo_queue_size, redo_rate, filestream_send_rate, last_commit_time, low_water_mark_for_ghosts
  870. FROM sys.dm_hadr_database_replica_states;
  871. SELECT 'Information' AS [Category], 'AlwaysOn_Replica_Cluster' AS [Information], replica_id, group_database_id, database_name, is_failover_ready, is_pending_secondary_suspend,
  872. is_database_joined, recovery_lsn, truncation_lsn
  873. FROM sys.dm_hadr_database_replica_cluster_states;
  874. END
  875. END;
  876. --------------------------------------------------------------------------------------------------------------------------------
  877. -- Linked servers info subsection
  878. --------------------------------------------------------------------------------------------------------------------------------
  879. RAISERROR (N'|-Starting Linked servers info', 10, 1) WITH NOWAIT
  880. IF (SELECT COUNT(*) FROM sys.servers AS s INNER JOIN sys.linked_logins AS l (NOLOCK) ON s.server_id = l.server_id INNER JOIN sys.server_principals AS p (NOLOCK) ON p.principal_id = l.local_principal_id WHERE s.is_linked = 1) > 0
  881. BEGIN
  882. IF @sqlmajorver > 9
  883. BEGIN
  884. EXEC ('SELECT ''Information'' AS [Category], ''Linked_servers'' AS [Information], s.name, s.product,
  885. s.provider, s.data_source, s.location, s.provider_string, s.catalog, s.connect_timeout,
  886. s.query_timeout, s.is_linked, s.is_remote_login_enabled, s.is_rpc_out_enabled,
  887. s.is_data_access_enabled, s.is_collation_compatible, s.uses_remote_collation, s.collation_name,
  888. s.lazy_schema_validation, s.is_system, s.is_publisher, s.is_subscriber, s.is_distributor,
  889. s.is_nonsql_subscriber, s.is_remote_proc_transaction_promotion_enabled,
  890. s.modify_date, CASE WHEN l.local_principal_id = 0 THEN ''local or wildcard'' ELSE p.name END AS [local_principal],
  891. CASE WHEN l.uses_self_credential = 0 THEN ''use own credentials'' ELSE ''use supplied username and pwd'' END AS uses_self_credential,
  892. l.remote_name, l.modify_date AS [linked_login_modify_date]
  893. FROM sys.servers AS s (NOLOCK)
  894. INNER JOIN sys.linked_logins AS l (NOLOCK) ON s.server_id = l.server_id
  895. INNER JOIN sys.server_principals AS p (NOLOCK) ON p.principal_id = l.local_principal_id
  896. WHERE s.is_linked = 1')
  897. END
  898. ELSE
  899. BEGIN
  900. EXEC ('SELECT ''Information'' AS [Category], ''Linked_servers'' AS [Information], s.name, s.product,
  901. s.provider, s.data_source, s.location, s.provider_string, s.catalog, s.connect_timeout,
  902. s.query_timeout, s.is_linked, s.is_remote_login_enabled, s.is_rpc_out_enabled,
  903. s.is_data_access_enabled, s.is_collation_compatible, s.uses_remote_collation, s.collation_name,
  904. s.lazy_schema_validation, s.is_system, s.is_publisher, s.is_subscriber, s.is_distributor,
  905. s.is_nonsql_subscriber, s.modify_date, CASE WHEN l.local_principal_id = 0 THEN ''local or wildcard'' ELSE p.name END AS [local_principal],
  906. CASE WHEN l.uses_self_credential = 0 THEN ''use own credentials'' ELSE ''use supplied username and pwd'' END AS uses_self_credential,
  907. l.remote_name, l.modify_date AS [linked_login_modify_date]
  908. FROM sys.servers AS s (NOLOCK)
  909. INNER JOIN sys.linked_logins AS l (NOLOCK) ON s.server_id = l.server_id
  910. INNER JOIN sys.server_principals AS p (NOLOCK) ON p.principal_id = l.local_principal_id
  911. WHERE s.is_linked = 1')
  912. END
  913. END
  914. ELSE
  915. BEGIN
  916. SELECT 'Information' AS [Category], 'Linked_servers' AS [Information], '[None]' AS [Status]
  917. END;
  918. --------------------------------------------------------------------------------------------------------------------------------
  919. -- Instance info subsection
  920. --------------------------------------------------------------------------------------------------------------------------------
  921. RAISERROR (N'|-Starting Instance info', 10, 1) WITH NOWAIT
  922. DECLARE @port VARCHAR(5), @replication int, @RegKey NVARCHAR(255), @cpuaffin VARCHAR(255), @cpucount int, @numa int
  923. DECLARE @i int, @cpuaffin_fixed VARCHAR(300)
  924. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild < 2500)
  925. BEGIN
  926. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  927. BEGIN
  928. BEGIN TRY
  929. SELECT @RegKey = CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) IS NULL THEN N'Software\Microsoft\MSSQLServer\MSSQLServer\SuperSocketNetLib\Tcp'
  930. ELSE N'Software\Microsoft\Microsoft SQL Server\' + CAST(SERVERPROPERTY('InstanceName') AS NVARCHAR(128)) + N'\MSSQLServer\SuperSocketNetLib\Tcp' END
  931. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'TcpPort', @port OUTPUT, NO_OUTPUT
  932. END TRY
  933. BEGIN CATCH
  934. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  935. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  936. RAISERROR (@ErrorMessage, 16, 1);
  937. END CATCH
  938. END
  939. ELSE
  940. BEGIN
  941. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing TCP port check]', 16, 1, N'sysadmin')
  942. --RETURN
  943. END
  944. END
  945. ELSE
  946. BEGIN
  947. BEGIN TRY
  948. SET @sqlcmd = N'SELECT @portOUT = MAX(CONVERT(int,CONVERT(float,value_data))) FROM sys.dm_server_registry WHERE registry_key LIKE ''%MSSQLServer\SuperSocketNetLib\Tcp\%'' AND value_name LIKE N''%TcpPort%'' AND CONVERT(float,value_data) > 0;';
  949. SET @params = N'@portOUT int OUTPUT';
  950. EXECUTE sp_executesql @sqlcmd, @params, @portOUT = @port OUTPUT;
  951. IF @port IS NULL
  952. BEGIN
  953. SET @sqlcmd = N'SELECT @portOUT = CONVERT(int,CONVERT(float,value_data)) FROM sys.dm_server_registry WHERE registry_key LIKE ''%MSSQLServer\SuperSocketNetLib\Tcp\%'' AND value_name LIKE N''%TcpDynamicPort%'' AND CONVERT(float,value_data) > 0;';
  954. SET @params = N'@portOUT int OUTPUT';
  955. EXECUTE sp_executesql @sqlcmd, @params, @portOUT = @port OUTPUT;
  956. END
  957. END TRY
  958. BEGIN CATCH
  959. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  960. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  961. RAISERROR (@ErrorMessage, 16, 1);
  962. END CATCH
  963. END
  964. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 1)
  965. BEGIN
  966. BEGIN TRY
  967. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Replication', N'IsInstalled', @replication OUTPUT, NO_OUTPUT
  968. END TRY
  969. BEGIN CATCH
  970. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  971. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  972. RAISERROR (@ErrorMessage, 16, 1);
  973. END CATCH
  974. END
  975. ELSE
  976. BEGIN
  977. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing replication check]', 16, 1, N'sysadmin')
  978. --RETURN
  979. END
  980. SELECT @cpucount = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64
  981. SELECT @numa = COUNT(DISTINCT parent_node_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64;
  982. ;WITH bits AS
  983. (SELECT 7 AS N, 128 AS E UNION ALL SELECT 6, 64 UNION ALL
  984. SELECT 5, 32 UNION ALL SELECT 4, 16 UNION ALL SELECT 3, 8 UNION ALL
  985. SELECT 2, 4 UNION ALL SELECT 1, 2 UNION ALL SELECT 0, 1),
  986. bytes AS
  987. (SELECT 1 M UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
  988. SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL
  989. SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9)
  990. -- CPU Affinity is shown highest to lowest CPU ID
  991. SELECT @cpuaffin = CASE WHEN [value] = 0 THEN REPLICATE('1', @cpucount)
  992. ELSE RIGHT((SELECT ((CONVERT(tinyint, SUBSTRING(CONVERT(binary(9), [value]), M, 1)) & E) / E) AS [text()]
  993. FROM bits CROSS JOIN bytes
  994. ORDER BY M, N DESC
  995. FOR XML PATH('')), @cpucount) END
  996. FROM sys.configurations (NOLOCK)
  997. WHERE name = 'affinity mask';
  998. SET @cpuaffin_fixed = @cpuaffin
  999. IF @numa > 1
  1000. BEGIN
  1001. -- format binary mask by node for better reading
  1002. SET @i = @cpucount/@numa + 1
  1003. WHILE @i <= @cpucount
  1004. BEGIN
  1005. SELECT @cpuaffin_fixed = STUFF(@cpuaffin_fixed, @i, 1, '_' + SUBSTRING(@cpuaffin, @i, 1))
  1006. SET @i = @i + @cpucount/@numa + 1
  1007. END
  1008. END
  1009. SELECT 'Information' AS [Category], 'Instance' AS [Information],
  1010. (CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) IS NULL THEN 'DEFAULT_INSTANCE'
  1011. ELSE CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) END) AS Instance_Name,
  1012. (CASE WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'CLUSTERED'
  1013. WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'NOT_CLUSTERED'
  1014. ELSE 'INVALID INPUT/ERROR' END) AS Failover_Clustered,
  1015. /*The version of SQL Server instance in the form: major.minor.build*/
  1016. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductVersion')) AS Product_Version,
  1017. /*Level of the version of SQL Server Instance*/
  1018. CASE WHEN (@sqlmajorver = 11 AND @sqlminorver >= 6020) OR (@sqlmajorver = 12 AND @sqlminorver BETWEEN 2556 AND 2569) OR (@sqlmajorver = 12 AND @sqlminorver >= 4427) OR @sqlmajorver >= 13 THEN
  1019. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductBuildType'))
  1020. ELSE 'NA' END AS Product_Build_Type,
  1021. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductLevel')) AS Product_Level,
  1022. CASE WHEN (@sqlmajorver = 11 AND @sqlminorver >= 6020) OR (@sqlmajorver = 12 AND @sqlminorver BETWEEN 2556 AND 2569) OR (@sqlmajorver = 12 AND @sqlminorver >= 4427) OR @sqlmajorver >= 13 THEN
  1023. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductUpdateLevel'))
  1024. ELSE 'NA' END AS Product_Update_Level,
  1025. CASE WHEN (@sqlmajorver = 11 AND @sqlminorver >= 6020) OR (@sqlmajorver = 12 AND @sqlminorver BETWEEN 2556 AND 2569) OR (@sqlmajorver = 12 AND @sqlminorver >= 4427) OR @sqlmajorver >= 13 THEN
  1026. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductUpdateReference'))
  1027. ELSE 'NA' END AS Product_Update_Ref_KB,
  1028. CONVERT(VARCHAR(128), SERVERPROPERTY('Edition')) AS Edition,
  1029. CONVERT(VARCHAR(128), SERVERPROPERTY('MachineName')) AS Machine_Name,
  1030. RTRIM(@port) AS TCP_Port,
  1031. @@SERVICENAME AS Service_Name,
  1032. /*To identify which sqlservr.exe belongs to this instance*/
  1033. SERVERPROPERTY('ProcessID') AS Process_ID,
  1034. CONVERT(VARCHAR(128), SERVERPROPERTY('ServerName')) AS Server_Name,
  1035. @cpuaffin_fixed AS Affinity_Mask_Bitmask,
  1036. CONVERT(VARCHAR(128), SERVERPROPERTY('Collation')) AS [Server_Collation],
  1037. (CASE WHEN @replication = 1 THEN 'Installed'
  1038. WHEN @replication = 0 THEN 'Not_Installed'
  1039. ELSE 'INVALID INPUT/ERROR' END) AS Replication_Components_Installation,
  1040. (CASE WHEN SERVERPROPERTY('IsFullTextInstalled') = 1 THEN 'Installed'
  1041. WHEN SERVERPROPERTY('IsFulltextInstalled') = 0 THEN 'Not_Installed'
  1042. ELSE 'INVALID INPUT/ERROR' END) AS Full_Text_Installation,
  1043. (CASE WHEN SERVERPROPERTY('IsIntegratedSecurityOnly') = 1 THEN 'Integrated_Security'
  1044. WHEN SERVERPROPERTY('IsIntegratedSecurityOnly') = 0 THEN 'SQL_Server_Security'
  1045. ELSE 'INVALID INPUT/ERROR' END) AS [Security],
  1046. (CASE WHEN SERVERPROPERTY('IsSingleUser') = 1 THEN 'Single_User'
  1047. WHEN SERVERPROPERTY('IsSingleUser') = 0 THEN 'Multi_User'
  1048. ELSE 'INVALID INPUT/ERROR' END) AS [Single_User],
  1049. (CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('LicenseType')) = 'PER_SEAT' THEN 'Per_Seat_Mode'
  1050. WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('LicenseType')) = 'PER_PROCESSOR' THEN 'Per_Processor_Mode'
  1051. ELSE 'Disabled' END) AS License_Type, -- From SQL Server 2008R2 always returns DISABLED.
  1052. CONVERT(NVARCHAR(128), SERVERPROPERTY('BuildClrVersion')) AS CLR_Version,
  1053. CASE WHEN @sqlmajorver >= 10 THEN
  1054. CASE WHEN SERVERPROPERTY('FilestreamConfiguredLevel') = 0 THEN 'Disabled'
  1055. WHEN SERVERPROPERTY('FilestreamConfiguredLevel') = 1 THEN 'Enabled_for_TSQL'
  1056. ELSE 'Enabled for TSQL and Win32' END
  1057. ELSE 'Not compatible' END AS Filestream_Configured_Level,
  1058. CASE WHEN @sqlmajorver >= 10 THEN
  1059. CASE WHEN SERVERPROPERTY('FilestreamEffectiveLevel') = 0 THEN 'Disabled'
  1060. WHEN SERVERPROPERTY('FilestreamEffectiveLevel') = 1 THEN 'Enabled_for_TSQL'
  1061. ELSE 'Enabled for TSQL and Win32' END
  1062. ELSE 'Not compatible' END AS Filestream_Effective_Level,
  1063. CASE WHEN @sqlmajorver >= 10 THEN
  1064. SERVERPROPERTY('FilestreamShareName')
  1065. ELSE 'Not compatible' END AS Filestream_Share_Name,
  1066. CASE WHEN @sqlmajorver >= 12 THEN
  1067. SERVERPROPERTY('IsXTPSupported')
  1068. ELSE 'Not compatible' END AS XTP_Compatible,
  1069. CASE WHEN @sqlmajorver >= 13 THEN
  1070. SERVERPROPERTY('IsPolybaseInstalled')
  1071. ELSE 'Not compatible' END AS Polybase_Installed,
  1072. CASE WHEN @sqlmajorver >= 13 THEN
  1073. SERVERPROPERTY('IsAdvancedAnalyticsInstalled')
  1074. ELSE 'Not compatible' END AS R_Services_Installed;
  1075. --------------------------------------------------------------------------------------------------------------------------------
  1076. -- Buffer Pool Extension info subsection
  1077. --------------------------------------------------------------------------------------------------------------------------------
  1078. RAISERROR (N'|-Starting Buffer Pool Extension info', 10, 1) WITH NOWAIT
  1079. IF @sqlmajorver > 11
  1080. BEGIN
  1081. SELECT 'Information' AS [Category], 'BP_Extension' AS [Information],
  1082. CASE WHEN state = 0 THEN 'BP_Extension_Disabled'
  1083. WHEN state = 1 THEN 'BP_Extension_is_Disabling'
  1084. WHEN state = 3 THEN 'BP_Extension_is_Enabling'
  1085. WHEN state = 5 THEN 'BP_Extension_Enabled'
  1086. END AS state,
  1087. [path], current_size_in_kb
  1088. FROM sys.dm_os_buffer_pool_extension_configuration
  1089. END
  1090. ELSE
  1091. BEGIN
  1092. SELECT 'Information' AS [Category], 'BP_Extension' AS [Information], '[NA]' AS state
  1093. END;
  1094. --------------------------------------------------------------------------------------------------------------------------------
  1095. -- Resource Governor info subsection
  1096. --------------------------------------------------------------------------------------------------------------------------------
  1097. RAISERROR (N'|-Starting Resource Governor info', 10, 1) WITH NOWAIT
  1098. IF @sqlmajorver > 9
  1099. BEGIN
  1100. SELECT 'Information' AS [Category], 'RG_Classifier_Function' AS [Information], CASE WHEN classifier_function_id = 0 THEN 'Default_Configuration' ELSE OBJECT_SCHEMA_NAME(classifier_function_id) + '.' + OBJECT_NAME(classifier_function_id) END AS classifier_function, is_reconfiguration_pending
  1101. FROM sys.dm_resource_governor_configuration
  1102. SET @sqlcmd = 'SELECT ''Information'' AS [Category], ''RG_Resource_Pool'' AS [Information], rp.pool_id, name, statistics_start_time, total_cpu_usage_ms, cache_memory_kb, compile_memory_kb,
  1103. used_memgrant_kb, total_memgrant_count, total_memgrant_timeout_count, active_memgrant_count, active_memgrant_kb, memgrant_waiter_count, max_memory_kb, used_memory_kb, target_memory_kb,
  1104. out_of_memory_count, min_cpu_percent, max_cpu_percent, min_memory_percent, max_memory_percent' + CASE WHEN @sqlmajorver > 10 THEN ', cap_cpu_percent, rpa.processor_group, rpa.scheduler_mask' ELSE '' END + '
  1105. FROM sys.dm_resource_governor_resource_pools rp' + CASE WHEN @sqlmajorver > 10 THEN ' LEFT JOIN sys.dm_resource_governor_resource_pool_affinity rpa ON rp.pool_id = rpa.pool_id' ELSE '' END
  1106. EXECUTE sp_executesql @sqlcmd
  1107. SET @sqlcmd = 'SELECT ''Information'' AS [Category], ''RG_Workload_Groups'' AS [Information], group_id, name, pool_id, statistics_start_time, total_request_count, total_queued_request_count,
  1108. active_request_count, queued_request_count, total_cpu_limit_violation_count, total_cpu_usage_ms, max_request_cpu_time_ms, blocked_task_count, total_lock_wait_count,
  1109. total_lock_wait_time_ms, total_query_optimization_count, total_suboptimal_plan_generation_count, total_reduced_memgrant_count, max_request_grant_memory_kb,
  1110. active_parallel_thread_count, importance, request_max_memory_grant_percent, request_max_cpu_time_sec, request_memory_grant_timeout_sec,
  1111. group_max_requests, max_dop' + CASE WHEN @sqlmajorver > 10 THEN ', effective_max_dop' ELSE '' END + '
  1112. FROM sys.dm_resource_governor_workload_groups'
  1113. EXECUTE sp_executesql @sqlcmd
  1114. END;
  1115. --------------------------------------------------------------------------------------------------------------------------------
  1116. -- Logon triggers subsection
  1117. --------------------------------------------------------------------------------------------------------------------------------
  1118. RAISERROR (N'|-Starting Logon triggers', 10, 1) WITH NOWAIT
  1119. IF (SELECT COUNT([name]) FROM sys.server_triggers WHERE is_disabled = 0 AND is_ms_shipped = 0) > 0
  1120. BEGIN
  1121. SELECT 'Information' AS [Category], 'Logon_Triggers' AS [Information], name AS [Trigger_Name], type_desc AS [Trigger_Type],create_date, modify_date
  1122. FROM sys.server_triggers WHERE is_disabled = 0 AND is_ms_shipped = 0
  1123. ORDER BY name;
  1124. END
  1125. ELSE
  1126. BEGIN
  1127. SELECT 'Information' AS [Category], 'Logon_Triggers' AS [Information], '[NA]' AS [Comment]
  1128. END;
  1129. --------------------------------------------------------------------------------------------------------------------------------
  1130. -- Database Information subsection
  1131. --------------------------------------------------------------------------------------------------------------------------------
  1132. RAISERROR (N'|-Starting Database Information', 10, 1) WITH NOWAIT
  1133. RAISERROR (N' |-Building DB list', 10, 1) WITH NOWAIT
  1134. DECLARE @curdbname VARCHAR(1000), @curdbid int, @currole tinyint, @cursecondary_role_allow_connections tinyint, @state tinyint
  1135. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  1136. DROP TABLE #tmpdbs0;
  1137. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  1138. CREATE TABLE #tmpdbs0 (id int IDENTITY(1,1), [dbid] int, [dbname] VARCHAR(1000), [compatibility_level] int, is_read_only bit, [state] tinyint, is_distributor bit, [role] tinyint, [secondary_role_allow_connections] tinyint, is_database_joined bit, is_failover_ready bit, isdone bit);
  1139. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  1140. DROP TABLE #tmpdbfiledetail;
  1141. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  1142. CREATE TABLE #tmpdbfiledetail([database_id] [int] NOT NULL, [file_id] int, [type_desc] NVARCHAR(60), [data_space_id] int,[name] sysname, [physical_name] NVARCHAR(260), [state_desc] NVARCHAR(60), [size] int, [max_size] int, [is_percent_growth] bit, [growth] int, [is_media_read_only] bit, [is_read_only] bit, [is_sparse] bit, [is_name_reserved] bit)
  1143. IF @sqlmajorver < 11
  1144. BEGIN
  1145. INSERT INTO #tmpdbs0 ([dbid], [dbname], [compatibility_level], is_read_only, [state], is_distributor, [role], [secondary_role_allow_connections], [isdone])
  1146. SELECT database_id, name, [compatibility_level], is_read_only, [state], is_distributor, 1, 1, 0 FROM master.sys.databases (NOLOCK)
  1147. END;
  1148. IF @sqlmajorver > 10
  1149. BEGIN
  1150. INSERT INTO #tmpdbs0 ([dbid], [dbname], [compatibility_level], is_read_only, [state], is_distributor, [role], [secondary_role_allow_connections], is_database_joined, is_failover_ready, [isdone])
  1151. SELECT sd.database_id, sd.name, sd.[compatibility_level], sd.is_read_only, sd.[state], sd.is_distributor, MIN(COALESCE(ars.[role],1)) AS [role], ar.secondary_role_allow_connections, rcs.is_database_joined, rcs.is_failover_ready, 0
  1152. FROM master.sys.databases sd (NOLOCK)
  1153. LEFT JOIN sys.dm_hadr_database_replica_states d ON sd.database_id = d.database_id
  1154. LEFT JOIN sys.availability_replicas ar ON d.group_id = ar.group_id AND d.replica_id = ar.replica_id
  1155. LEFT JOIN sys.dm_hadr_availability_replica_states ars ON d.group_id = ars.group_id AND d.replica_id = ars.replica_id
  1156. LEFT JOIN sys.dm_hadr_database_replica_cluster_states rcs ON rcs.database_name = sd.name AND rcs.replica_id = ar.replica_id
  1157. GROUP BY sd.database_id, sd.name, sd.is_read_only, sd.[state], sd.is_distributor, ar.secondary_role_allow_connections, sd.[compatibility_level], rcs.is_database_joined, rcs.is_failover_ready;
  1158. END;
  1159. /* Validate if database scope is set */
  1160. IF @dbScope IS NOT NULL AND ISNUMERIC(@dbScope) <> 1 AND @dbScope NOT LIKE '%,%'
  1161. BEGIN
  1162. RAISERROR('ERROR: Invalid parameter. Valid input consists of database IDs. If more than one ID is specified, the values must be comma separated.', 16, 42) WITH NOWAIT;
  1163. RETURN
  1164. END;
  1165. RAISERROR (N' |-Applying specific database scope list, if any', 10, 1) WITH NOWAIT
  1166. IF @dbScope IS NOT NULL
  1167. BEGIN
  1168. SELECT @sqlcmd = 'DELETE FROM #tmpdbs0 WHERE [dbid] > 4 AND [dbid] NOT IN (' + REPLACE(@dbScope,' ','') + ')'
  1169. EXEC sp_executesql @sqlcmd;
  1170. END;
  1171. IF @sqlmajorver < 11
  1172. BEGIN
  1173. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1174. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1175. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1176. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1177. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1178. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1179. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
  1180. db.is_auto_update_stats_async_on, db.is_parameterization_forced,
  1181. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1182. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on, ''NA'' AS [is_indirect_checkpoint_on],
  1183. db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1184. FROM master.sys.databases AS db (NOLOCK)
  1185. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1186. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1187. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1188. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1189. AND ls.cntr_value > 0 AND ls.cntr_value > 0' + CASE WHEN @dbScope IS NOT NULL THEN CHAR(10) + 'AND db.[database_id] IN (' + REPLACE(@dbScope,' ','') + ')' ELSE '' END + '
  1190. ORDER BY [Database_Name]
  1191. OPTION (RECOMPILE)'
  1192. END
  1193. ELSE IF @sqlmajorver = 11
  1194. BEGIN
  1195. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1196. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1197. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1198. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1199. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1200. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1201. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
  1202. db.is_auto_update_stats_async_on, db.is_parameterization_forced,
  1203. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1204. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1205. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1206. db.target_recovery_time_in_seconds,
  1207. db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1208. FROM master.sys.databases AS db (NOLOCK)
  1209. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1210. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1211. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1212. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1213. AND ls.cntr_value > 0 AND ls.cntr_value > 0' + CASE WHEN @dbScope IS NOT NULL THEN CHAR(10) + 'AND db.[database_id] IN (' + REPLACE(@dbScope,' ','') + ')' ELSE '' END + '
  1214. ORDER BY [Database_Name]
  1215. OPTION (RECOMPILE)'
  1216. END
  1217. ELSE IF @sqlmajorver = 12
  1218. BEGIN
  1219. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1220. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1221. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1222. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1223. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1224. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1225. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_create_stats_incremental_on,
  1226. db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.delayed_durability_desc AS [delayed_durability_status],
  1227. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1228. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1229. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1230. db.target_recovery_time_in_seconds, db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1231. FROM master.sys.databases AS db (NOLOCK)
  1232. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1233. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1234. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1235. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1236. AND ls.cntr_value > 0 AND ls.cntr_value > 0' + CASE WHEN @dbScope IS NOT NULL THEN CHAR(10) + 'AND db.[database_id] IN (' + REPLACE(@dbScope,' ','') + ')' ELSE '' END + '
  1237. ORDER BY [Database_Name]
  1238. OPTION (RECOMPILE)'
  1239. END
  1240. ELSE IF @sqlmajorver >= 13
  1241. BEGIN
  1242. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1243. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1244. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1245. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1246. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1247. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1248. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_create_stats_incremental_on,
  1249. db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.delayed_durability_desc AS [delayed_durability_status],
  1250. db.is_query_store_on, db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1251. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1252. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1253. db.target_recovery_time_in_seconds, db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced,
  1254. db.is_memory_optimized_elevate_to_snapshot_on, db.is_remote_data_archive_enabled, db.is_mixed_page_allocation_on
  1255. FROM master.sys.databases AS db (NOLOCK)
  1256. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1257. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1258. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1259. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1260. AND ls.cntr_value > 0 AND ls.cntr_value > 0' + CASE WHEN @dbScope IS NOT NULL THEN CHAR(10) + 'AND db.[database_id] IN (' + REPLACE(@dbScope,' ','') + ')' ELSE '' END + '
  1261. ORDER BY [Database_Name]
  1262. OPTION (RECOMPILE)'
  1263. END
  1264. EXECUTE sp_executesql @sqlcmd;
  1265. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1266. BEGIN
  1267. SELECT TOP 1 @curdbname = [dbname], @curdbid = [dbid], @currole = [role], @state = [state], @cursecondary_role_allow_connections = secondary_role_allow_connections FROM #tmpdbs0 WHERE isdone = 0
  1268. IF (@currole = 2 AND @cursecondary_role_allow_connections = 0) OR @state <> 0
  1269. BEGIN
  1270. SET @sqlcmd = 'SELECT [database_id], [file_id], type_desc, data_space_id, name, physical_name, state_desc, size, max_size, is_percent_growth,growth, is_media_read_only, is_read_only, is_sparse, is_name_reserved
  1271. FROM sys.master_files (NOLOCK) WHERE [database_id] = ' + CONVERT(VARCHAR(10), @curdbid)
  1272. END
  1273. ELSE
  1274. BEGIN
  1275. SET @sqlcmd = 'USE ' + QUOTENAME(@curdbname) + ';
  1276. SELECT ' + CONVERT(VARCHAR(10), @curdbid) + ' AS [database_id], [file_id], type_desc, data_space_id, name, physical_name, state_desc, size, max_size, is_percent_growth,growth, is_media_read_only, is_read_only, is_sparse, is_name_reserved
  1277. FROM sys.database_files (NOLOCK)'
  1278. END
  1279. BEGIN TRY
  1280. INSERT INTO #tmpdbfiledetail
  1281. EXECUTE sp_executesql @sqlcmd
  1282. END TRY
  1283. BEGIN CATCH
  1284. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1285. SELECT @ErrorMessage = 'Database Information subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1286. RAISERROR (@ErrorMessage, 16, 1);
  1287. END CATCH
  1288. UPDATE #tmpdbs0
  1289. SET isdone = 1
  1290. WHERE [dbid] = @curdbid
  1291. END;
  1292. SELECT 'Information' AS [Category], 'Database_Files' AS [Information], DB_NAME(database_id) AS [Database_Name], [file_id], type_desc, data_space_id AS [Filegroup], name, physical_name,
  1293. state_desc, (size * 8) / 1024 AS size_MB, CASE max_size WHEN -1 THEN 'Unlimited' ELSE CONVERT(VARCHAR(10), max_size) END AS max_size,
  1294. CASE WHEN is_percent_growth = 0 THEN CONVERT(VARCHAR(10),((growth * 8) / 1024)) ELSE growth END AS [growth], CASE WHEN is_percent_growth = 1 THEN 'Pct' ELSE 'MB' END AS growth_type,
  1295. is_media_read_only, is_read_only, is_sparse, is_name_reserved
  1296. FROM #tmpdbfiledetail
  1297. ORDER BY database_id, [file_id];
  1298. IF @sqlmajorver >= 12
  1299. BEGIN
  1300. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1301. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  1302. DROP TABLE #tblInMemDBs;
  1303. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  1304. CREATE TABLE #tblInMemDBs ([DBName] sysname, [Has_MemoryOptimizedObjects] bit, [MemoryAllocated_MemoryOptimizedObjects_KB] DECIMAL(18,2), [MemoryUsed_MemoryOptimizedObjects_KB] DECIMAL(18,2));
  1305. UPDATE #tmpdbs0
  1306. SET isdone = 0;
  1307. UPDATE #tmpdbs0
  1308. SET isdone = 1
  1309. WHERE [state] <> 0 OR [dbid] < 5;
  1310. UPDATE #tmpdbs0
  1311. SET isdone = 1
  1312. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1313. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1314. BEGIN
  1315. RAISERROR (N' |-Starting Storage analysis for In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  1316. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1317. BEGIN
  1318. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1319. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1320. SELECT ''' + @dbname + ''' AS [DBName], ISNULL((SELECT 1 FROM sys.filegroups FG WHERE FG.[type] = ''FX''), 0) AS [Has_MemoryOptimizedObjects],
  1321. ISNULL((SELECT CONVERT(DECIMAL(18,2), (SUM(tms.memory_allocated_for_table_kb) + SUM(tms.memory_allocated_for_indexes_kb))) FROM sys.dm_db_xtp_table_memory_stats tms), 0.00) AS [MemoryAllocated_MemoryOptimizedObjects_KB],
  1322. ISNULL((SELECT CONVERT(DECIMAL(18,2),(SUM(tms.memory_used_by_table_kb) + SUM(tms.memory_used_by_indexes_kb))) FROM sys.dm_db_xtp_table_memory_stats tms), 0.00) AS [MemoryUsed_MemoryOptimizedObjects_KB];'
  1323. BEGIN TRY
  1324. INSERT INTO #tblInMemDBs
  1325. EXECUTE sp_executesql @sqlcmd
  1326. END TRY
  1327. BEGIN CATCH
  1328. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1329. SELECT @ErrorMessage = 'Storage analysis for In-Memory OLTP Engine subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1330. RAISERROR (@ErrorMessage, 16, 1);
  1331. END CATCH
  1332. UPDATE #tmpdbs0
  1333. SET isdone = 1
  1334. WHERE [dbid] = @dbid
  1335. END
  1336. END;
  1337. IF (SELECT COUNT([DBName]) FROM #tblInMemDBs WHERE [Has_MemoryOptimizedObjects] = 1) > 0
  1338. BEGIN
  1339. SELECT 'Information' AS [Category], 'InMem_Database_Storage' AS [Information], DBName AS [Database_Name],
  1340. [MemoryAllocated_MemoryOptimizedObjects_KB], [MemoryUsed_MemoryOptimizedObjects_KB]
  1341. FROM #tblInMemDBs WHERE Has_MemoryOptimizedObjects = 1
  1342. ORDER BY DBName;
  1343. END
  1344. ELSE
  1345. BEGIN
  1346. SELECT 'Information' AS [Category], 'InMem_Database_Storage' AS [Information], '[NA]' AS [Comment]
  1347. END
  1348. END;
  1349. -- http://support.microsoft.com/kb/2857849
  1350. IF @sqlmajorver > 10 AND @IsHadrEnabled = 1
  1351. BEGIN
  1352. SELECT 'Information' AS [Category], 'AlwaysOn_AG_Databases' AS [Information], dc.database_name AS [Database_Name],
  1353. d.synchronization_health_desc, d.synchronization_state_desc, d.database_state_desc
  1354. FROM sys.dm_hadr_database_replica_states d
  1355. INNER JOIN sys.availability_databases_cluster dc ON d.group_database_id=dc.group_database_id
  1356. WHERE d.is_local=1
  1357. END;
  1358. --------------------------------------------------------------------------------------------------------------------------------
  1359. -- Database file autogrows last 72h subsection
  1360. --------------------------------------------------------------------------------------------------------------------------------
  1361. RAISERROR (N' |-Starting database file autogrows last 72h', 10, 1) WITH NOWAIT
  1362. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE is_default = 1)
  1363. BEGIN
  1364. DECLARE @tracefilename VARCHAR(500)
  1365. SELECT @tracefilename = LEFT([path],LEN([path]) - PATINDEX('%\%', REVERSE([path]))) + '\log.trc' FROM sys.traces WHERE is_default = 1;
  1366. WITH AutoGrow_CTE (databaseid, [filename], Growth, Duration, StartTime, EndTime)
  1367. AS
  1368. (
  1369. SELECT databaseid, [filename], SUM(IntegerData*8) AS Growth, Duration, StartTime, EndTime--, CASE WHEN EventClass =
  1370. FROM ::fn_trace_gettable(@tracefilename, default)
  1371. WHERE EventClass >= 92 AND EventClass <= 95 AND DATEDIFF(hh,StartTime,GETDATE()) < 72 -- Last 24h
  1372. GROUP BY databaseid, [filename], IntegerData, Duration, StartTime, EndTime
  1373. )
  1374. SELECT 'Information' AS [Category], 'Recorded_Autogrows_Lst72H' AS [Information], DB_NAME(database_id) AS Database_Name,
  1375. mf.name AS logical_file_name, mf.size*8 / 1024 AS size_MB, mf.type_desc,
  1376. ag.Growth AS [growth_KB], CASE WHEN is_percent_growth = 1 THEN 'Pct' ELSE 'MB' END AS growth_type,
  1377. Duration/1000 AS Growth_Duration_ms, ag.StartTime, ag.EndTime
  1378. FROM sys.master_files mf
  1379. LEFT OUTER JOIN AutoGrow_CTE ag ON mf.database_id=ag.databaseid AND mf.name=ag.[filename]
  1380. WHERE ag.Growth > 0 --Only where growth occurred
  1381. GROUP BY database_id, mf.name, mf.size, ag.Growth, ag.Duration, ag.StartTime, ag.EndTime, is_percent_growth, mf.growth, mf.type_desc
  1382. ORDER BY Database_Name, logical_file_name, ag.StartTime;
  1383. END
  1384. ELSE
  1385. BEGIN
  1386. SELECT 'Information' AS [Category], 'Recorded_Autogrows_Lst72H' AS [Information], '[WARNING: Could not gather information on autogrow times]' AS [Comment]
  1387. END;
  1388. --------------------------------------------------------------------------------------------------------------------------------
  1389. -- Database triggers subsection
  1390. --------------------------------------------------------------------------------------------------------------------------------
  1391. IF @ptochecks = 1
  1392. BEGIN
  1393. RAISERROR (N' |-Starting database triggers', 10, 1) WITH NOWAIT
  1394. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1395. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  1396. DROP TABLE #tblTriggers;
  1397. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  1398. CREATE TABLE #tblTriggers ([DBName] sysname, [triggerName] sysname, [schemaName] sysname, [tableName] sysname, [type_desc] NVARCHAR(60), [parent_class_desc] NVARCHAR(60), [create_date] DATETIME, [modify_date] DATETIME, [is_disabled] bit, [is_instead_of_trigger] bit, [is_not_for_replication] bit);
  1399. UPDATE #tmpdbs0
  1400. SET isdone = 0;
  1401. UPDATE #tmpdbs0
  1402. SET isdone = 1
  1403. WHERE [state] <> 0 OR [dbid] < 5;
  1404. UPDATE #tmpdbs0
  1405. SET isdone = 1
  1406. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1407. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1408. BEGIN
  1409. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1410. BEGIN
  1411. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1412. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1413. SELECT ''' + @dbname + ''' AS [DBName], st.name, ss.name, stb.name, st.type_desc, st.parent_class_desc, st.create_date, st.modify_date, st.is_disabled, st.is_instead_of_trigger, st.is_not_for_replication
  1414. FROM sys.triggers AS st
  1415. INNER JOIN sys.tables stb ON st.parent_id = stb.[object_id]
  1416. INNER JOIN sys.schemas ss ON stb.[schema_id] = ss.[schema_id]
  1417. WHERE st.is_ms_shipped = 0
  1418. ORDER BY stb.name, st.name;'
  1419. BEGIN TRY
  1420. INSERT INTO #tblTriggers
  1421. EXECUTE sp_executesql @sqlcmd
  1422. END TRY
  1423. BEGIN CATCH
  1424. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1425. SELECT @ErrorMessage = 'Database triggers subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1426. RAISERROR (@ErrorMessage, 16, 1);
  1427. END CATCH
  1428. UPDATE #tmpdbs0
  1429. SET isdone = 1
  1430. WHERE [dbid] = @dbid
  1431. END
  1432. END;
  1433. IF (SELECT COUNT([triggerName]) FROM #tblTriggers) > 0
  1434. BEGIN
  1435. SELECT 'Information' AS [Category], 'Database_Triggers' AS [Information], DBName AS [Database_Name],
  1436. triggerName AS [Trigger_Name], schemaName AS [Schema_Name], tableName AS [Table_Name],
  1437. type_desc AS [Trigger_Type], parent_class_desc AS [Trigger_Parent],
  1438. CASE is_instead_of_trigger WHEN 1 THEN 'INSTEAD_OF' ELSE 'AFTER' END AS [Trigger_Behavior],
  1439. create_date, modify_date,
  1440. CASE WHEN is_disabled = 1 THEN 'YES' ELSE 'NO' END AS [is_disabled],
  1441. CASE WHEN is_not_for_replication = 1 THEN 'YES' ELSE 'NO' END AS [is_not_for_replication]
  1442. FROM #tblTriggers
  1443. ORDER BY DBName, tableName, triggerName;
  1444. END
  1445. ELSE
  1446. BEGIN
  1447. SELECT 'Information' AS [Category], 'Database_Triggers' AS [Information], '[NA]' AS [Comment]
  1448. END
  1449. END;
  1450. --------------------------------------------------------------------------------------------------------------------------------
  1451. -- Enterprise features usage subsection
  1452. --------------------------------------------------------------------------------------------------------------------------------
  1453. IF @sqlmajorver > 9
  1454. BEGIN
  1455. RAISERROR (N'|-Starting Enterprise features usage', 10, 1) WITH NOWAIT
  1456. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1457. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  1458. DROP TABLE #tblPerSku;
  1459. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  1460. CREATE TABLE #tblPerSku ([DBName] sysname NULL, [Feature_Name] VARCHAR(100));
  1461. UPDATE #tmpdbs0
  1462. SET isdone = 0;
  1463. UPDATE #tmpdbs0
  1464. SET isdone = 1
  1465. WHERE [state] <> 0 OR [dbid] < 5;
  1466. UPDATE #tmpdbs0
  1467. SET isdone = 1
  1468. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1469. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1470. BEGIN
  1471. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1472. BEGIN
  1473. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1474. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1475. SELECT ''' + @dbname + ''' AS [DBName], feature_name FROM sys.dm_db_persisted_sku_features (NOLOCK);'
  1476. BEGIN TRY
  1477. INSERT INTO #tblPerSku
  1478. EXECUTE sp_executesql @sqlcmd
  1479. END TRY
  1480. BEGIN CATCH
  1481. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1482. SELECT @ErrorMessage = 'Enterprise features usage subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1483. RAISERROR (@ErrorMessage, 16, 1);
  1484. END CATCH
  1485. UPDATE #tmpdbs0
  1486. SET isdone = 1
  1487. WHERE [dbid] = @dbid
  1488. END
  1489. END;
  1490. IF @sqlmajorver > 10 AND ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13) AND @IsHadrEnabled = 1
  1491. BEGIN
  1492. INSERT INTO #tblPerSku
  1493. SELECT NULL, 'Always_On' AS feature_name
  1494. END;
  1495. IF (SELECT COUNT(DISTINCT d.name) FROM master.sys.databases d (NOLOCK) WHERE database_id NOT IN (2,3) AND source_database_id IS NOT NULL) > 0 -- Snapshot
  1496. BEGIN
  1497. INSERT INTO #tblPerSku
  1498. SELECT DISTINCT d.name, 'DB_Snapshot' AS feature_name FROM master.sys.databases d (NOLOCK) WHERE database_id NOT IN (2,3) AND source_database_id IS NOT NULL
  1499. END;
  1500. IF (@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13
  1501. BEGIN
  1502. DELETE FROM #tblPerSku
  1503. WHERE feature_name IN ('ColumnStoreIndex','InMemoryOLTP')
  1504. END;
  1505. IF (SELECT COUNT([Feature_Name]) FROM #tblPerSku) > 0
  1506. BEGIN
  1507. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Check], '[INFORMATION: Some databases are using Enterprise only features]' AS [Comment]
  1508. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Information], DBName AS [Database_Name], [Feature_Name]
  1509. FROM #tblPerSku
  1510. ORDER BY 2, 3
  1511. END
  1512. ELSE
  1513. BEGIN
  1514. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Check], '[NA]' AS [Comment]
  1515. END
  1516. END;
  1517. --------------------------------------------------------------------------------------------------------------------------------
  1518. -- Backups since last Full Information subsection
  1519. --------------------------------------------------------------------------------------------------------------------------------
  1520. RAISERROR (N'|-Starting Backups', 10, 1) WITH NOWAIT
  1521. IF @sqlmajorver > 10
  1522. BEGIN
  1523. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Backups_since_last_Full'' AS [Information],
  1524. [database_name] AS [Database_Name], CASE WHEN type = ''D'' THEN ''Database''
  1525. WHEN type = ''I'' THEN ''Diff_Database''
  1526. WHEN type = ''L'' THEN ''Log''
  1527. WHEN type = ''F'' THEN ''File''
  1528. WHEN type = ''G'' THEN ''Diff_file''
  1529. WHEN type = ''P'' THEN ''Partial''
  1530. WHEN type = ''Q'' THEN ''Diff_partial''
  1531. ELSE NULL END AS [bck_type],
  1532. [backup_start_date], [backup_finish_date],
  1533. CONVERT(decimal(20,2),backup_size/1024.00/1024.00) AS [backup_size_MB],
  1534. CONVERT(decimal(20,2),compressed_backup_size/1024.00/1024.00) AS [compressed_backup_size_MB],
  1535. [recovery_model], [user_name],
  1536. database_backup_lsn AS [full_base_lsn], [differential_base_lsn], [expiration_date],
  1537. [is_password_protected], [has_backup_checksums], [is_readonly], is_copy_only, [has_incomplete_metadata] AS [Tail_log]
  1538. FROM msdb.dbo.backupset bck1 (NOLOCK)
  1539. WHERE is_copy_only = 0 -- No COPY_ONLY backups
  1540. AND backup_start_date >= (SELECT MAX(backup_start_date) FROM msdb.dbo.backupset bck2 (NOLOCK) WHERE bck2.type IN (''D'',''F'',''P'') AND is_copy_only = 0 AND bck1.database_name = bck2.database_name)
  1541. ORDER BY database_name, backup_start_date DESC'
  1542. END
  1543. ELSE
  1544. BEGIN
  1545. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Backups_since_last_Full'' AS [Information],
  1546. [database_name] AS [Database_Name], CASE WHEN type = ''D'' THEN ''Database''
  1547. WHEN type = ''I'' THEN ''Diff_Database''
  1548. WHEN type = ''L'' THEN ''Log''
  1549. WHEN type = ''F'' THEN ''File''
  1550. WHEN type = ''G'' THEN ''Diff_file''
  1551. WHEN type = ''P'' THEN ''Partial''
  1552. WHEN type = ''Q'' THEN ''Diff_partial''
  1553. ELSE NULL END AS [bck_type],
  1554. [backup_start_date], [backup_finish_date],
  1555. CONVERT(decimal(20,2),backup_size/1024.00/1024.00) AS [backup_size_MB],
  1556. ''[NA]'' AS [compressed_backup_size_MB],
  1557. [recovery_model], [user_name],
  1558. database_backup_lsn AS [full_base_lsn], [differential_base_lsn], [expiration_date],
  1559. [is_password_protected], [has_backup_checksums], [is_readonly], is_copy_only, [has_incomplete_metadata] AS [Tail_log]
  1560. FROM msdb.dbo.backupset bck1 (NOLOCK)
  1561. WHERE is_copy_only = 0 -- No COPY_ONLY backups
  1562. AND backup_start_date >= (SELECT MAX(backup_start_date) FROM msdb.dbo.backupset bck2 (NOLOCK) WHERE bck2.type IN (''D'',''F'',''P'') AND is_copy_only = 0 AND bck1.database_name = bck2.database_name)
  1563. ORDER BY database_name, backup_start_date DESC'
  1564. END;
  1565. EXECUTE sp_executesql @sqlcmd;
  1566. --------------------------------------------------------------------------------------------------------------------------------
  1567. -- System Configuration subsection
  1568. --------------------------------------------------------------------------------------------------------------------------------
  1569. RAISERROR (N'|-Starting System Configuration', 10, 1) WITH NOWAIT
  1570. SELECT 'Information' AS [Category], 'All_System_Configurations' AS [Information],
  1571. name AS [Name],
  1572. configuration_id AS [Number],
  1573. minimum AS [Minimum],
  1574. maximum AS [Maximum],
  1575. is_dynamic AS [Dynamic],
  1576. is_advanced AS [Advanced],
  1577. value AS [ConfigValue],
  1578. value_in_use AS [RunValue],
  1579. description AS [Description]
  1580. FROM sys.configurations (NOLOCK)
  1581. ORDER BY name OPTION (RECOMPILE);
  1582. --------------------------------------------------------------------------------------------------------------------------------
  1583. -- Pre-checks section
  1584. --------------------------------------------------------------------------------------------------------------------------------
  1585. RAISERROR (N'Starting Pre-Checks - Building DB list excluding MS shipped', 10, 1) WITH NOWAIT
  1586. DECLARE @MSdb int
  1587. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  1588. DROP TABLE #tmpdbs1;
  1589. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  1590. CREATE TABLE #tmpdbs1 (id int IDENTITY(1,1), [dbid] int, [dbname] VARCHAR(1000), [role] tinyint, [secondary_role_allow_connections] tinyint, isdone bit)
  1591. RAISERROR (N'|-Excluding MS shipped by standard names and databases belonging to non-readable AG secondary replicas (if available)', 10, 1) WITH NOWAIT
  1592. -- Ignore MS shipped databases and databases belonging to non-readable AG secondary replicas
  1593. INSERT INTO #tmpdbs1 ([dbid], [dbname], [role], [secondary_role_allow_connections], [isdone])
  1594. SELECT [dbid], [dbname], [role], [secondary_role_allow_connections], 0
  1595. FROM #tmpdbs0 (NOLOCK)
  1596. WHERE is_read_only = 0 AND [state] = 0 AND [dbid] > 4 AND is_distributor = 0
  1597. AND [role] <> 2 AND (secondary_role_allow_connections <> 0 OR secondary_role_allow_connections IS NULL)
  1598. AND lower([dbname]) NOT IN ('virtualmanagerdb', --Virtual Machine Manager
  1599. 'scspfdb', --Service Provider Foundation
  1600. 'semanticsdb', --Semantic Search
  1601. 'servicemanager','service manager','dwstagingandconfig','dwrepository','dwdatamart','dwasdatabase','omdwdatamart','cmdwdatamart', --SCSM
  1602. 'ssodb','bamanalysis','bamarchive','bamalertsapplication','bamalertsnsmain','bamprimaryimport','bamstarschema','biztalkmgmtdb','biztalkmsgboxdb','biztalkdtadb','biztalkruleenginedb','bamprimaryimport','biztalkedidb','biztalkhwsdb','tpm','biztalkanalysisdb','bamprimaryimportsuccessfully', --BizTalk
  1603. 'aspstate','aspnet', --ASP.NET
  1604. 'mscrm_config', --Dynamics CRM
  1605. 'cpsdyn','lcslog','lcscdr','lis','lyss','mgc','qoemetrics','rgsconfig','rgsdyn','rtc','rtcab','rtcab1','rtcdyn','rtcshared','rtcxds','xds', --Lync
  1606. 'activitylog','branchdb','clienttracelog','eventlog','listingssettings','servicegroupdb','tservercontroller','vodbackend', --MediaRoom
  1607. 'operationsmanager','operationsmanagerdw','operationsmanagerac', --SCOM
  1608. 'orchestrator', --Orchestrator
  1609. 'sso','wss_search','wss_search_config','sharedservices_db','sharedservices_search_db','wss_content','profiledb', 'social db','sync db', --Sharepoint
  1610. 'susdb', --WSUS
  1611. 'projectserver_archive','projectserver_draft','projectserver_published','projectserver_reporting', --Project Server
  1612. 'reportserver','reportservertempdb','rsdb','rstempdb', --SSRS
  1613. 'fastsearchadmindatabase', --Fast Search
  1614. 'ppsmonitoring','ppsplanningservice','ppsplanningsystem', --PerformancePoint Services
  1615. 'dynamics', --Dynamics GP
  1616. 'microsoftdynamicsax','microsoftdynamicsaxbaseline', --Dynamics AX
  1617. 'fimservice','fimsynchronizationservice', --Forefront Identity Manager
  1618. 'sbgatewaydatabase','sbmanagementdb', --Service Bus
  1619. 'wfinstancemanagementdb','wfmanagementdb','wfresourcemanagementdb' --Workflow Manager
  1620. )
  1621. AND [dbname] NOT LIKE 'repANDtingservice[_]%' --SSRS
  1622. AND [dbname] NOT LIKE 'tfs[_]%' --TFS
  1623. AND [dbname] NOT LIKE 'defaultpowerpivotserviceapplicationdb%' --PowerPivot
  1624. AND [dbname] NOT LIKE 'perfANDmancepoint service[_]%' --PerfANDmancePoint Services
  1625. AND [dbname] NOT LIKE '%database nav%' --Dynamics NAV
  1626. AND [dbname] NOT LIKE '%[_]mscrm' --Dynamics CRM
  1627. AND [dbname] NOT LIKE 'dpmdb[_]%' --DPM
  1628. AND [dbname] NOT LIKE 'sbmessagecontainer%' --Service Bus
  1629. AND [dbname] NOT LIKE 'sma%' --SCSMA
  1630. AND [dbname] NOT LIKE 'releasemanagement%' --TFS Release Management
  1631. AND [dbname] NOT LIKE 'projectwebapp%' --Project Server
  1632. AND [dbname] NOT LIKE 'sms[_]%' AND [dbname] NOT LIKE 'cm[_]%' --SCCM
  1633. AND [dbname] NOT LIKE 'fepdw%' AND [dbname] NOT LIKE 'FEPDB[_]%' --Forefront Endpoint Protection
  1634. --Sharepoint
  1635. AND [dbname] NOT LIKE 'sharepoint[_]admincontent%' AND [dbname] NOT LIKE 'sharepoint[_]config%' AND [dbname] NOT LIKE 'wss[_]content%' AND [dbname] NOT LIKE 'wss[_]search%'
  1636. AND [dbname] NOT LIKE 'sharedservices[_]db%' AND [dbname] NOT LIKE 'sharedservices[_]search[_]db%' AND [dbname] NOT LIKE 'sharedservices[_][_]db%' AND [dbname] NOT LIKE 'sharedservices[_][_]search[_]db%'
  1637. AND [dbname] NOT LIKE 'sharedservicescontent%' AND [dbname] NOT LIKE 'application[_]registry[_]service[_]db%' AND [dbname] NOT LIKE 'search[_]service[_]application[_]propertystANDedb[_]%'
  1638. AND [dbname] NOT LIKE 'subscriptionsettings[_]%' AND [dbname] NOT LIKE 'webanalyticsserviceapplication[_]stagingdb[_]%' AND [dbname] NOT LIKE 'webanalyticsserviceapplication[_]repANDtingdb[_]%'
  1639. AND [dbname] NOT LIKE 'bdc[_]service[_]db[_]%' AND [dbname] NOT LIKE 'managed metadata service[_]%' AND [dbname] NOT LIKE 'perfANDmancepoint service application[_]%'
  1640. AND [dbname] NOT LIKE 'search[_]service[_]application[_]crawlstANDedb[_]%' AND [dbname] NOT LIKE 'search[_]service[_]application[_]db[_]%' AND [dbname] NOT LIKE 'secure[_]stANDe[_]service[_]db[_]%' AND [dbname] NOT LIKE 'stateservice%'
  1641. AND [dbname] NOT LIKE 'user profile service application[_]profiledb[_]%' AND [dbname] NOT LIKE 'user profile service application[_]syncdb[_]%' AND [dbname] NOT LIKE 'user profile service application[_]socialdb[_]%'
  1642. AND [dbname] NOT LIKE 'wANDdautomationservices[_]%' AND [dbname] NOT LIKE 'wss[_]logging%' AND [dbname] NOT LIKE 'wss[_]usageapplication%' AND [dbname] NOT LIKE 'appmng[_]service[_]db%'
  1643. AND [dbname] NOT LIKE 'search[_]service[_]application[_]analyticsrepANDtingstANDedb[_]%' AND [dbname] NOT LIKE 'search[_]service[_]application[_]linksstANDedb[_]%' AND [dbname] NOT LIKE 'sharepoint[_]logging[_]%'
  1644. AND [dbname] NOT LIKE 'settingsservicedb%' AND [dbname] NOT LIKE 'sharepoint[_]logging[_]%' AND [dbname] NOT LIKE 'translationservice[_]%' AND [dbname] NOT LIKE 'sharepoint translation services[_]%' AND [dbname] NOT LIKE 'sessionstateservice%'
  1645. IF EXISTS (SELECT name FROM msdb.sys.objects (NOLOCK) WHERE name='MSdistributiondbs' AND is_ms_shipped = 1)
  1646. BEGIN
  1647. DELETE FROM #tmpdbs1 WHERE [dbid] IN (SELECT DB_ID(name) FROM msdb.dbo.MSdistributiondbs)
  1648. END;
  1649. RAISERROR (N'|-Excluding MS shipped by notable object names', 10, 1) WITH NOWAIT
  1650. -- Removing other noticeable MS shipped DBs
  1651. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  1652. BEGIN
  1653. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  1654. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1655. IF (OBJECT_ID(''dbo.AR_Class'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.AR_Entity'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.AR_System'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_ar_CreateEntity'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.proc_ar_CreateMethod'',''P'') IS NOT NULL)
  1656. OR (OBJECT_ID(''dbo.Versions'',''U'') IS NOT NULL
  1657. AND (OBJECT_ID(''dbo.ECMApplicationLog'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.ECMTerm'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_ECM_GetPackage'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.proc_ECM_GetGroups'',''P'') IS NOT NULL)
  1658. OR (OBJECT_ID(''dbo.Configuration'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.MonthlyPartitions'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.Search_GetCrawlPipeline'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.prc_EnumSandboxedRequests'',''P'') IS NOT NULL)
  1659. OR (OBJECT_ID(''dbo.MSSConfiguration'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.MSSOrdinal'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_MSS_GetConfigurationProperty'',''P'') IS NOT NULL)
  1660. OR (OBJECT_ID(''dbo.Tenants'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_Admin_ListPartitionedTables'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.proc_DefragmentIndices'',''P'') IS NOT NULL)
  1661. OR (OBJECT_ID(''dbo.WAScope'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.WASetting'',''U'') IS NOT NULL AND SCHEMA_ID(''Processing'') IS NOT NULL)
  1662. OR (OBJECT_ID(''dbo.Groups'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.Items'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_GetGroups'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.proc_GetVersion'',''P'') IS NOT NULL)
  1663. OR (OBJECT_ID(''dbo.Mapping'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.PropertySet'',''U'') IS NOT NULL AND SCHEMA_ID(''SubscriptionSettingsService_Application_Pool'') IS NOT NULL)
  1664. OR (OBJECT_ID(''dbo.Sessions'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_AddItem'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.proc_GetItemWithLock'',''P'') IS NOT NULL)
  1665. OR (OBJECT_ID(''dbo.SiteMap'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SiteCounts'',''U'') IS NOT NULL AND SCHEMA_ID(''WSS_Content_Application_Pools'') IS NOT NULL)
  1666. OR (OBJECT_ID(''dbo.PPSAnnotations'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.PPSParameterValues'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_PPS_GetAnnotation'',''P'') IS NOT NULL)
  1667. OR (OBJECT_ID(''dbo.AM_Licenses'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.AM_DeploymentIds'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_AM_GetApps'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.proc_AM_SetDeploymentId'',''P'') IS NOT NULL)
  1668. OR (OBJECT_ID(''dbo.MSSDefinitions'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.MSSSecurityDescriptors'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_MSS_GetCrawls'',''P'') IS NOT NULL)
  1669. )
  1670. OR (OBJECT_ID(''dbo.SSSApplication'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SSSAudit'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SSSConfig'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_sss_GetConfig'',''P'') IS NOT NULL)
  1671. OR (OBJECT_ID(''dbo.Actions'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.VersionInfo'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.mms_extensions'',''U'') IS NOT NULL AND SCHEMA_ID(''persistenceUsers'') IS NOT NULL AND SCHEMA_ID(''state_persistence_users'') IS NOT NULL)
  1672. OR (OBJECT_ID(''dbo.AllDocs'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.AllLists'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.NameValuePair'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.proc_GetWorkItems'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.proc_EnumLists'',''P'') IS NOT NULL)
  1673. OR (OBJECT_ID(''dbo.SSO_Application'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SSO_Ticket'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SSO_Config'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.sso_InsertAudit'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.sso_RetrieveSSOConfig'',''P'') IS NOT NULL)
  1674. -- End Sharepoint
  1675. OR ((OBJECT_ID(''dbo.ASPStateTempSessions'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.ASPStateTempApplications'',''U'') IS NOT NULL) OR OBJECT_ID(''dbo.CreateTempTables'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.DeleteExpiredSessions'',''P'') IS NOT NULL)
  1676. OR (OBJECT_ID(''dbo.aspnet_Applications'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.aspnet_Profile'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.aspnet_Users'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.aspnet_CheckSchemaVersion'',''P'') IS NOT NULL)
  1677. -- End ASP.NET
  1678. OR (OBJECT_ID(''DataRefresh.Runs'',''U'') IS NOT NULL AND OBJECT_ID(''GeminiService.Version'',''U'') IS NOT NULL AND OBJECT_ID(''Usage.Requests'',''U'') IS NOT NULL AND SCHEMA_ID(''HealthRule'') IS NOT NULL)
  1679. -- End PowerPivot
  1680. OR (OBJECT_ID(''dbo.LICENSES'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.VERSION'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.TASK_RUNPROGRAM'',''U'') IS NOT NULL AND SCHEMA_ID(''Microsoft.SystemCenter.Orchestrator'') IS NOT NULL)
  1681. -- End Orchestrator
  1682. OR (OBJECT_ID(''dbo.tbl_Cloud_Cloud'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.tbl_PXE_PxeServer'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.tbl_VMM_Server'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.prc_VMM_AddVmmServer'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.prc_Cloud_Cloud_GetParent'',''P'') IS NOT NULL)
  1683. -- End VMM
  1684. OR (OBJECT_ID(''scspf.EventHandlers'',''U'') IS NOT NULL AND OBJECT_ID(''scspf.Servers'',''U'') IS NOT NULL AND OBJECT_ID(''scspf.Tenants'',''U'') IS NOT NULL)
  1685. -- End Service Provider Foundation
  1686. OR ((OBJECT_ID(''dbo.SSOX_AuditTable'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SSOX_GlobalInfo'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SSOX_Servers'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.sp_BackupBizTalkFull'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.ssox_spGetDBVersion'',''P'') IS NOT NULL)
  1687. OR (OBJECT_ID(''dbo.BizTalkDBVersion'',''U'') IS NOT NULL AND SCHEMA_ID(''BTS_ADMIN_USERS'') IS NOT NULL AND SCHEMA_ID(''BTS_OPERATORS'') IS NOT NULL))
  1688. -- End BizTalk
  1689. OR (OBJECT_ID(''dbo.Layer'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.ModelGroup'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SchemaVersion'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.XI_GetUserName'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.XU_AssignAxId'',''P'') IS NOT NULL)
  1690. -- End Dynamics AX
  1691. OR (OBJECT_ID(''dbo.Notification'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SystemUserRoles'',''U'') IS NOT NULL
  1692. AND (OBJECT_ID(''dbo.p_GetCrmUserId'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.p_GetPrivilegesInRole'',''P'') IS NOT NULL)
  1693. OR (OBJECT_ID(''dbo.p_AccountOVRollup'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.p_GetDbSize'',''P'') IS NOT NULL))
  1694. -- End Dynamics CRM
  1695. OR (OBJECT_ID(''dbo.User Personalization'',''U'') IS NOT NULL AND EXISTS(SELECT 1 FROM sys.all_objects (NOLOCK) WHERE type=''U'' AND (name like ''%$G[_]L Entry'' OR name LIKE ''%$Item Ledger Entry'')))
  1696. -- End Dynamics NAV
  1697. OR (OBJECT_ID(''dbo.DBVERSION'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.PATH'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SY_SQL_Options'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.zDP_ActivitySD'',''P'') IS NOT NULL)
  1698. -- End Dynamics GP
  1699. OR (OBJECT_ID(''dbo.Agents'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.DistributionPoints'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SysResList'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.PXE_GetPXECert'',''P'') IS NOT NULL)
  1700. -- End SCCM
  1701. OR (OBJECT_ID(''dbo.dtFEP_Infra_InstalledJobs'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.dtFEP_Common_User'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.dtAN_Infra_JobLastRun'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.spFEP_Infra_CreateJob'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.spAN_Infra_ScheduleJob'',''P'') IS NOT NULL)
  1702. -- End Forefront Endpoint Protection
  1703. OR (OBJECT_ID(''admin.categories'',''U'') IS NOT NULL AND OBJECT_ID(''admin.keyword'',''U'') IS NOT NULL AND OBJECT_ID(''admin.storeentry'',''U'') IS NOT NULL)
  1704. -- End Fast Search
  1705. OR (OBJECT_ID(''fim.Objects'',''U'') IS NOT NULL AND SCHEMA_ID(''debug'') IS NOT NULL)
  1706. OR (OBJECT_ID(''dbo.mms_extensions'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.mms_partition'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.mms_addmvlink'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.mms_getcsguidfromanchor'',''P'') IS NOT NULL)
  1707. -- End Forefront Identity Manager
  1708. OR (OBJECT_ID(''dbo.Annotations'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.BsmUsers'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.FCObjects'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.BsmUserCreate'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.BsmUserDelete'',''P'') IS NOT NULL)
  1709. OR (OBJECT_ID(''dbo.DBSchemaVersion'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.QueueStatus'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.ServerStates'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.bsp_UpdateQueueSizeLimit'',''P'') IS NOT NULL)
  1710. -- End PerformancePoint Services
  1711. OR (OBJECT_ID(''dbo.Versions'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.MSP_DAL_GetDatabaseCacheExceptions'',''P'') IS NOT NULL AND (OBJECT_ID(''dbo.MSP_DAL_GetSprocInfo'',''P'') IS NOT NULL OR OBJECT_ID(''dbo.MSP_DAL_GetSprocList'',''P'') IS NOT NULL))
  1712. -- End Project Server
  1713. OR (OBJECT_ID(''apm.MESSAGES'',''U'') IS NOT NULL AND SCHEMA_ID(''CS'') IS NOT NULL OR SCHEMA_ID(''CM'') IS NOT NULL)
  1714. OR (OBJECT_ID(''dbo.Event_00'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.MT_Database'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.PerformanceData_00'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.p_MPSelectViews'',''P'') IS NOT NULL)
  1715. OR (OBJECT_ID(''dbo.AemApplication'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.EventLoggingComputer'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.HealthState'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.p_MOMManagementGroupInfoSelect'',''P'') IS NOT NULL)
  1716. OR (OBJECT_ID(''dbo.dtMachine'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.dtPartition'',''U'') IS NOT NULL AND SCHEMA_ID(''AdtServer'') IS NOT NULL)
  1717. -- End SCOM
  1718. OR (OBJECT_ID(''dbo.version'',''U'') IS NOT NULL AND EXISTS(SELECT 1 FROM sys.internal_tables (NOLOCK) WHERE name LIKE ''language[_]model[_]%''))
  1719. -- End Semantic Search
  1720. OR (OBJECT_ID(''dbo.tbComputerTarget'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.tbTarget'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.tbUpdate'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.spGetUpdateByID'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.spSearchUpdates'',''P'') IS NOT NULL)
  1721. -- End WSUS
  1722. OR (OBJECT_ID(''dbo.tbl_DPM_InstalledUpdates'',''U'') IS NOT NULL AND SCHEMA_ID(''MSDPMExecRole'') IS NOT NULL AND SCHEMA_ID(''MSDPMRecoveryRole'') IS NOT NULL)
  1723. -- End DPM
  1724. OR ((OBJECT_ID(''dbo.DomainTable'',''U'') IS NOT NULL AND OBJECT_ID(''etl.Source'',''U'') IS NOT NULL)
  1725. OR (OBJECT_ID(''dbo.Module'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.MT_Computer'',''U'') IS NOT NULL AND OBJECT_ID(''LFXSTG.vex_Collection'',''U'') IS NOT NULL AND SCHEMA_ID(''LFX'') IS NOT NULL)
  1726. OR (OBJECT_ID(''dbo.DomainTable'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.State'',''U'') IS NOT NULL AND SCHEMA_ID(''etl'') IS NOT NULL))
  1727. -- End SCSM
  1728. OR (OBJECT_ID(''dbo.ChunkData'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SegmentedChunk'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SnapshotData'',''U'') IS NOT NULL AND SCHEMA_ID(''RSExecRole'') IS NOT NULL)
  1729. -- End SSRS
  1730. OR (OBJECT_ID(''dbo.prc_ChangeHostId'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.prc_EnablePrefixCompression'',''P'') IS NOT NULL
  1731. AND (OBJECT_ID(''dbo.tbl_RegistryItems'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.tbl_OAuthToken'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.tbl_Content'',''U'') IS NOT NULL)
  1732. OR (OBJECT_ID(''dbo.DimBuild'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.FactCurrentWorkItem'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.FactBuildProject'',''U'') IS NOT NULL))
  1733. OR (OBJECT_ID(''dbo.LoadTestCase'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.LoadTestReport'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.LoadTestScenario'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.prc_GetAgents'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.prc_QueryLoadTestRuns'',''P'') IS NOT NULL)
  1734. -- End TFS
  1735. OR (OBJECT_ID(''dbo.Release'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.Server'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.TeamProject'',''U'') IS NOT NULL AND SCHEMA_ID(''System.Activities.DurableInstancing'') IS NOT NULL)
  1736. -- End TFS Release Management
  1737. OR (OBJECT_ID(''dbo.ContainersTable'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.Quotas'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.Tenants'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.GetAllEntities'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.UpdateGatewayEntity'',''P'') IS NOT NULL)
  1738. OR (OBJECT_ID(''dbo.LockResourcesTable'',''U'') IS NOT NULL AND OBJECT_ID(''Store.Nodes'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.OperationsTable'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.AcquireLock'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.UpdateOperation'',''P'') IS NOT NULL)
  1739. OR (OBJECT_ID(''dbo.CursorsTable'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.LogsTable'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.MessagesTable'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.GetCursorState'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.LockEntity'',''P'') IS NOT NULL)
  1740. -- End Service Bus
  1741. OR (OBJECT_ID(''dbo.DebugTraces'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.Instances'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.StoreVersionTable'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.GetInstanceCount'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.GetStoreVersion'',''P'') IS NOT NULL)
  1742. OR (OBJECT_ID(''dbo.StoreVersionTable'',''U'') IS NOT NULL AND OBJECT_ID(''Store.Clusters'',''U'') IS NOT NULL AND OBJECT_ID(''Store.Services'',''U'') IS NOT NULL AND OBJECT_ID(''Store.GetNode'',''P'') IS NOT NULL AND OBJECT_ID(''Store.UpdateCluster'',''P'') IS NOT NULL)
  1743. OR (OBJECT_ID(''dbo.Activities'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.Scopes'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.WorkflowServices'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.GetActivities'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.TenantCheck'',''P'') IS NOT NULL)
  1744. -- End Workflow Manager
  1745. OR (OBJECT_ID(''Core.Runbooks'',''U'') IS NOT NULL AND OBJECT_ID(''Core.Activities'',''U'') IS NOT NULL AND OBJECT_ID(''Core.Connections'',''U'') IS NOT NULL AND SCHEMA_ID(''Common'') IS NOT NULL)
  1746. -- End SCSMA
  1747. BEGIN
  1748. SELECT @MSdbOUT = ' + CONVERT(VARCHAR(10), @dbid) + '
  1749. END'
  1750. SET @params = N'@MSdbOUT int OUTPUT';
  1751. EXECUTE sp_executesql @sqlcmd, @params, @MSdbOUT=@MSdb OUTPUT
  1752. IF @MSdb = @dbid
  1753. BEGIN
  1754. DELETE FROM #tmpdbs1
  1755. WHERE [dbid] = @dbid;
  1756. END
  1757. ELSE
  1758. BEGIN
  1759. UPDATE #tmpdbs1
  1760. SET isdone = 1
  1761. WHERE [dbid] = @dbid
  1762. END
  1763. END;
  1764. UPDATE #tmpdbs1
  1765. SET isdone = 0;
  1766. RAISERROR (N'|-Applying 2nd layer of specific database scope, if any', 10, 1) WITH NOWAIT
  1767. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  1768. DROP TABLE #tmpdbs_userchoice;
  1769. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  1770. CREATE TABLE #tmpdbs_userchoice ([dbid] int PRIMARY KEY, [dbname] VARCHAR(1000))
  1771. IF @dbScope IS NOT NULL
  1772. BEGIN
  1773. SELECT @sqlcmd = 'SELECT [dbid], [dbname]
  1774. FROM #tmpdbs0 (NOLOCK)
  1775. WHERE is_read_only = 0 AND [state] = 0 AND [dbid] > 4 AND is_distributor = 0
  1776. AND [role] <> 2 AND (secondary_role_allow_connections <> 0 OR secondary_role_allow_connections IS NULL)
  1777. AND [dbid] IN (' + REPLACE(@dbScope,' ','') + ')'
  1778. INSERT INTO #tmpdbs_userchoice ([dbid], [dbname])
  1779. EXEC sp_executesql @sqlcmd;
  1780. SELECT @sqlcmd = 'DELETE FROM #tmpdbs1 WHERE [dbid] NOT IN (' + REPLACE(@dbScope,' ','') + ')'
  1781. EXEC sp_executesql @sqlcmd;
  1782. END;
  1783. --------------------------------------------------------------------------------------------------------------------------------
  1784. -- Checks section
  1785. --------------------------------------------------------------------------------------------------------------------------------
  1786. RAISERROR (N'Starting Checks section', 10, 1) WITH NOWAIT
  1787. RAISERROR (N'|-Starting Processor Checks', 10, 1) WITH NOWAIT
  1788. --------------------------------------------------------------------------------------------------------------------------------
  1789. -- Number of available Processors for this instance vs. MaxDOP setting subsection
  1790. --------------------------------------------------------------------------------------------------------------------------------
  1791. RAISERROR (N' |-Starting Number of available Processors for this instance vs. MaxDOP setting', 10, 1) WITH NOWAIT
  1792. DECLARE /*@cpucount int, @numa int, */@affined_cpus int
  1793. /*
  1794. DECLARE @i int, @cpuaffin_fixed VARCHAR(300)
  1795. SET @cpuaffin_fixed = @cpuaffin
  1796. SET @i = @cpucount/@numa + 1
  1797. WHILE @i <= @cpucount
  1798. BEGIN
  1799. SELECT @cpuaffin_fixed = STUFF(@cpuaffin_fixed, @i, 1, '_' + SUBSTRING(@cpuaffin, @i, 1))
  1800. SET @i = @i + @cpucount/@numa + 1
  1801. END
  1802. */
  1803. SELECT @affined_cpus = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE is_online = 1 AND scheduler_id < 255 AND parent_node_id < 64;
  1804. --SELECT @cpucount = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64
  1805. SELECT 'Processor_checks' AS [Category], 'Parallelism_MaxDOP' AS [Check],
  1806. CASE WHEN [value] > @affined_cpus THEN '[WARNING: MaxDOP setting exceeds available processor count (affinity)]'
  1807. WHEN @numa = 1 AND @affined_cpus > 8 AND ([value] = 0 OR [value] > 8) THEN '[WARNING: MaxDOP setting is not recommended for current processor count (affinity)]'
  1808. WHEN @numa > 1 AND (@cpucount/@numa) < 8 AND ([value] = 0 OR [value] > (@cpucount/@numa)) THEN '[WARNING: MaxDOP setting is not recommended for current NUMA node to processor count (affinity) ratio]'
  1809. WHEN @numa > 1 AND (@cpucount/@numa) >= 8 AND ([value] = 0 OR [value] > 8 OR [value] > (@cpucount/@numa)) THEN '[WARNING: MaxDOP setting is not recommended for current NUMA node to processor count (affinity) ratio]'
  1810. ELSE '[OK]'
  1811. END AS [Deviation]
  1812. FROM sys.configurations (NOLOCK) WHERE name = 'max degree of parallelism';
  1813. SELECT 'Processor_checks' AS [Category], 'Parallelism_MaxDOP' AS [Information],
  1814. CASE WHEN [value] > @affined_cpus THEN @affined_cpus
  1815. WHEN @numa = 1 AND @affined_cpus > 8 AND ([value] = 0 OR [value] > 8) THEN 8
  1816. WHEN @numa > 1 AND (@cpucount/@numa) < 8 AND ([value] = 0 OR [value] > (@cpucount/@numa)) THEN @cpucount/@numa
  1817. WHEN @numa > 1 AND (@cpucount/@numa) >= 8 AND ([value] = 0 OR [value] > 8 OR [value] > (@cpucount/@numa)) THEN 8
  1818. ELSE 0
  1819. END AS [Recommended_MaxDOP],
  1820. [value] AS [Current_MaxDOP], @cpucount AS [Available_Processors], @affined_cpus AS [Affined_Processors],
  1821. -- Processor Affinity is shown highest to lowest CPU ID
  1822. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1823. FROM sys.configurations (NOLOCK) WHERE name = 'max degree of parallelism';
  1824. --------------------------------------------------------------------------------------------------------------------------------
  1825. -- Processor Affinity in NUMA architecture subsection
  1826. --------------------------------------------------------------------------------------------------------------------------------
  1827. RAISERROR (N' |-Starting Processor Affinity in NUMA architecture', 10, 1) WITH NOWAIT
  1828. IF @numa > 1
  1829. BEGIN
  1830. WITH ncpuCTE (ncpus) AS (SELECT COUNT(cpu_id) AS ncpus from sys.dm_os_schedulers WHERE is_online = 1 AND scheduler_id < 255 AND parent_node_id < 64 GROUP BY parent_node_id, is_online HAVING COUNT(cpu_id) = 1),
  1831. cpuCTE (node, afin) AS (SELECT DISTINCT(parent_node_id), is_online FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64 GROUP BY parent_node_id, is_online)
  1832. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Check],
  1833. CASE WHEN (SELECT COUNT(*) FROM ncpuCTE) > 0 THEN '[WARNING: Current NUMA configuration is not recommended. At least one node has a single assigned CPU]'
  1834. WHEN (SELECT COUNT(DISTINCT(node)) FROM cpuCTE WHERE afin = 0 AND node NOT IN (SELECT DISTINCT(node) FROM cpuCTE WHERE afin = 1)) > 0 THEN '[WARNING: Current NUMA configuration is not recommended. At least one node does not have assigned CPUs]'
  1835. ELSE '[OK]' END AS [Deviation]
  1836. FROM sys.dm_os_sys_info (NOLOCK)
  1837. OPTION (RECOMPILE);
  1838. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Information], cpu_count AS [Logical_CPU_Count],
  1839. (SELECT COUNT(DISTINCT parent_node_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64) AS [NUMA_Nodes],
  1840. -- Processor Affinity is shown highest to lowest CPU ID
  1841. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1842. FROM sys.dm_os_sys_info (NOLOCK)
  1843. OPTION (RECOMPILE);
  1844. END
  1845. ELSE
  1846. BEGIN
  1847. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Check], '[Not_NUMA]' AS [Deviation]
  1848. FROM sys.dm_os_sys_info (NOLOCK)
  1849. OPTION (RECOMPILE);
  1850. END;
  1851. --------------------------------------------------------------------------------------------------------------------------------
  1852. -- Additional Processor information subsection
  1853. --------------------------------------------------------------------------------------------------------------------------------
  1854. RAISERROR (N' |-Starting Additional Processor information', 10, 1) WITH NOWAIT
  1855. -- Processor Info
  1856. SELECT 'Processor_checks' AS [Category], 'Processor_Summary' AS [Information], cpu_count AS [Logical_CPU_Count], hyperthread_ratio AS [Cores2Socket_Ratio],
  1857. cpu_count/hyperthread_ratio AS [CPU_Sockets],
  1858. CASE WHEN @numa > 1 THEN (SELECT COUNT(DISTINCT parent_node_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64) ELSE 0 END AS [NUMA_Nodes],
  1859. @affined_cpus AS [Affined_Processors],
  1860. -- Processor Affinity is shown highest to lowest Processor ID
  1861. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1862. FROM sys.dm_os_sys_info (NOLOCK)
  1863. OPTION (RECOMPILE);
  1864. IF @ptochecks = 1
  1865. BEGIN
  1866. RAISERROR (N' |-Starting Processor utilization rate in the last 2 hours', 10, 1) WITH NOWAIT
  1867. -- Processor utilization rate in the last 2 hours
  1868. DECLARE @ts_now bigint
  1869. DECLARE @tblAggCPU TABLE (SQLProc tinyint, SysIdle tinyint, OtherProc tinyint, Minutes tinyint)
  1870. SELECT @ts_now = ms_ticks FROM sys.dm_os_sys_info (NOLOCK);
  1871. WITH cteCPU (record_id, SystemIdle, SQLProcessUtilization, [timestamp]) AS (SELECT
  1872. record.value('(./Record/@id)[1]', 'int') AS record_id,
  1873. record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS SystemIdle,
  1874. record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS SQLProcessUtilization,
  1875. [TIMESTAMP] FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  1876. FROM sys.dm_os_ring_buffers (NOLOCK)
  1877. WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
  1878. AND record LIKE '%<SystemHealth>%') AS x
  1879. )
  1880. INSERT INTO @tblAggCPU
  1881. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 10
  1882. FROM cteCPU
  1883. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -10, GETDATE())
  1884. UNION ALL
  1885. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 20
  1886. FROM cteCPU
  1887. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -10, GETDATE()) AND
  1888. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -20, GETDATE())
  1889. UNION ALL
  1890. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 30
  1891. FROM cteCPU
  1892. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -20, GETDATE()) AND
  1893. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -30, GETDATE())
  1894. UNION ALL
  1895. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 40
  1896. FROM cteCPU
  1897. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -30, GETDATE()) AND
  1898. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -40, GETDATE())
  1899. UNION ALL
  1900. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 50
  1901. FROM cteCPU
  1902. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -40, GETDATE()) AND
  1903. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -50, GETDATE())
  1904. UNION ALL
  1905. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 60
  1906. FROM cteCPU
  1907. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -50, GETDATE()) AND
  1908. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -60, GETDATE())
  1909. UNION ALL
  1910. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 70
  1911. FROM cteCPU
  1912. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -60, GETDATE()) AND
  1913. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -70, GETDATE())
  1914. UNION ALL
  1915. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 80
  1916. FROM cteCPU
  1917. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -70, GETDATE()) AND
  1918. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -80, GETDATE())
  1919. UNION ALL
  1920. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 90
  1921. FROM cteCPU
  1922. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -80, GETDATE()) AND
  1923. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -90, GETDATE())
  1924. UNION ALL
  1925. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 100
  1926. FROM cteCPU
  1927. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -90, GETDATE()) AND
  1928. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -100, GETDATE())
  1929. UNION ALL
  1930. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 110
  1931. FROM cteCPU
  1932. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -100, GETDATE()) AND
  1933. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -110, GETDATE())
  1934. UNION ALL
  1935. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 120
  1936. FROM cteCPU
  1937. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -110, GETDATE()) AND
  1938. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -120, GETDATE())
  1939. IF (SELECT COUNT(SysIdle) FROM @tblAggCPU WHERE SysIdle < 30) > 0
  1940. BEGIN
  1941. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[WARNING: Detected CPU usage over 70 pct]' AS [Deviation];
  1942. END
  1943. ELSE IF (SELECT COUNT(SysIdle) FROM @tblAggCPU WHERE SysIdle < 10) > 0
  1944. BEGIN
  1945. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[WARNING: Detected CPU usage over 90 pct]' AS [Deviation];
  1946. END
  1947. ELSE
  1948. BEGIN
  1949. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[OK]' AS [Deviation];
  1950. END;
  1951. SELECT 'Processor_checks' AS [Category], 'Agg_Processor_Usage_last_2h' AS [Information], SQLProc AS [SQL_Process_Utilization], SysIdle AS [System_Idle], OtherProc AS [Other_Process_Utilization], Minutes AS [Time_Slice_min]
  1952. FROM @tblAggCPU;
  1953. END;
  1954. RAISERROR (N'|-Starting Memory Checks', 10, 1) WITH NOWAIT
  1955. --------------------------------------------------------------------------------------------------------------------------------
  1956. -- Server Memory subsection
  1957. --------------------------------------------------------------------------------------------------------------------------------
  1958. RAISERROR (N' |-Starting Server Memory', 10, 1) WITH NOWAIT
  1959. DECLARE @maxservermem bigint, @minservermem bigint, @systemmem bigint, @systemfreemem bigint, @numa_nodes_afinned tinyint, @LowMemoryThreshold int
  1960. DECLARE @commit_target bigint -- Includes stolen and reserved memory in the memory manager
  1961. DECLARE @committed bigint -- Does not include reserved memory in the memory manager
  1962. DECLARE @mwthreads_count int, @xtp int
  1963. IF @sqlmajorver = 9
  1964. BEGIN
  1965. SET @sqlcmd = N'SELECT @systemmemOUT = t1.record.value(''(./Record/MemoryRecord/TotalPhysicalMemory)[1]'', ''bigint'')/1024,
  1966. @systemfreememOUT = t1.record.value(''(./Record/MemoryRecord/AvailablePhysicalMemory)[1]'', ''bigint'')/1024
  1967. FROM (SELECT MAX([TIMESTAMP]) AS [TIMESTAMP], CONVERT(xml, record) AS record
  1968. FROM sys.dm_os_ring_buffers (NOLOCK)
  1969. WHERE ring_buffer_type = N''RING_BUFFER_RESOURCE_MONITOR''
  1970. AND record LIKE ''%RESOURCE_MEMPHYSICAL%''
  1971. GROUP BY record) AS t1';
  1972. END
  1973. ELSE
  1974. BEGIN
  1975. SET @sqlcmd = N'SELECT @systemmemOUT = total_physical_memory_kb/1024, @systemfreememOUT = available_physical_memory_kb/1024 FROM sys.dm_os_sys_memory';
  1976. END
  1977. SET @params = N'@systemmemOUT bigint OUTPUT, @systemfreememOUT bigint OUTPUT';
  1978. EXECUTE sp_executesql @sqlcmd, @params, @systemmemOUT=@systemmem OUTPUT, @systemfreememOUT=@systemfreemem OUTPUT;
  1979. IF @sqlmajorver >= 9 AND @sqlmajorver < 11
  1980. BEGIN
  1981. SET @sqlcmd = N'SELECT @commit_targetOUT=bpool_commit_target*8, @committedOUT=bpool_committed*8 FROM sys.dm_os_sys_info (NOLOCK)'
  1982. END
  1983. ELSE IF @sqlmajorver >= 11
  1984. BEGIN
  1985. SET @sqlcmd = N'SELECT @commit_targetOUT=committed_target_kb, @committedOUT=committed_kb FROM sys.dm_os_sys_info (NOLOCK)'
  1986. END
  1987. SET @params = N'@commit_targetOUT bigint OUTPUT, @committedOUT bigint OUTPUT';
  1988. EXECUTE sp_executesql @sqlcmd, @params, @commit_targetOUT=@commit_target OUTPUT, @committedOUT=@committed OUTPUT;
  1989. SELECT @minservermem = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE [Name] = 'min server memory (MB)';
  1990. SELECT @maxservermem = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE [Name] = 'max server memory (MB)';
  1991. SELECT @mwthreads_count = max_workers_count FROM sys.dm_os_sys_info;
  1992. SELECT @numa_nodes_afinned = COUNT (DISTINCT parent_node_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64 AND is_online = 1
  1993. /*
  1994. From Windows Internals book by David Solomon and Mark Russinovich:
  1995. "The default level of available memory that signals a low-memory-resource notification event is approximately 32 MB per 4 GB,
  1996. to a maximum of 64 MB. The default level that signals a high-memory-resource notification event is three times the default low-memory value."
  1997. */
  1998. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  1999. BEGIN
  2000. BEGIN TRY
  2001. SELECT @RegKey = N'System\CurrentControlSet\Control\SessionManager\MemoryManagement'
  2002. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'LowMemoryThreshold', @LowMemoryThreshold OUTPUT, NO_OUTPUT
  2003. IF @LowMemoryThreshold IS NULL
  2004. SELECT @LowMemoryThreshold = CASE WHEN @systemmem <= 4096 THEN 32 ELSE 64 END
  2005. END TRY
  2006. BEGIN CATCH
  2007. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2008. SELECT @ErrorMessage = 'Server Memory subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  2009. RAISERROR (@ErrorMessage, 16, 1);
  2010. END CATCH
  2011. END
  2012. ELSE
  2013. BEGIN
  2014. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing LowMemoryThreshold check]', 16, 1, N'sysadmin')
  2015. --RETURN
  2016. END;
  2017. SELECT 'Memory_checks' AS [Category], 'Memory_issues_MaxServerMem' AS [Check],
  2018. CASE WHEN @maxservermem = 2147483647 THEN '[WARNING: MaxMem setting is default. Please revise memory settings]'
  2019. WHEN @maxservermem > @systemmem THEN '[WARNING: MaxMem setting exceeds available system memory]'
  2020. WHEN @numa > 1 AND (@maxservermem/@numa) * @numa_nodes_afinned > (@systemmem/@numa) * @numa_nodes_afinned THEN '[WARNING: Current MaxMem setting will leverage node foreign memory.
  2021. Maximum value for MaxMem setting on this configuration is ' + CONVERT(NVARCHAR,(@systemmem/@numa) * @numa_nodes_afinned) + ' for a single instance]'
  2022. ELSE '[OK]'
  2023. END AS [Deviation], @maxservermem AS [sql_max_mem_MB];
  2024. SELECT 'Memory_checks' AS [Category], 'Memory_issues_MinServerMem' AS [Check],
  2025. CASE WHEN @minservermem = 0 AND (LOWER(@SystemManufacturer) = 'microsoft' OR LOWER(@SystemManufacturer) = 'vmware') THEN '[WARNING: Min Server Mem setting is not set in a VM, allowing memory pressure on the Host to attempt to deallocate memory on a guest SQL Server]'
  2026. WHEN @minservermem = 0 AND @clustered = 1 THEN '[INFORMATION: Min Server Mem setting is default in a clustered instance. Leverage Min Server Mem for the purpose of limiting memory concurrency between instances]'
  2027. WHEN @minservermem = @maxservermem THEN '[WARNING: Min Server Mem setting is equal to Max Server Mem. This will not allow dynamic memory. Please revise memory settings]'
  2028. WHEN @numa > 1 AND (@minservermem/@numa) * @numa_nodes_afinned > (@systemmem/@numa) * @numa_nodes_afinned THEN '[WARNING: Current MinMem setting will leverage node foreign memory]'
  2029. ELSE '[OK]'
  2030. END AS [Deviation], @minservermem AS [sql_min_mem_MB];
  2031. SELECT 'Memory_checks' AS [Category], 'Memory_issues_FreeMem' AS [Check],
  2032. CASE WHEN (@systemfreemem*100)/@systemmem <= 5 THEN '[WARNING: Less than 5 percent of Free Memory available. Please revise memory settings]'
  2033. /* 64 is the default LowMemThreshold for windows on a system with 8GB of mem or more*/
  2034. WHEN @systemfreemem <= 64*3 THEN '[WARNING: System Free Memory is dangerously low. Please revise memory settings]'
  2035. ELSE '[OK]'
  2036. END AS [Deviation], @systemmem AS system_total_physical_memory_MB, @systemfreemem AS system_available_physical_memory_MB;
  2037. SELECT 'Memory_checks' AS [Category], 'Memory_issues_CommitedMem' AS [Check],
  2038. CASE WHEN @commit_target > @committed AND @sqlmajorver >= 11 THEN '[INFORMATION: Memory manager will try to obtain additional memory]'
  2039. WHEN @commit_target < @committed AND @sqlmajorver >= 11 THEN '[INFORMATION: Memory manager will try to shrink the amount of memory committed]'
  2040. WHEN @commit_target > @committed AND @sqlmajorver < 11 THEN '[INFORMATION: Buffer Pool will try to obtain additional memory]'
  2041. WHEN @commit_target < @committed AND @sqlmajorver < 11 THEN '[INFORMATION: Buffer Pool will try to shrink]'
  2042. ELSE '[OK]'
  2043. END AS [Deviation], @commit_target/1024 AS sql_commit_target_MB, @committed/1024 AS sql_commited_MB;
  2044. SELECT 'Memory_checks' AS [Category], 'Memory_reference' AS [Check],
  2045. CASE WHEN @arch IS NULL THEN '[WARNING: Could not determine architecture needed for check]'
  2046. WHEN (@systemmem <= 2048 AND @maxservermem > @systemmem-512-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))) OR
  2047. (@systemmem BETWEEN 2049 AND 4096 AND @maxservermem > @systemmem-819-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))) OR
  2048. (@systemmem BETWEEN 4097 AND 8192 AND @maxservermem > @systemmem-1228-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))) OR
  2049. (@systemmem BETWEEN 8193 AND 12288 AND @maxservermem > @systemmem-2048-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))) OR
  2050. (@systemmem BETWEEN 12289 AND 24576 AND @maxservermem > @systemmem-2560-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))) OR
  2051. (@systemmem BETWEEN 24577 AND 32768 AND @maxservermem > @systemmem-3072-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))) OR
  2052. (@systemmem > 32768 AND @maxservermem > @systemmem-4096-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))) THEN '[WARNING: Not at the recommended MaxMem setting for this server memory configuration, with a single instance]'
  2053. ELSE '[OK]'
  2054. END AS [Deviation],
  2055. CASE WHEN @systemmem <= 2048 THEN @systemmem-512-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))
  2056. WHEN @systemmem BETWEEN 2049 AND 4096 THEN @systemmem-819-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))
  2057. WHEN @systemmem BETWEEN 4097 AND 8192 THEN @systemmem-1228-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))
  2058. WHEN @systemmem BETWEEN 8193 AND 12288 THEN @systemmem-2048-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))
  2059. WHEN @systemmem BETWEEN 12289 AND 24576 THEN @systemmem-2560-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))
  2060. WHEN @systemmem BETWEEN 24577 AND 32768 THEN @systemmem-3072-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))
  2061. WHEN @systemmem > 32768 THEN @systemmem-4096-(@mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END))
  2062. END AS [Recommended_MaxMem_MB_SingleInstance],
  2063. CASE WHEN @systemmem <= 2048 THEN 512
  2064. WHEN @systemmem BETWEEN 2049 AND 4096 THEN 819
  2065. WHEN @systemmem BETWEEN 4097 AND 8192 THEN 1228
  2066. WHEN @systemmem BETWEEN 8193 AND 12288 THEN 2048
  2067. WHEN @systemmem BETWEEN 12289 AND 24576 THEN 2560
  2068. WHEN @systemmem BETWEEN 24577 AND 32768 THEN 3072
  2069. WHEN @systemmem > 32768 THEN 4096
  2070. END AS [Mem_MB_for_OS],
  2071. CASE WHEN @systemmem <= 2048 THEN @mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END)
  2072. WHEN @systemmem BETWEEN 2049 AND 4096 THEN @mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END)
  2073. WHEN @systemmem BETWEEN 4097 AND 8192 THEN @mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END)
  2074. WHEN @systemmem BETWEEN 8193 AND 12288 THEN @mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END)
  2075. WHEN @systemmem BETWEEN 12289 AND 24576 THEN @mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END)
  2076. WHEN @systemmem BETWEEN 24577 AND 32768 THEN @mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END)
  2077. WHEN @systemmem > 32768 THEN @mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END)
  2078. END AS [Potential_threads_mem_MB],
  2079. @mwthreads_count AS [Configured_workers];
  2080. IF @sqlmajorver = 9
  2081. BEGIN
  2082. SELECT 'Memory_checks' AS [Category], 'Memory_Summary' AS [Information],
  2083. @maxservermem AS sql_max_mem_MB, @minservermem AS sql_min_mem_MB,
  2084. @commit_target/1024 AS sql_commit_target_MB, --BPool in SQL 2005 to 2008R2
  2085. @committed/1024 AS sql_commited_MB, --BPool in SQL 2005 to 2008R2
  2086. @systemmem AS system_total_physical_memory_MB,
  2087. @systemfreemem AS system_available_physical_memory_MB
  2088. END
  2089. ELSE
  2090. BEGIN
  2091. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Memory_Summary'' AS [Information],
  2092. @maxservermemIN AS sql_max_mem_MB, @minservermemIN AS sql_min_mem_MB,
  2093. @commit_targetIN/1024 AS sql_commit_target_MB, --BPool in SQL 2005 to 2008R2
  2094. @committedIN/1024 AS sql_commited_MB, --BPool in SQL 2005 to 2008R2
  2095. physical_memory_in_use_kb/1024 AS sql_physical_memory_in_use_MB,
  2096. large_page_allocations_kb/1024 AS sql_large_page_allocations_MB,
  2097. locked_page_allocations_kb/1024 AS sql_locked_page_allocations_MB,
  2098. @systemmemIN AS system_total_physical_memory_MB,
  2099. @systemfreememIN AS system_available_physical_memory_MB,
  2100. total_virtual_address_space_kb/1024 AS sql_total_VAS_MB,
  2101. virtual_address_space_reserved_kb/1024 AS sql_VAS_reserved_MB,
  2102. virtual_address_space_committed_kb/1024 AS sql_VAS_committed_MB,
  2103. virtual_address_space_available_kb/1024 AS sql_VAS_available_MB,
  2104. page_fault_count AS sql_page_fault_count,
  2105. memory_utilization_percentage AS sql_memory_utilization_percentage,
  2106. process_physical_memory_low AS sql_process_physical_memory_low,
  2107. process_virtual_memory_low AS sql_process_virtual_memory_low
  2108. FROM sys.dm_os_process_memory (NOLOCK)'
  2109. SET @params = N'@maxservermemIN bigint, @minservermemIN bigint, @systemmemIN bigint, @systemfreememIN bigint, @commit_targetIN bigint, @committedIN bigint';
  2110. EXECUTE sp_executesql @sqlcmd, @params, @maxservermemIN=@maxservermem, @minservermemIN=@minservermem,@systemmemIN=@systemmem, @systemfreememIN=@systemfreemem, @commit_targetIN=@commit_target, @committedIN=@committed
  2111. END;
  2112. IF @numa > 1 AND @sqlmajorver > 10
  2113. BEGIN
  2114. EXEC ('SELECT ''Memory_checks'' AS [Category], ''NUMA_Memory_Distribution'' AS [Information], memory_node_id, virtual_address_space_reserved_kb, virtual_address_space_committed_kb, locked_page_allocations_kb, pages_kb, foreign_committed_kb, shared_memory_reserved_kb, shared_memory_committed_kb, processor_group FROM sys.dm_os_memory_nodes;')
  2115. END
  2116. ELSE IF @numa > 1 AND @sqlmajorver = 10
  2117. BEGIN
  2118. EXEC ('SELECT ''Memory_checks'' AS [Category], ''NUMA_Memory_Distribution'' AS [Information], memory_node_id, virtual_address_space_reserved_kb, virtual_address_space_committed_kb, locked_page_allocations_kb, single_pages_kb, multi_pages_kb, shared_memory_reserved_kb, shared_memory_committed_kb, processor_group FROM sys.dm_os_memory_nodes;')
  2119. END;
  2120. IF @ptochecks = 1
  2121. BEGIN
  2122. RAISERROR (N' |-Starting RM Task', 10, 1) WITH NOWAIT
  2123. IF @LowMemoryThreshold IS NOT NULL
  2124. SELECT 'Memory_checks' AS [Category], 'Memory_RM_Tresholds' AS [Information], @LowMemoryThreshold AS [MEMPHYSICAL_LOW_Threshold], @LowMemoryThreshold * 3 AS [MEMPHYSICAL_HIGH_Threshold]
  2125. SELECT 'Memory_checks' AS [Category], 'Memory_RM_Notifications' AS [Information],
  2126. CASE WHEN x.[TIMESTAMP] BETWEEN -2147483648 AND 2147483647 AND si.ms_ticks BETWEEN -2147483648 AND 2147483647 THEN DATEADD(ms, x.[TIMESTAMP] - si.ms_ticks, GETDATE())
  2127. ELSE DATEADD(s, ([TIMESTAMP]/1000) - (si.ms_ticks/1000), GETDATE()) END AS Event_Time,
  2128. record.value('(./Record/ResourceMonitor/Notification)[1]', 'VARCHAR(max)') AS [Notification],
  2129. record.value('(./Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint')/1024 AS [Total_Physical_Mem_MB],
  2130. record.value('(./Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint')/1024 AS [Avail_Physical_Mem_MB],
  2131. record.value('(./Record/MemoryRecord/AvailableVirtualAddressSpace)[1]', 'bigint')/1024 AS [Avail_VAS_MB],
  2132. record.value('(./Record/MemoryRecord/TotalPageFile)[1]', 'bigint')/1024 AS [Total_Pagefile_MB],
  2133. record.value('(./Record/MemoryRecord/AvailablePageFile)[1]', 'bigint')/1024 AS [Avail_Pagefile_MB]
  2134. FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  2135. FROM sys.dm_os_ring_buffers (NOLOCK)
  2136. WHERE ring_buffer_type = N'RING_BUFFER_RESOURCE_MONITOR') AS x
  2137. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2138. --WHERE CASE WHEN x.[timestamp] BETWEEN -2147483648 AND 2147483648 THEN DATEADD(ms, x.[timestamp] - si.ms_ticks, GETDATE())
  2139. -- ELSE DATEADD(s, (x.[timestamp]/1000) - (si.ms_ticks/1000), GETDATE()) END >= DATEADD(hh, -12, GETDATE())
  2140. ORDER BY 2 DESC;
  2141. RAISERROR (N' |-Starting Hand Movements from Cache Clock Hands', 10, 1) WITH NOWAIT
  2142. IF (SELECT COUNT(rounds_count) FROM sys.dm_os_memory_cache_clock_hands (NOLOCK) WHERE rounds_count > 0) > 0
  2143. BEGIN
  2144. IF @sqlmajorver >= 11
  2145. BEGIN
  2146. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Clock_Hand_Notifications'' AS [Information], mcch.name, mcch.[type],
  2147. mcch.clock_hand, mcch.clock_status, SUM(mcch.rounds_count) AS rounds_count,
  2148. SUM(mcch.removed_all_rounds_count) AS cache_entries_removed_all_rounds,
  2149. SUM(mcch.removed_last_round_count) AS cache_entries_removed_last_round,
  2150. SUM(mcch.updated_last_round_count) AS cache_entries_updated_last_round,
  2151. SUM(mcc.pages_kb) AS cache_pages_kb,
  2152. SUM(mcc.pages_in_use_kb) AS cache_pages_in_use_kb,
  2153. SUM(mcc.entries_count) AS cache_entries_count,
  2154. SUM(mcc.entries_in_use_count) AS cache_entries_in_use_count,
  2155. CASE WHEN mcch.last_tick_time BETWEEN -2147483648 AND 2147483647 AND si.ms_ticks BETWEEN -2147483648 AND 2147483647 THEN DATEADD(ms, mcch.last_tick_time - si.ms_ticks, GETDATE())
  2156. WHEN mcch.last_tick_time/1000 BETWEEN -2147483648 AND 2147483647 AND si.ms_ticks/1000 BETWEEN -2147483648 AND 2147483647 THEN DATEADD(s, (mcch.last_tick_time/1000) - (si.ms_ticks/1000), GETDATE())
  2157. ELSE NULL END AS last_clock_hand_move
  2158. FROM sys.dm_os_memory_cache_counters mcc (NOLOCK)
  2159. INNER JOIN sys.dm_os_memory_cache_clock_hands mcch (NOLOCK) ON mcc.cache_address = mcch.cache_address
  2160. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2161. WHERE mcch.rounds_count > 0
  2162. GROUP BY mcch.name, mcch.[type], mcch.clock_hand, mcch.clock_status, mcc.pages_kb, mcc.pages_in_use_kb, mcch.last_tick_time, si.ms_ticks, mcc.entries_count, mcc.entries_in_use_count
  2163. ORDER BY SUM(mcch.removed_all_rounds_count) DESC, mcch.[type];'
  2164. END
  2165. ELSE
  2166. BEGIN
  2167. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Clock_Hand_Notifications'' AS [Information], mcch.name, mcch.[type],
  2168. mcch.clock_hand, mcch.clock_status, SUM(mcch.rounds_count) AS rounds_count,
  2169. SUM(mcch.removed_all_rounds_count) AS cache_entries_removed_all_rounds,
  2170. SUM(mcch.removed_last_round_count) AS cache_entries_removed_last_round,
  2171. SUM(mcch.updated_last_round_count) AS cache_entries_updated_last_round,
  2172. SUM(mcc.single_pages_kb) AS cache_single_pages_kb,
  2173. SUM(mcc.multi_pages_kb) AS cache_multi_pages_kb,
  2174. SUM(mcc.single_pages_in_use_kb) AS cache_single_pages_in_use_kb,
  2175. SUM(mcc.multi_pages_in_use_kb) AS cache_multi_pages_in_use_kb,
  2176. SUM(mcc.entries_count) AS cache_entries_count,
  2177. SUM(mcc.entries_in_use_count) AS cache_entries_in_use_count,
  2178. CASE WHEN mcch.last_tick_time BETWEEN -2147483648 AND 2147483647 AND si.ms_ticks BETWEEN -2147483648 AND 2147483647 THEN DATEADD(ms, mcch.last_tick_time - si.ms_ticks, GETDATE())
  2179. WHEN mcch.last_tick_time/1000 BETWEEN -2147483648 AND 2147483647 AND si.ms_ticks/1000 BETWEEN -2147483648 AND 2147483647 THEN DATEADD(s, (mcch.last_tick_time/1000) - (si.ms_ticks/1000), GETDATE())
  2180. ELSE NULL END AS last_clock_hand_move
  2181. FROM sys.dm_os_memory_cache_counters mcc (NOLOCK)
  2182. INNER JOIN sys.dm_os_memory_cache_clock_hands mcch (NOLOCK) ON mcc.cache_address = mcch.cache_address
  2183. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2184. WHERE mcch.rounds_count > 0
  2185. GROUP BY mcch.name, mcch.[type], mcch.clock_hand, mcch.clock_status, mcc.single_pages_kb, mcc.multi_pages_kb, mcc.single_pages_in_use_kb, mcc.multi_pages_in_use_kb, mcch.last_tick_time, si.ms_ticks, mcc.entries_count, mcc.entries_in_use_count
  2186. ORDER BY SUM(mcch.removed_all_rounds_count) DESC, mcch.[type];'
  2187. END
  2188. EXECUTE sp_executesql @sqlcmd;
  2189. END
  2190. ELSE
  2191. BEGIN
  2192. SELECT 'Memory_checks' AS [Category], 'Clock_Hand_Notifications' AS [Information], '[OK]' AS Comment
  2193. END;
  2194. IF @bpool_consumer = 1
  2195. BEGIN
  2196. RAISERROR (N' |-Starting Buffer Pool Consumers from Buffer Descriptors', 10, 1) WITH NOWAIT
  2197. -- Note: in case of NUMA architecture, more than one entry per database is expected
  2198. SET @sqlcmd = 'SELECT ''Memory_checks'' AS [Category], ''Buffer_Pool_Consumers'' AS [Information],
  2199. COUNT_BIG(DISTINCT page_id)*8/1024 AS total_pages_MB,
  2200. CASE database_id WHEN 32767 THEN ''ResourceDB'' ELSE DB_NAME(database_id) END AS database_name,
  2201. SUM(row_count)/COUNT_BIG(DISTINCT page_id) AS avg_row_count_per_page,
  2202. SUM(CONVERT(BIGINT, free_space_in_bytes))/COUNT_BIG(DISTINCT page_id) AS avg_free_space_bytes_per_page
  2203. ' + CASE WHEN @sqlmajorver >= 12 THEN ',is_in_bpool_extension' ELSE '' END + '
  2204. ' + CASE WHEN @sqlmajorver = 10 THEN ',numa_node' ELSE '' END + '
  2205. ' + CASE WHEN @sqlmajorver >= 11 THEN ',AVG(read_microsec) AS avg_read_microsec' ELSE '' END + '
  2206. FROM sys.dm_os_buffer_descriptors
  2207. --WHERE bd.page_type IN (''DATA_PAGE'', ''INDEX_PAGE'')
  2208. GROUP BY database_id' + CASE WHEN @sqlmajorver >= 10 THEN ', numa_node' ELSE '' END + CASE WHEN @sqlmajorver >= 12 THEN ', is_in_bpool_extension' ELSE '' END + '
  2209. ORDER BY total_pages_MB DESC;'
  2210. EXECUTE sp_executesql @sqlcmd;
  2211. END
  2212. RAISERROR (N' |-Starting Memory Allocations from Memory Clerks', 10, 1) WITH NOWAIT
  2213. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], [type] AS Alloc_Type,
  2214. ' + CASE WHEN @sqlmajorver < 11 THEN 'SUM(single_pages_kb + multi_pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb + awe_allocated_kb) AS Alloc_Mem_KB'
  2215. ELSE 'SUM(pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb + awe_allocated_kb) AS Alloc_Mem_KB' END + '
  2216. FROM sys.dm_os_memory_clerks
  2217. WHERE type IN (''CACHESTORE_COLUMNSTOREOBJECTPOOL'',''CACHESTORE_CLRPROC'',''CACHESTORE_OBJCP'',''CACHESTORE_PHDR'',''CACHESTORE_SQLCP'',''CACHESTORE_TEMPTABLES'',
  2218. ''MEMORYCLERK_SQLBUFFERPOOL'',''MEMORYCLERK_SQLCLR'',''MEMORYCLERK_SQLGENERAL'',''MEMORYCLERK_SQLLOGPOOL'',''MEMORYCLERK_SQLOPTIMIZER'',
  2219. ''MEMORYCLERK_SQLQUERYCOMPILE'',''MEMORYCLERK_SQLQUERYEXEC'',''MEMORYCLERK_SQLQUERYPLAN'',''MEMORYCLERK_SQLSTORENG'',''MEMORYCLERK_XTP'',
  2220. ''OBJECTSTORE_LOCK_MANAGER'',''OBJECTSTORE_SNI_PACKET'',''USERSTORE_DBMETADATA'',''USERSTORE_OBJPERM'')
  2221. GROUP BY [type]
  2222. UNION ALL
  2223. SELECT ''Memory_checks'' AS [Category], ''Others'' AS Alloc_Type,
  2224. ' + CASE WHEN @sqlmajorver < 11 THEN 'SUM(single_pages_kb + multi_pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb) AS Alloc_Mem_KB'
  2225. ELSE 'SUM(pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb) AS Alloc_Mem_KB' END + '
  2226. FROM sys.dm_os_memory_clerks
  2227. WHERE type NOT IN (''CACHESTORE_COLUMNSTOREOBJECTPOOL'',''CACHESTORE_CLRPROC'',''CACHESTORE_OBJCP'',''CACHESTORE_PHDR'',''CACHESTORE_SQLCP'',''CACHESTORE_TEMPTABLES'',
  2228. ''MEMORYCLERK_SQLBUFFERPOOL'',''MEMORYCLERK_SQLCLR'',''MEMORYCLERK_SQLGENERAL'',''MEMORYCLERK_SQLLOGPOOL'',''MEMORYCLERK_SQLOPTIMIZER'',
  2229. ''MEMORYCLERK_SQLQUERYCOMPILE'',''MEMORYCLERK_SQLQUERYEXEC'',''MEMORYCLERK_SQLQUERYPLAN'',''MEMORYCLERK_SQLSTORENG'',''MEMORYCLERK_XTP'',
  2230. ''OBJECTSTORE_LOCK_MANAGER'',''OBJECTSTORE_SNI_PACKET'',''USERSTORE_DBMETADATA'',''USERSTORE_OBJPERM'')
  2231. ORDER BY Alloc_Mem_KB'
  2232. EXECUTE sp_executesql @sqlcmd;
  2233. IF @sqlmajorver >= 12
  2234. BEGIN
  2235. SET @sqlcmd = N'SELECT @xtpOUT = COUNT(*) FROM sys.dm_db_xtp_memory_consumers';
  2236. SET @params = N'@xtpOUT int OUTPUT';
  2237. EXECUTE sp_executesql @sqlcmd, @params, @xtpOUT = @xtp OUTPUT;
  2238. IF @xtp > 0
  2239. BEGIN
  2240. RAISERROR (N' |-Starting Memory Consumers from In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  2241. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''InMemory_Consumers'' AS Alloc_Type,
  2242. OBJECT_NAME([object_id]) AS [Object_Name], memory_consumer_type_desc, [object_id], index_id,
  2243. allocated_bytes/(1024*1024) AS Allocated_MB, used_bytes/(1024*1024) AS Used_MB,
  2244. CASE WHEN used_bytes IS NULL THEN ''used_bytes_is_varheap_only'' ELSE '''' END AS [Comment]
  2245. FROM sys.dm_db_xtp_memory_consumers
  2246. WHERE [object_id] > 0
  2247. ORDER BY Allocated_MB DESC' -- Only user objects; system objects are negative numbers
  2248. EXECUTE sp_executesql @sqlcmd;
  2249. RAISERROR (N' |-Starting Memory Allocations from In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  2250. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''InMemory_Alloc'' AS Alloc_Type,
  2251. SUM(allocated_bytes)/(1024*1024) AS total_allocated_MB, SUM(used_bytes)/(1024*1024) AS total_used_MB
  2252. FROM sys.dm_db_xtp_memory_consumers
  2253. ORDER BY total_allocated_MB DESC'
  2254. EXECUTE sp_executesql @sqlcmd;
  2255. END;
  2256. END;
  2257. END;
  2258. RAISERROR (N' |-Starting OOM', 10, 1) WITH NOWAIT
  2259. IF (SELECT COUNT([TIMESTAMP]) FROM sys.dm_os_ring_buffers (NOLOCK) WHERE ring_buffer_type = N'RING_BUFFER_OOM') > 0
  2260. BEGIN
  2261. SELECT 'Memory_checks' AS [Category], 'OOM_Notifications' AS [Information],
  2262. CASE WHEN x.[TIMESTAMP] BETWEEN -2147483648 AND 2147483647 AND si.ms_ticks BETWEEN -2147483648 AND 2147483647 THEN DATEADD(ms, x.[TIMESTAMP] - si.ms_ticks, GETDATE())
  2263. ELSE DATEADD(s, ([TIMESTAMP]/1000) - (si.ms_ticks/1000), GETDATE()) END AS Event_Time,
  2264. record.value('(./Record/OOM/Action)[1]', 'varchar(50)') AS [Action],
  2265. record.value('(./Record/OOM/Resources)[1]', 'int') AS [Resources],
  2266. record.value('(./Record/OOM/Task)[1]', 'varchar(20)') AS [Task],
  2267. record.value('(./Record/OOM/Pool)[1]', 'int') AS [PoolID],
  2268. rgrp.name AS [PoolName],
  2269. record.value('(./Record/MemoryRecord/MemoryUtilization)[1]', 'bigint') AS [MemoryUtilPct],
  2270. record.value('(./Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint')/1024 AS [Total_Physical_Mem_MB],
  2271. record.value('(./Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint')/1024 AS [Avail_Physical_Mem_MB],
  2272. record.value('(./Record/MemoryRecord/AvailableVirtualAddressSpace)[1]', 'bigint')/1024 AS [Avail_VAS_MB],
  2273. record.value('(./Record/MemoryRecord/TotalPageFile)[1]', 'bigint')/1024 AS [Total_Pagefile_MB],
  2274. record.value('(./Record/MemoryRecord/AvailablePageFile)[1]', 'bigint')/1024 AS [Avail_Pagefile_MB]
  2275. FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  2276. FROM sys.dm_os_ring_buffers (NOLOCK)
  2277. WHERE ring_buffer_type = N'RING_BUFFER_OOM') AS x
  2278. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2279. LEFT JOIN sys.resource_governor_resource_pools rgrp (NOLOCK) ON rgrp.pool_id = record.value('(./Record/OOM/Pool)[1]', 'int')
  2280. --WHERE CASE WHEN x.[timestamp] BETWEEN -2147483648 AND 2147483648 THEN DATEADD(ms, x.[timestamp] - si.ms_ticks, GETDATE())
  2281. -- ELSE DATEADD(s, (x.[timestamp]/1000) - (si.ms_ticks/1000), GETDATE()) END >= DATEADD(hh, -12, GETDATE())
  2282. ORDER BY 2 DESC;
  2283. END
  2284. ELSE
  2285. BEGIN
  2286. SELECT 'Memory_checks' AS [Category], 'OOM_Notifications' AS [Information], '[OK]' AS Comment
  2287. END;
  2288. --------------------------------------------------------------------------------------------------------------------------------
  2289. -- LPIM subsection
  2290. --------------------------------------------------------------------------------------------------------------------------------
  2291. RAISERROR (N' |-Starting LPIM', 10, 1) WITH NOWAIT
  2292. DECLARE @lpim bit, @lognumber int, @logcount int
  2293. IF ((@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13)
  2294. BEGIN
  2295. SET @sqlcmd = N'SELECT @lpimOUT = CASE WHEN sql_memory_model = 2 THEN 1 ELSE 0 END FROM sys.dm_os_sys_info';
  2296. SET @params = N'@lpimOUT bit OUTPUT';
  2297. EXECUTE sp_executesql @sqlcmd, @params, @lpimOUT=@lpim OUTPUT;
  2298. END
  2299. ELSE IF ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13)
  2300. BEGIN
  2301. SET @sqlcmd = N'SELECT @lpimOUT = CASE WHEN locked_page_allocations_kb > 0 THEN 1 ELSE 0 END FROM sys.dm_os_process_memory (NOLOCK)'
  2302. SET @params = N'@lpimOUT bit OUTPUT';
  2303. EXECUTE sp_executesql @sqlcmd, @params, @lpimOUT=@lpim OUTPUT
  2304. END
  2305. ELSE IF @sqlmajorver = 9
  2306. BEGIN
  2307. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2308. OR ISNULL(IS_SRVROLEMEMBER(N'securityadmin'), 0) = 1 -- Is securityadmin
  2309. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_readerrorlog') > 0
  2310. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_readerrorlog') > 0
  2311. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_enumerrorlogs') > 0)
  2312. BEGIN
  2313. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimdbcc'))
  2314. DROP TABLE #lpimdbcc;
  2315. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimdbcc'))
  2316. CREATE TABLE #lpimdbcc (logdate DATETIME, spid VARCHAR(50), logmsg VARCHAR(4000))
  2317. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimavail_logs'))
  2318. DROP TABLE #lpimavail_logs;
  2319. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimavail_logs'))
  2320. CREATE TABLE #lpimavail_logs (lognum int, logdate DATETIME, logsize int)
  2321. -- Get the number of available logs
  2322. INSERT INTO #lpimavail_logs
  2323. EXEC xp_enumerrorlogs
  2324. SELECT @lognumber = MIN(lognum) FROM #lpimavail_logs WHERE DATEADD(dd, DATEDIFF(dd, 0, logdate), 0) >= DATEADD(dd, DATEDIFF(dd, 0, @StartDate), 0)
  2325. SELECT @logcount = ISNULL(MAX(lognum),@lognumber) FROM #lpimavail_logs WHERE DATEADD(dd, DATEDIFF(dd, 0, logdate), 0) >= DATEADD(dd, DATEDIFF(dd, 0, @StartDate), 0)
  2326. IF @lognumber IS NULL
  2327. BEGIN
  2328. SELECT @ErrorMessage = '[WARNING: Could not retrieve information about Locked pages usage in SQL Server 2005]'
  2329. RAISERROR (@ErrorMessage, 16, 1);
  2330. END
  2331. ELSE
  2332. WHILE @lognumber < @logcount
  2333. BEGIN
  2334. -- Cycle through sql error logs (Cannot use Large Page Extensions: lock memory privilege was not granted)
  2335. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''Using locked pages for buffer pool'''
  2336. BEGIN TRY
  2337. INSERT INTO #lpimdbcc (logdate, spid, logmsg)
  2338. EXECUTE (@sqlcmd);
  2339. END TRY
  2340. BEGIN CATCH
  2341. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2342. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  2343. RAISERROR (@ErrorMessage, 16, 1);
  2344. END CATCH
  2345. -- Next log
  2346. --SET @lognumber = @lognumber + 1
  2347. SELECT @lognumber = MIN(lognum) FROM #lpimavail_logs WHERE lognum > @lognumber
  2348. END
  2349. IF (SELECT COUNT(*) FROM #lpimdbcc) > 0
  2350. BEGIN
  2351. SET @lpim = 1
  2352. END
  2353. ELSE IF (SELECT COUNT(*) FROM #lpimdbcc) = 0 AND @lognumber IS NOT NULL
  2354. BEGIN
  2355. SET @lpim = 0
  2356. END;
  2357. DROP TABLE #lpimavail_logs;
  2358. DROP TABLE #lpimdbcc;
  2359. END
  2360. ELSE
  2361. BEGIN
  2362. RAISERROR('[WARNING: Only a sysadmin or securityadmin can run the "Locked_pages" check. Bypassing check]', 16, 1, N'permissions')
  2363. RAISERROR('[WARNING: If not sysadmin or securityadmin, then user must be a granted EXECUTE permissions on the following sprocs to run checks: xp_enumerrorlogs and sp_readerrorlog. Bypassing check]', 16, 1, N'extended_sprocs')
  2364. --RETURN
  2365. END;
  2366. END
  2367. IF @lpim = 0 AND CONVERT(DECIMAL(3,1), @winver) < 6.0 AND @arch = 64
  2368. BEGIN
  2369. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[WARNING: Locked pages are not in use by SQL Server. In a WS2003 x64 architecture it is recommended to enable LPIM]' AS [Deviation]
  2370. END
  2371. ELSE IF @lpim = 1 AND CONVERT(DECIMAL(3,1), @winver) < 6.0 AND @arch = 64
  2372. BEGIN
  2373. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[INFORMATION: Locked pages are being used by SQL Server. This is recommended in a WS2003 x64 architecture]' AS [Deviation]
  2374. END
  2375. ELSE IF @lpim = 1 AND CONVERT(DECIMAL(3,1), @winver) >= 6.0 AND @arch = 64
  2376. BEGIN
  2377. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[INFORMATION: Locked pages are being used by SQL Server. This is recommended in WS2008 or above only when there are signs of paging]' AS [Deviation]
  2378. END
  2379. ELSE IF @lpim IS NULL
  2380. BEGIN
  2381. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[Could_not_retrieve_information]' AS [Deviation]
  2382. END
  2383. ELSE
  2384. BEGIN
  2385. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[Not_used]' AS [Deviation]
  2386. END;
  2387. --------------------------------------------------------------------------------------------------------------------------------
  2388. -- Pagefile subsection
  2389. --------------------------------------------------------------------------------------------------------------------------------
  2390. RAISERROR (N'|-Starting Pagefile Checks', 10, 1) WITH NOWAIT
  2391. DECLARE @pf_value tinyint--, @RegKey NVARCHAR(255)
  2392. DECLARE @pagefile bigint, @freepagefile bigint, @paged bigint
  2393. DECLARE @tbl_pf_value TABLE (Value VARCHAR(25), Data VARCHAR(50))
  2394. IF @sqlmajorver = 9
  2395. BEGIN
  2396. SET @sqlcmd = N'SELECT @pagefileOUT = (t1.record.value(''(./Record/MemoryRecord/TotalPageFile)[1]'', ''bigint'')-t1.record.value(''(./Record/MemoryRecord/TotalPhysicalMemory)[1]'', ''bigint''))/1024,
  2397. @freepagefileOUT = (t1.record.value(''(./Record/MemoryRecord/AvailablePageFile)[1]'', ''bigint'')-t1.record.value(''(./Record/MemoryRecord/AvailablePhysicalMemory)[1]'', ''bigint''))/1024,
  2398. @pagedOUT = ((t1.record.value(''(./Record/MemoryRecord/TotalPageFile)[1]'', ''bigint'')-t1.record.value(''(./Record/MemoryRecord/AvailablePageFile)[1]'', ''bigint''))/t1.record.value(''(./Record/MemoryRecord/TotalPageFile)[1]'', ''bigint''))/1024
  2399. FROM (SELECT MAX([TIMESTAMP]) AS [TIMESTAMP], CONVERT(xml, record) AS record
  2400. FROM sys.dm_os_ring_buffers (NOLOCK)
  2401. WHERE ring_buffer_type = N''RING_BUFFER_RESOURCE_MONITOR''
  2402. AND record LIKE ''%RESOURCE_MEMPHYSICAL%''
  2403. GROUP BY record) AS t1';
  2404. END
  2405. ELSE
  2406. BEGIN
  2407. SET @sqlcmd = N'SELECT @pagefileOUT = (total_page_file_kb-total_physical_memory_kb)/1024,
  2408. @freepagefileOUT = (available_page_file_kb-available_physical_memory_kb)/1024,
  2409. @pagedOUT = ((total_page_file_kb-available_page_file_kb)/total_page_file_kb)
  2410. FROM sys.dm_os_sys_memory (NOLOCK)';
  2411. END
  2412. SET @params = N'@pagefileOUT bigint OUTPUT, @freepagefileOUT bigint OUTPUT, @pagedOUT bigint OUTPUT';
  2413. EXECUTE sp_executesql @sqlcmd, @params, @pagefileOUT=@pagefile OUTPUT, @freepagefileOUT=@freepagefile OUTPUT, @pagedOUT=@paged OUTPUT;
  2414. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  2415. BEGIN
  2416. BEGIN TRY
  2417. SELECT @RegKey = N'System\CurrentControlSet\Control\Session Manager\Memory Management'
  2418. INSERT INTO @tbl_pf_value
  2419. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'PagingFiles', NO_OUTPUT
  2420. END TRY
  2421. BEGIN CATCH
  2422. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2423. SELECT @ErrorMessage = 'Pagefile subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  2424. RAISERROR (@ErrorMessage, 16, 1);
  2425. END CATCH
  2426. END
  2427. ELSE
  2428. BEGIN
  2429. RAISERROR('[WARNING: Missing permissions for full "Pagefile" checks. Bypassing System managed pagefile check]', 16, 1, N'sysadmin')
  2430. --RETURN
  2431. END;
  2432. IF (SELECT COUNT(*) FROM @tbl_pf_value) > 0
  2433. BEGIN
  2434. SELECT @pf_value = CASE WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data = '') > 0 THEN 1
  2435. WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data = '?:\pagefile.sys') > 0 THEN 2
  2436. WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data LIKE '%:\pagefile.sys 0 0%') > 0 THEN 3
  2437. ELSE 0 END
  2438. FROM @tbl_pf_value
  2439. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_management' AS [Check],
  2440. CASE WHEN @pf_value = 1 THEN '[WARNING: No pagefile is configured]'
  2441. WHEN @pf_value = 2 THEN '[WARNING: Pagefile is managed automatically on ALL drives]'
  2442. WHEN @pf_value = 3 THEN '[WARNING: Pagefile is managed automatically]'
  2443. ELSE '[OK]' END AS [Deviation]
  2444. END
  2445. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_free_space' AS [Check],
  2446. CASE WHEN @freepagefile <= 150 THEN '[WARNING: Pagefile free space is dangerously low. Please revise Pagefile settings]'
  2447. WHEN (@freepagefile*100)/@pagefile <= 10 THEN '[WARNING: Less than 10 percent of Pagefile is available. Please revise Pagefile settings]'
  2448. WHEN (@freepagefile*100)/@pagefile <= 30 THEN '[INFORMATION: Less than 30 percent of Pagefile is available]'
  2449. ELSE '[OK]' END AS [Deviation],
  2450. @pagefile AS total_pagefile_MB, @freepagefile AS available_pagefile_MB;
  2451. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_minimum_size' AS [Check],
  2452. CASE WHEN @winver = '5.2' AND @arch = 64 AND @pagefile < 8192 THEN '[WARNING: Pagefile is smaller than 8GB on a WS2003 x64 system. Please revise Pagefile settings]'
  2453. WHEN @winver = '5.2' AND @arch = 32 AND @pagefile < 2048 THEN '[WARNING: Pagefile is smaller than 2GB on a WS2003 x86 system. Please revise Pagefile settings]'
  2454. WHEN @winver <> '5.2' THEN '[NA]'
  2455. ELSE '[OK]' END AS [Deviation],
  2456. @pagefile AS total_pagefile_MB;
  2457. SELECT 'Pagefile_checks' AS [Category], 'Process_paged_out' AS [Check],
  2458. CASE WHEN @paged > 0 THEN '[WARNING: Part of SQL Server process memory has been paged out. Please revise LPIM settings]'
  2459. ELSE '[OK]' END AS [Deviation],
  2460. @paged AS paged_out_MB;
  2461. IF @ptochecks = 1
  2462. RAISERROR (N'|-Starting I/O Checks', 10, 1) WITH NOWAIT
  2463. --------------------------------------------------------------------------------------------------------------------------------
  2464. -- I/O stall in database files over 50% of cumulative sampled time or I/O latencies over 20ms in the last 5s subsection
  2465. -- io_stall refers to user processes waited for I/O. This number can be much greater than the sample_ms.
  2466. -- Might indicate that your I/O has insufficient service capabilities (HBA queue depths, reduced throughput, etc).
  2467. --------------------------------------------------------------------------------------------------------------------------------
  2468. IF @ptochecks = 1
  2469. BEGIN
  2470. RAISERROR (N' |-Starting I/O Stall subsection (wait for 5s)', 10, 1) WITH NOWAIT
  2471. DECLARE @mincol DATETIME, @maxcol DATETIME
  2472. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  2473. DROP TABLE #tmp_dm_io_virtual_file_stats;
  2474. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  2475. CREATE TABLE [dbo].[#tmp_dm_io_virtual_file_stats]([retrieval_time] [datetime],database_id int, [file_id] int, [DBName] sysname, [logical_file_name] NVARCHAR(255), [type_desc] NVARCHAR(60),
  2476. [physical_location] NVARCHAR(260),[sample_ms] int,[num_of_reads] bigint,[num_of_bytes_read] bigint,[io_stall_read_ms] bigint,[num_of_writes] bigint,
  2477. [num_of_bytes_written] bigint,[io_stall_write_ms] bigint,[io_stall] bigint,[size_on_disk_bytes] bigint,
  2478. CONSTRAINT PK_dm_io_virtual_file_stats PRIMARY KEY CLUSTERED(database_id, [file_id], [retrieval_time]));
  2479. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  2480. DROP TABLE #tblIOStall;
  2481. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  2482. CREATE TABLE #tblIOStall (database_id int, [file_id] int, [DBName] sysname, [logical_file_name] NVARCHAR(255), [type_desc] NVARCHAR(60),
  2483. [physical_location] NVARCHAR(260), size_on_disk_Mbytes int, num_of_reads bigint, num_of_writes bigint, num_of_KBytes_read bigint, num_of_KBytes_written bigint,
  2484. io_stall_ms int, io_stall_read_ms int, io_stall_write_ms int, avg_read_latency_ms int, avg_write_latency_ms int, avg_io_stall_read_pct int, cumulative_io_stall_read_pct int,
  2485. avg_io_stall_write_pct int, cumulative_io_stall_write_pct int, cumulative_sample_HH int, io_stall_pct_of_cumulative_sample int,
  2486. CONSTRAINT PK_IOStall PRIMARY KEY CLUSTERED(database_id, [file_id]));
  2487. SELECT @mincol = GETDATE()
  2488. INSERT INTO #tmp_dm_io_virtual_file_stats
  2489. SELECT @mincol, f.database_id, f.[file_id], DB_NAME(f.database_id), f.name AS logical_file_name, f.type_desc,
  2490. CAST (CASE
  2491. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2492. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2493. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2494. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2495. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2496. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2497. ELSE f.physical_name
  2498. END AS NVARCHAR(255)) AS physical_location,
  2499. fs.[sample_ms],fs.[num_of_reads],fs.[num_of_bytes_read],fs.[io_stall_read_ms],fs.[num_of_writes],
  2500. fs.[num_of_bytes_written],fs.[io_stall_write_ms],fs.[io_stall],fs.[size_on_disk_bytes]
  2501. FROM sys.dm_io_virtual_file_stats (default, default) AS fs
  2502. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id]
  2503. WAITFOR DELAY '00:00:05' -- wait 5s between pooling
  2504. SELECT @maxcol = GETDATE()
  2505. INSERT INTO #tmp_dm_io_virtual_file_stats
  2506. SELECT @maxcol, f.database_id, f.[file_id], DB_NAME(f.database_id), f.name AS logical_file_name, f.type_desc,
  2507. CAST (CASE
  2508. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2509. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2510. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2511. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2512. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2513. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2514. ELSE f.physical_name
  2515. END AS NVARCHAR(255)) AS physical_location,
  2516. fs.[sample_ms],fs.[num_of_reads],fs.[num_of_bytes_read],fs.[io_stall_read_ms],fs.[num_of_writes],
  2517. fs.[num_of_bytes_written],fs.[io_stall_write_ms],fs.[io_stall],fs.[size_on_disk_bytes]
  2518. FROM sys.dm_io_virtual_file_stats (default, default) AS fs
  2519. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id]
  2520. ;WITH cteFileStats1 AS (SELECT database_id,[file_id],[DBName],[logical_file_name],[type_desc],
  2521. [physical_location],[sample_ms],[num_of_reads],[num_of_bytes_read],[io_stall_read_ms],[num_of_writes],
  2522. [num_of_bytes_written],[io_stall_write_ms],[io_stall],[size_on_disk_bytes]
  2523. FROM #tmp_dm_io_virtual_file_stats WHERE [retrieval_time] = @mincol),
  2524. cteFileStats2 AS (SELECT database_id,[file_id],[DBName],[logical_file_name],[type_desc],
  2525. [physical_location],[sample_ms],[num_of_reads],[num_of_bytes_read],[io_stall_read_ms],[num_of_writes],
  2526. [num_of_bytes_written],[io_stall_write_ms],[io_stall],[size_on_disk_bytes]
  2527. FROM #tmp_dm_io_virtual_file_stats WHERE [retrieval_time] = @maxcol)
  2528. INSERT INTO #tblIOStall
  2529. SELECT t1.database_id, t1.[file_id], t1.[DBName], t1.logical_file_name, t1.type_desc, t1.physical_location,
  2530. t1.size_on_disk_bytes/1024/1024 AS size_on_disk_Mbytes,
  2531. (t2.num_of_reads-t1.num_of_reads) AS num_of_reads,
  2532. (t2.num_of_writes-t1.num_of_writes) AS num_of_writes,
  2533. (t2.num_of_bytes_read-t1.num_of_bytes_read)/1024 AS num_of_KBytes_read,
  2534. (t2.num_of_bytes_written-t1.num_of_bytes_written)/1024 AS num_of_KBytes_written,
  2535. (t2.io_stall-t1.io_stall) AS io_stall_ms,
  2536. (t2.io_stall_read_ms-t1.io_stall_read_ms) AS io_stall_read_ms,
  2537. (t2.io_stall_write_ms-t1.io_stall_write_ms) AS io_stall_write_ms,
  2538. ((t2.io_stall_read_ms-t1.io_stall_read_ms) / (1.0 + (t2.num_of_reads-t1.num_of_reads))) AS avg_read_latency_ms,
  2539. ((t2.io_stall_write_ms-t1.io_stall_write_ms) / (1.0 + (t2.num_of_writes-t1.num_of_writes))) AS avg_write_latency_ms,
  2540. ((t2.io_stall_read_ms - t1.io_stall_read_ms) * 100.) / (CASE WHEN (t2.io_stall - t1.io_stall) <= 0 THEN 1 ELSE (t2.io_stall - t1.io_stall) END) AS avg_io_stall_read_pct,
  2541. ((t2.io_stall_read_ms)*100)/(CASE WHEN t2.io_stall = 0 THEN 1 ELSE t2.io_stall END) AS cumulative_io_stall_read_pct,
  2542. ((t2.io_stall_write_ms - t1.io_stall_write_ms) * 100.) / (CASE WHEN (t2.io_stall - t1.io_stall) <= 0 THEN 1 ELSE (t2.io_stall - t1.io_stall) END) AS avg_io_stall_write_pct,
  2543. ((t2.io_stall_write_ms)*100)/(CASE WHEN t2.io_stall = 0 THEN 1 ELSE t2.io_stall END) AS cumulative_io_stall_write_pct,
  2544. ABS((t2.sample_ms/1000)/60/60) AS cumulative_sample_HH,
  2545. ((t2.io_stall/1000/60)*100)/(ABS((t2.sample_ms/1000)/60)) AS io_stall_pct_of_cumulative_sample
  2546. FROM cteFileStats1 t1 INNER JOIN cteFileStats2 t2 ON t1.database_id = t2.database_id AND t1.[file_id] = t2.[file_id]
  2547. IF (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE avg_read_latency_ms >= 20) > 0
  2548. OR (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE avg_write_latency_ms >= 20) > 0
  2549. BEGIN
  2550. SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Check], '[WARNING: Some database files have latencies >= 20ms in the last 5s. Review I/O related performance counters and storage-related configurations.]' AS [Deviation]
  2551. SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Information], [DBName] AS [Database_Name], [logical_file_name], [type_desc], avg_read_latency_ms, avg_write_latency_ms,
  2552. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2553. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2554. avg_io_stall_read_pct, cumulative_io_stall_read_pct, avg_io_stall_write_pct, cumulative_io_stall_write_pct, cumulative_sample_HH, io_stall_pct_of_cumulative_sample
  2555. FROM #tblIOStall
  2556. WHERE avg_read_latency_ms >= 20 OR avg_write_latency_ms >= 20
  2557. ORDER BY avg_read_latency_ms DESC, avg_write_latency_ms DESC, [DBName], [type_desc], [logical_file_name]
  2558. END
  2559. ELSE IF (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE io_stall_pct_of_cumulative_sample > 50) > 0
  2560. BEGIN
  2561. SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Check], '[WARNING: Some database files have stall I/O exceeding 50 pct of cumulative sampled time. Review I/O related performance counters and storage-related configurations.]' AS [Deviation]
  2562. SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Information], [DBName] AS [Database_Name], [logical_file_name], [type_desc], avg_read_latency_ms, avg_write_latency_ms,
  2563. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2564. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2565. avg_io_stall_read_pct, cumulative_io_stall_read_pct, avg_io_stall_write_pct, cumulative_io_stall_write_pct, cumulative_sample_HH, io_stall_pct_of_cumulative_sample
  2566. FROM #tblIOStall
  2567. WHERE io_stall_pct_of_cumulative_sample > 50
  2568. ORDER BY io_stall_pct_of_cumulative_sample DESC, [DBName], [type_desc], [logical_file_name]
  2569. END
  2570. ELSE
  2571. BEGIN
  2572. SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Check], '[OK]' AS [Deviation]
  2573. /*SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Information], [DBName] AS [Database_Name], [logical_file_name], [type_desc], avg_read_latency_ms, avg_write_latency_ms,
  2574. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2575. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2576. avg_io_stall_read_pct, cumulative_io_stall_read_pct, avg_io_stall_write_pct, cumulative_io_stall_write_pct, cumulative_sample_HH, io_stall_pct_of_cumulative_sample
  2577. FROM #tblIOStall
  2578. ORDER BY [DBName], [type_desc], [logical_file_name]*/
  2579. END;
  2580. END;
  2581. --------------------------------------------------------------------------------------------------------------------------------
  2582. -- Pending disk I/O Requests subsection
  2583. -- Indicate that your I/O has insufficient service capabilities (HBA queue depths, reduced throughput, etc).
  2584. --------------------------------------------------------------------------------------------------------------------------------
  2585. IF @ptochecks = 1
  2586. BEGIN
  2587. RAISERROR (N' |-Starting Pending disk I/O Requests subsection (wait for a max of 5s)', 10, 1) WITH NOWAIT
  2588. DECLARE @IOCnt tinyint
  2589. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  2590. DROP TABLE #tblPendingIOReq;
  2591. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  2592. CREATE TABLE #tblPendingIOReq (io_completion_request_address varbinary(8), io_handle varbinary(8), io_type VARCHAR(7), io_pending bigint, io_pending_ms_ticks bigint, scheduler_address varbinary(8));
  2593. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  2594. DROP TABLE #tblPendingIO;
  2595. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  2596. CREATE TABLE #tblPendingIO (database_id int, [file_id] int, [DBName] sysname, [logical_file_name] NVARCHAR(255), [type_desc] NVARCHAR(60),
  2597. [physical_location] NVARCHAR(260), io_stall_min int, io_stall_read_min int, io_stall_write_min int, avg_read_latency_ms int,
  2598. avg_write_latency_ms int, io_stall_read_pct int, io_stall_write_pct int, sampled_HH int,
  2599. io_stall_pct_of_overall_sample int, io_completion_request_address varbinary(8), io_handle varbinary(8), io_type VARCHAR(7), io_pending bigint, io_pending_ms_ticks bigint, scheduler_address varbinary(8),
  2600. scheduler_id int, pending_disk_io_count int, work_queue_count bigint);
  2601. SET @IOCnt = 1
  2602. WHILE @IOCnt < 5
  2603. BEGIN
  2604. INSERT INTO #tblPendingIOReq
  2605. SELECT io_completion_request_address, io_handle, io_type, io_pending, io_pending_ms_ticks, scheduler_address
  2606. FROM sys.dm_io_pending_io_requests;
  2607. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 1
  2608. BREAK
  2609. WAITFOR DELAY '00:00:01' -- wait 1s between pooling
  2610. SET @IOCnt = @IOCnt + 1
  2611. END;
  2612. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 0
  2613. BEGIN
  2614. INSERT INTO #tblPendingIO
  2615. SELECT DISTINCT f.database_id, f.[file_id], DB_NAME(f.database_id) AS database_name, f.name AS logical_file_name, f.type_desc,
  2616. CAST (CASE
  2617. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2618. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2619. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2620. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2621. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2622. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2623. ELSE f.physical_name
  2624. END AS NVARCHAR(255)) AS physical_location,
  2625. fs.io_stall/1000/60 AS io_stall_min,
  2626. fs.io_stall_read_ms/1000/60 AS io_stall_read_min,
  2627. fs.io_stall_write_ms/1000/60 AS io_stall_write_min,
  2628. (fs.io_stall_read_ms / (1.0 + fs.num_of_reads)) AS avg_read_latency_ms,
  2629. (fs.io_stall_write_ms / (1.0 + fs.num_of_writes)) AS avg_write_latency_ms,
  2630. ((fs.io_stall_read_ms/1000/60)*100)/(CASE WHEN fs.io_stall/1000/60 = 0 THEN 1 ELSE fs.io_stall/1000/60 END) AS io_stall_read_pct,
  2631. ((fs.io_stall_write_ms/1000/60)*100)/(CASE WHEN fs.io_stall/1000/60 = 0 THEN 1 ELSE fs.io_stall/1000/60 END) AS io_stall_write_pct,
  2632. ABS((fs.sample_ms/1000)/60/60) AS 'sample_HH',
  2633. ((fs.io_stall/1000/60)*100)/(ABS((fs.sample_ms/1000)/60))AS 'io_stall_pct_of_overall_sample',
  2634. pio.io_completion_request_address, pio.io_handle, pio.io_type, pio.io_pending,
  2635. pio.io_pending_ms_ticks, pio.scheduler_address, os.scheduler_id, os.pending_disk_io_count, os.work_queue_count
  2636. FROM #tblPendingIOReq AS pio
  2637. INNER JOIN sys.dm_io_virtual_file_stats (NULL,NULL) AS fs ON fs.file_handle = pio.io_handle
  2638. INNER JOIN sys.dm_os_schedulers AS os ON pio.scheduler_address = os.scheduler_address
  2639. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id];
  2640. END;
  2641. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 0
  2642. BEGIN
  2643. SELECT 'IO_checks' AS [Category], 'Pending_IO' AS [Check], '[WARNING: Pending disk I/O requests were found. Review I/O related performance counters and storage-related configurations]' AS [Deviation]
  2644. SELECT 'IO_checks' AS [Category], 'Pending_IO' AS [Information], [DBName] AS [Database_Name], [logical_file_name], [type_desc], avg_read_latency_ms, avg_write_latency_ms,
  2645. io_stall_read_pct, io_stall_write_pct, sampled_HH, io_stall_pct_of_overall_sample, [physical_location], io_stall_min, io_stall_read_min, io_stall_write_min,
  2646. io_completion_request_address, io_type, CASE WHEN io_pending = 1 THEN 'Pending_Context_Switching' ELSE 'Pending_WindowsOS' END AS io_pending_type,
  2647. io_pending_ms_ticks, scheduler_address, scheduler_id, pending_disk_io_count, work_queue_count
  2648. FROM #tblPendingIO
  2649. ORDER BY scheduler_address, [DBName], [type_desc], [logical_file_name]
  2650. END
  2651. ELSE
  2652. BEGIN
  2653. SELECT 'IO_checks' AS [Category], 'Pending_IO' AS [Check], '[OK]' AS [Deviation]
  2654. END;
  2655. END;
  2656. RAISERROR (N'|-Starting Server Checks', 10, 1) WITH NOWAIT
  2657. --------------------------------------------------------------------------------------------------------------------------------
  2658. -- Power plan subsection
  2659. --------------------------------------------------------------------------------------------------------------------------------
  2660. RAISERROR (N' |-Starting Power plan', 10, 1) WITH NOWAIT
  2661. DECLARE @planguid NVARCHAR(64), @powerkey NVARCHAR(255)
  2662. --SELECT @powerkey = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel\NameSpace\{025A5937-A6BE-4686-A844-36FE4BEC8B6D}'
  2663. --SELECT @powerkey = 'SYSTEM\CurrentControlSet\Control\Power\User\Default\PowerSchemes'
  2664. SELECT @powerkey = 'SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes'
  2665. IF CONVERT(DECIMAL(3,1), @winver) >= 6.0
  2666. BEGIN
  2667. BEGIN TRY
  2668. --EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @powerkey, 'PreferredPlan', @planguid OUTPUT, NO_OUTPUT
  2669. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @powerkey, 'ActivePowerScheme', @planguid OUTPUT, NO_OUTPUT
  2670. END TRY
  2671. BEGIN CATCH
  2672. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2673. SELECT @ErrorMessage = 'Power plan subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  2674. RAISERROR (@ErrorMessage, 16, 1);
  2675. END CATCH
  2676. END
  2677. -- http://support.microsoft.com/kb/935799/en-us
  2678. IF @winver IS NULL
  2679. BEGIN
  2680. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Check], '[WARNING: Could not determine Windows version for check]' AS [Deviation]
  2681. END
  2682. ELSE IF @planguid IS NOT NULL AND @planguid <> '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
  2683. BEGIN
  2684. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Check], '[WARNING: The current power plan scheme is not recommended for database servers. Please reconfigure for High Performance mode]' AS [Deviation]
  2685. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Information], CASE WHEN @planguid = '381b4222-f694-41f0-9685-ff5bb260df2e' THEN 'Balanced'
  2686. WHEN @planguid = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c' THEN 'High Performance'
  2687. WHEN @planguid = 'a1841308-3541-4fab-bc81-f71556f20b4a' THEN 'Power Saver'
  2688. ELSE 'Other' END AS [Power_Plan]
  2689. END
  2690. ELSE IF @planguid IS NOT NULL AND @planguid = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
  2691. BEGIN
  2692. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Check], '[OK]' AS [Deviation]
  2693. END;
  2694. --------------------------------------------------------------------------------------------------------------------------------
  2695. -- Disk Partition alignment offset < 64KB subsection
  2696. --------------------------------------------------------------------------------------------------------------------------------
  2697. RAISERROR (N' |-Starting Disk Partition alignment offset < 64KB', 10, 1) WITH NOWAIT
  2698. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  2699. BEGIN
  2700. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2701. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2702. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  2703. AND (SELECT COUNT(l.name)
  2704. FROM sys.server_permissions p JOIN sys.server_principals l
  2705. ON p.grantee_principal_id = l.principal_id
  2706. AND p.class = 100 -- Server
  2707. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  2708. AND l.is_disabled = 0
  2709. AND p.permission_name = 'ALTER SETTINGS'
  2710. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  2711. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2712. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  2713. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  2714. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  2715. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  2716. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  2717. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  2718. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  2719. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  2720. BEGIN
  2721. DECLARE @diskpart int
  2722. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  2723. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  2724. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  2725. RAISERROR (' |-Configuration options set for Disk partition alignment offset check', 10, 1) WITH NOWAIT
  2726. IF @sao = 0
  2727. BEGIN
  2728. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  2729. END
  2730. IF @xcmd = 0
  2731. BEGIN
  2732. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  2733. END
  2734. IF @ole = 0
  2735. BEGIN
  2736. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  2737. END
  2738. DECLARE @output_hw_tot_diskpart TABLE ([PS_OUTPUT] VARCHAR(2048));
  2739. DECLARE @output_hw_format_diskpart TABLE ([volid] smallint IDENTITY(1,1), [HD_Partition] VARCHAR(50) NULL, StartingOffset bigint NULL)
  2740. IF @custompath IS NULL
  2741. BEGIN
  2742. IF @sqlmajorver < 11
  2743. BEGIN
  2744. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  2745. SET @path = @path + '\LOG'
  2746. END
  2747. ELSE
  2748. BEGIN
  2749. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  2750. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  2751. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  2752. END
  2753. -- Create COM object with FSO
  2754. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  2755. IF @OLEResult <> 0
  2756. BEGIN
  2757. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2758. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2759. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2760. END
  2761. ELSE
  2762. BEGIN
  2763. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  2764. IF @OLEResult <> 0
  2765. BEGIN
  2766. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2767. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  2768. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2769. END
  2770. ELSE
  2771. BEGIN
  2772. IF @existout <> 1
  2773. BEGIN
  2774. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  2775. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  2776. END
  2777. END
  2778. EXEC @OLEResult = sp_OADestroy @FSO
  2779. END
  2780. END
  2781. ELSE
  2782. BEGIN
  2783. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  2784. END
  2785. SET @FileName = @path + '\checkbp_diskpart_' + RTRIM(@server) + '.ps1'
  2786. EXEC master.dbo.xp_fileexist @FileName, @existout out
  2787. IF @existout = 0
  2788. BEGIN -- Scan for local disks
  2789. SET @Text1 = '[string] $serverName = ''localhost''
  2790. $partitions = Get-WmiObject -computername $serverName -query "SELECT * FROM Win32_DiskPartition"
  2791. foreach ($partition in $partitions)
  2792. {
  2793. [string] $diskpart = "{0}_{1};{2}" -f $partition.DiskIndex,$partition.Index,$partition.StartingOffset
  2794. Write-Output $diskpart
  2795. }
  2796. '
  2797. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  2798. IF @OLEResult <> 0
  2799. BEGIN
  2800. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2801. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2802. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2803. END
  2804. --Open file
  2805. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  2806. IF @OLEResult <> 0
  2807. BEGIN
  2808. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2809. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  2810. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2811. END
  2812. ELSE
  2813. BEGIN
  2814. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  2815. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  2816. END
  2817. --Write Text1
  2818. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  2819. IF @OLEResult <> 0
  2820. BEGIN
  2821. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2822. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  2823. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2824. END
  2825. EXEC @OLEResult = sp_OADestroy @FileID
  2826. EXEC @OLEResult = sp_OADestroy @FS
  2827. END
  2828. ELSE
  2829. BEGIN
  2830. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  2831. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  2832. END
  2833. IF @psver = 1
  2834. BEGIN
  2835. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  2836. END
  2837. ELSE
  2838. BEGIN
  2839. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  2840. END;
  2841. INSERT INTO @output_hw_tot_diskpart
  2842. EXEC master.dbo.xp_cmdshell @CMD
  2843. SET @CMD = 'del /Q "' + @FileName + '"'
  2844. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  2845. INSERT INTO @output_hw_format_diskpart ([HD_Partition],StartingOffset)
  2846. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  2847. RIGHT(RTRIM([PS_OUTPUT]), LEN(RTRIM([PS_OUTPUT]))-CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT])) END)
  2848. FROM @output_hw_tot_diskpart
  2849. WHERE [PS_OUTPUT] IS NOT NULL;
  2850. SET @CMD2 = 'del ' + @FileName
  2851. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  2852. IF @xcmd = 0
  2853. BEGIN
  2854. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  2855. END
  2856. IF @ole = 0
  2857. BEGIN
  2858. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  2859. END
  2860. IF @sao = 0
  2861. BEGIN
  2862. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  2863. END;
  2864. ;WITH diskpartcte (StartingOffset) AS (
  2865. SELECT StartingOffset
  2866. FROM @output_hw_format_diskpart
  2867. WHERE StartingOffset IS NOT NULL OR LEN(StartingOffset) > 0)
  2868. SELECT @diskpart = CASE WHEN (SELECT COUNT(*) FROM diskpartcte) = 0 THEN NULL ELSE COUNT(cte1.[StartingOffset]) END
  2869. FROM diskpartcte cte1
  2870. WHERE cte1.[StartingOffset] < 65536;
  2871. IF @diskpart > 0 AND @diskpart IS NOT NULL
  2872. BEGIN
  2873. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Check], '[WARNING: Some disk partitions are not using a minimum recommended alignment offset of 64KB]' AS [Deviation]
  2874. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Information], LEFT(t1.[HD_Partition],LEN(t1.[HD_Partition])-CHARINDEX('_',t1.[HD_Partition])) AS HD_Volume,
  2875. RIGHT(t1.[HD_Partition],LEN(t1.[HD_Partition])-CHARINDEX('_',t1.[HD_Partition])) AS [HD_Partition],
  2876. (t1.StartingOffset/1024) AS [StartingOffset_KB]
  2877. FROM @output_hw_format_diskpart t1
  2878. WHERE t1.StartingOffset IS NOT NULL OR LEN(t1.StartingOffset) > 0
  2879. ORDER BY t1.[HD_Partition]
  2880. OPTION (RECOMPILE);
  2881. END
  2882. ELSE IF @diskpart IS NULL
  2883. BEGIN
  2884. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Check], '[WARNING: Could not gather information on disk partition offset size]' AS [Deviation]
  2885. END
  2886. ELSE
  2887. BEGIN
  2888. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Check], '[OK]' AS [Deviation]
  2889. END;
  2890. END
  2891. ELSE
  2892. BEGIN
  2893. RAISERROR('[WARNING: Only a sysadmin can run the "partition alignment offset" checks. A regular user can also run this check if a xp_cmdshell proxy account exists. Bypassing check]', 16, 1, N'xp_cmdshellproxy')
  2894. RAISERROR('[WARNING: If not sysadmin, then must be a granted EXECUTE permissions on the following extended sprocs to run checks: sp_OACreate, sp_OADestroy, sp_OAGetErrorInfo, xp_cmdshell, xp_instance_regread, xp_regread, xp_fileexist and xp_regenumvalues. Bypassing check]', 16, 1, N'extended_sprocs')
  2895. --RETURN
  2896. END
  2897. END
  2898. ELSE
  2899. BEGIN
  2900. RAISERROR(' |- [INFORMATION: "partition alignment offset" check was skipped: either xp_cmdshell or execution of PS scripts was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  2901. --RETURN
  2902. END;
  2903. --------------------------------------------------------------------------------------------------------------------------------
  2904. -- NTFS block size in volumes that hold database files <> 64KB subsection
  2905. --------------------------------------------------------------------------------------------------------------------------------
  2906. RAISERROR (N' |-Starting NTFS block size in volumes that hold database files <> 64KB', 10, 1) WITH NOWAIT
  2907. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  2908. BEGIN
  2909. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2910. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2911. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  2912. AND (SELECT COUNT(l.name)
  2913. FROM sys.server_permissions p JOIN sys.server_principals l
  2914. ON p.grantee_principal_id = l.principal_id
  2915. AND p.class = 100 -- Server
  2916. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  2917. AND l.is_disabled = 0
  2918. AND p.permission_name = 'ALTER SETTINGS'
  2919. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  2920. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2921. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  2922. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  2923. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  2924. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  2925. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  2926. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  2927. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  2928. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  2929. BEGIN
  2930. DECLARE @ntfs int
  2931. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  2932. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  2933. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  2934. RAISERROR (' |-Configuration options set for NTFS Block size check', 10, 1) WITH NOWAIT
  2935. IF @sao = 0
  2936. BEGIN
  2937. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  2938. END
  2939. IF @xcmd = 0
  2940. BEGIN
  2941. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  2942. END
  2943. IF @ole = 0
  2944. BEGIN
  2945. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  2946. END
  2947. DECLARE @output_hw_tot_ntfs TABLE ([PS_OUTPUT] VARCHAR(2048));
  2948. DECLARE @output_hw_format_ntfs TABLE ([volid] smallint IDENTITY(1,1), [HD_Volume] NVARCHAR(2048) NULL, [NTFS_Block] NVARCHAR(8) NULL)
  2949. IF @custompath IS NULL
  2950. BEGIN
  2951. IF @sqlmajorver < 11
  2952. BEGIN
  2953. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  2954. SET @path = @path + '\LOG'
  2955. END
  2956. ELSE
  2957. BEGIN
  2958. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  2959. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  2960. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  2961. END
  2962. -- Create COM object with FSO
  2963. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  2964. IF @OLEResult <> 0
  2965. BEGIN
  2966. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2967. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2968. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2969. END
  2970. ELSE
  2971. BEGIN
  2972. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  2973. IF @OLEResult <> 0
  2974. BEGIN
  2975. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2976. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  2977. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2978. END
  2979. ELSE
  2980. BEGIN
  2981. IF @existout <> 1
  2982. BEGIN
  2983. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  2984. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  2985. END
  2986. END
  2987. EXEC @OLEResult = sp_OADestroy @FSO
  2988. END
  2989. END
  2990. ELSE
  2991. BEGIN
  2992. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  2993. END
  2994. SET @FileName = @path + '\checkbp_ntfs_' + RTRIM(@server) + '.ps1'
  2995. EXEC master.dbo.xp_fileexist @FileName, @existout out
  2996. IF @existout = 0
  2997. BEGIN -- Scan for local disks
  2998. SET @Text1 = '[string] $serverName = ''localhost''
  2999. $vols = Get-WmiObject -computername $serverName -query "select name, blocksize from Win32_Volume where Capacity <> NULL and DriveType = 3"
  3000. foreach($vol in $vols)
  3001. {
  3002. [string] $drive = "{0};{1}" -f $vol.name,$vol.blocksize
  3003. Write-Output $drive
  3004. } '
  3005. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3006. IF @OLEResult <> 0
  3007. BEGIN
  3008. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3009. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3010. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3011. END
  3012. --Open file
  3013. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3014. IF @OLEResult <> 0
  3015. BEGIN
  3016. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3017. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3018. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3019. END
  3020. ELSE
  3021. BEGIN
  3022. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3023. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3024. END
  3025. --Write Text1
  3026. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3027. IF @OLEResult <> 0
  3028. BEGIN
  3029. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3030. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3031. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3032. END
  3033. EXEC @OLEResult = sp_OADestroy @FileID
  3034. EXEC @OLEResult = sp_OADestroy @FS
  3035. END
  3036. ELSE
  3037. BEGIN
  3038. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3039. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3040. END
  3041. IF @psver = 1
  3042. BEGIN
  3043. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3044. END
  3045. ELSE
  3046. BEGIN
  3047. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3048. END;
  3049. INSERT INTO @output_hw_tot_ntfs
  3050. EXEC master.dbo.xp_cmdshell @CMD
  3051. SET @CMD = 'del /Q "' + @FileName + '"'
  3052. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3053. INSERT INTO @output_hw_format_ntfs ([HD_Volume],[NTFS_Block])
  3054. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3055. RIGHT(RTRIM([PS_OUTPUT]), LEN(RTRIM([PS_OUTPUT]))-CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT])) END)
  3056. FROM @output_hw_tot_ntfs
  3057. WHERE [PS_OUTPUT] IS NOT NULL;
  3058. SET @CMD2 = 'del ' + @FileName
  3059. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3060. IF @xcmd = 0
  3061. BEGIN
  3062. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3063. END
  3064. IF @ole = 0
  3065. BEGIN
  3066. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3067. END
  3068. IF @sao = 0
  3069. BEGIN
  3070. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3071. END;
  3072. WITH ntfscte (physical_name, ntfsblock) AS (
  3073. SELECT DISTINCT(LEFT(physical_name, LEN(t2.HD_Volume))), [NTFS_Block]
  3074. FROM sys.master_files t1 INNER JOIN @output_hw_format_ntfs t2
  3075. ON LEFT(physical_name, LEN(t2.HD_Volume)) = t2.HD_Volume
  3076. WHERE [database_id] <> 32767 AND (t2.[NTFS_Block] IS NOT NULL OR LEN(t2.[NTFS_Block]) > 0)
  3077. )
  3078. SELECT @ntfs = CASE WHEN (SELECT COUNT(*) FROM ntfscte) = 0 THEN NULL ELSE COUNT(cte1.[ntfsblock]) END
  3079. FROM ntfscte cte1
  3080. WHERE cte1.[ntfsblock] <> 65536;
  3081. IF @ntfs > 0 AND @ntfs IS NOT NULL
  3082. BEGIN
  3083. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Check], '[WARNING: Some volumes that hold database files are not formatted using the recommended NTFS block size of 64KB]' AS [Deviation]
  3084. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Information], t1.HD_Volume, (t1.[NTFS_Block]/1024) AS [NTFS_Block_Size_KB]
  3085. FROM (SELECT DISTINCT(LEFT(physical_name, LEN(t2.HD_Volume))) AS [HD_Volume], [NTFS_Block]
  3086. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format_ntfs t2
  3087. ON LEFT(physical_name, LEN(t2.HD_Volume)) = t2.HD_Volume
  3088. WHERE [database_id] <> 32767 AND (t2.[NTFS_Block] IS NOT NULL OR LEN(t2.[NTFS_Block]) > 0)) t1
  3089. ORDER BY t1.HD_Volume OPTION (RECOMPILE);
  3090. END
  3091. ELSE IF @ntfs IS NULL
  3092. BEGIN
  3093. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Check], '[WARNING: Could not gather information on NTFS block size]' AS [Deviation]
  3094. END
  3095. ELSE
  3096. BEGIN
  3097. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Check], '[OK]' AS [Deviation]
  3098. END;
  3099. END
  3100. ELSE
  3101. BEGIN
  3102. RAISERROR('[WARNING: Only a sysadmin can run the "NTFS block size" checks. A regular user can also run this check if a xp_cmdshell proxy account exists. Bypassing check]', 16, 1, N'xp_cmdshellproxy')
  3103. RAISERROR('[WARNING: If not sysadmin, then must be a granted EXECUTE permissions on the following extended sprocs to run checks: sp_OACreate, sp_OADestroy, sp_OAGetErrorInfo, xp_cmdshell, xp_instance_regread, xp_regread, xp_fileexist and xp_regenumvalues. Bypassing check]', 16, 1, N'extended_sprocs')
  3104. --RETURN
  3105. END
  3106. END
  3107. ELSE
  3108. BEGIN
  3109. RAISERROR(' |- [INFORMATION: "NTFS block size" check was skipped: either xp_cmdshell or execution of PS scripts was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  3110. --RETURN
  3111. END;
  3112. --------------------------------------------------------------------------------------------------------------------------------
  3113. -- Disk Fragmentation Analysis subsection
  3114. --------------------------------------------------------------------------------------------------------------------------------
  3115. IF @diskfrag = 1
  3116. BEGIN
  3117. RAISERROR (N' |-Starting Disk Fragmentation Analysis', 10, 1) WITH NOWAIT
  3118. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  3119. BEGIN
  3120. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3121. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3122. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  3123. AND (SELECT COUNT(l.name)
  3124. FROM sys.server_permissions p JOIN sys.server_principals l
  3125. ON p.grantee_principal_id = l.principal_id
  3126. AND p.class = 100 -- Server
  3127. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  3128. AND l.is_disabled = 0
  3129. AND p.permission_name = 'ALTER SETTINGS'
  3130. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  3131. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3132. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  3133. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  3134. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  3135. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  3136. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  3137. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  3138. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  3139. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  3140. BEGIN
  3141. DECLARE @frag int
  3142. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3143. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3144. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  3145. RAISERROR (' |-Configuration options set for Disk Fragmentation Analysis', 10, 1) WITH NOWAIT
  3146. IF @sao = 0
  3147. BEGIN
  3148. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3149. END
  3150. IF @xcmd = 0
  3151. BEGIN
  3152. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3153. END
  3154. IF @ole = 0
  3155. BEGIN
  3156. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  3157. END
  3158. DECLARE @output_hw_frag TABLE ([PS_OUTPUT] VARCHAR(2048));
  3159. DECLARE @output_hw_format_frag TABLE ([volid] smallint IDENTITY(1,1), [volfrag] VARCHAR(255), [fragrec] VARCHAR(10) NULL)
  3160. IF @custompath IS NULL
  3161. BEGIN
  3162. IF @sqlmajorver < 11
  3163. BEGIN
  3164. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  3165. SET @path = @path + '\LOG'
  3166. END
  3167. ELSE
  3168. BEGIN
  3169. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  3170. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  3171. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  3172. END
  3173. -- Create COM object with FSO
  3174. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  3175. IF @OLEResult <> 0
  3176. BEGIN
  3177. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3178. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3179. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3180. END
  3181. ELSE
  3182. BEGIN
  3183. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  3184. IF @OLEResult <> 0
  3185. BEGIN
  3186. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3187. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  3188. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3189. END
  3190. ELSE
  3191. BEGIN
  3192. IF @existout <> 1
  3193. BEGIN
  3194. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  3195. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  3196. END
  3197. END
  3198. EXEC @OLEResult = sp_OADestroy @FSO
  3199. END
  3200. END
  3201. ELSE
  3202. BEGIN
  3203. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  3204. END
  3205. SET @FileName = @path + '\checkbp_frag_' + RTRIM(@server) + '.ps1'
  3206. EXEC master.dbo.xp_fileexist @FileName, @existout out
  3207. IF @existout = 0
  3208. BEGIN -- Scan for frag
  3209. SET @Text1 = '$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
  3210. $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
  3211. $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
  3212. if ($myWindowsPrincipal.IsInRole($adminRole))
  3213. {
  3214. [string] $serverName = ''localhost''
  3215. $DiskResults = @()
  3216. $objDisks = Get-WmiObject -Computername $serverName -Class Win32_Volume | Where-Object { $_.DriveType -eq 3 -and $_.Name -like "*:\"}
  3217. ForEach( $disk in $objDisks)
  3218. {
  3219. $objDefrag = $disk.DefragAnalysis()
  3220. $rec = $objDefrag.DefragRecommended
  3221. $objDefragDetail = $objDefrag.DefragAnalysis
  3222. $diskFragmentation = $objDefragDetail.TotalPercentFragmentation
  3223. $FreeFragmentation = $objDefragDetail.FreeSpacePercentFragmentation
  3224. $FileFragmentation = $objDefragDetail.FilePercentFragmentation
  3225. [string] $ThisVolume = "{0}TotalFragPct {1} :: FreeSpaceFragPct {2} :: FileFragPct {3};{4}" -f $($disk.Name),$diskFragmentation,$FreeFragmentation,$FileFragmentation,$rec
  3226. $DiskResults += $ThisVolume
  3227. }
  3228. $DiskResults
  3229. }
  3230. else
  3231. {
  3232. Write-Host "NotAdmin"
  3233. }
  3234. '
  3235. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3236. IF @OLEResult <> 0
  3237. BEGIN
  3238. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3239. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3240. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3241. END
  3242. --Open file
  3243. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3244. IF @OLEResult <> 0
  3245. BEGIN
  3246. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3247. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3248. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3249. END
  3250. ELSE
  3251. BEGIN
  3252. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3253. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3254. END
  3255. --Write Text1
  3256. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3257. IF @OLEResult <> 0
  3258. BEGIN
  3259. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3260. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3261. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3262. END
  3263. EXEC @OLEResult = sp_OADestroy @FileID
  3264. EXEC @OLEResult = sp_OADestroy @FS
  3265. END
  3266. ELSE
  3267. BEGIN
  3268. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3269. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3270. END
  3271. RAISERROR (' |-Getting Disk(s) Fragmentation. This may take some time...', 10, 1) WITH NOWAIT
  3272. IF @psver = 1
  3273. BEGIN
  3274. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3275. END
  3276. ELSE
  3277. BEGIN
  3278. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3279. END;
  3280. INSERT INTO @output_hw_frag
  3281. EXEC master.dbo.xp_cmdshell @CMD
  3282. SET @CMD = 'del /Q "' + @FileName + '"'
  3283. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3284. IF (SELECT COUNT([PS_OUTPUT]) FROM @output_hw_frag WHERE [PS_OUTPUT] LIKE '%NotAdmin%') = 1
  3285. BEGIN
  3286. RAISERROR ('[WARNING: Powershell not running under Elevated Privileges. Bypassing Disk Fragmentation Analysis]',16,1);
  3287. END
  3288. ELSE
  3289. BEGIN
  3290. INSERT INTO @output_hw_format_frag ([volfrag],fragrec)
  3291. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3292. RIGHT(RTRIM([PS_OUTPUT]), LEN(RTRIM([PS_OUTPUT]))-CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT])) END)
  3293. FROM @output_hw_frag
  3294. WHERE [PS_OUTPUT] IS NOT NULL
  3295. END
  3296. SET @CMD2 = 'del ' + @FileName
  3297. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3298. IF @xcmd = 0
  3299. BEGIN
  3300. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3301. END
  3302. IF @ole = 0
  3303. BEGIN
  3304. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3305. END
  3306. IF @sao = 0
  3307. BEGIN
  3308. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3309. END;
  3310. ;WITH fragcte (fragrec) AS (
  3311. SELECT fragrec
  3312. FROM @output_hw_format_frag
  3313. WHERE fragrec IS NOT NULL OR LEN(fragrec) > 0)
  3314. SELECT @frag = CASE WHEN (SELECT COUNT(*) FROM fragcte) = 0 THEN NULL ELSE COUNT(cte1.[fragrec]) END
  3315. FROM fragcte cte1
  3316. WHERE cte1.[fragrec] = 'True';
  3317. IF @frag > 0 AND @frag IS NOT NULL
  3318. BEGIN
  3319. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Check], '[WARNING: Found volumes with physical fragmentation. Determine how and when these can be defragmented]' AS [Deviation]
  3320. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Information],
  3321. LEFT(t1.[volfrag],1) AS HD_Volume,
  3322. RIGHT(t1.[volfrag],(LEN(t1.[volfrag])-3)) AS [Fragmentation_Percent],
  3323. t1.fragrec AS [Defragmentation_Recommended]
  3324. FROM @output_hw_format_frag t1
  3325. WHERE t1.fragrec = 'True'
  3326. ORDER BY t1.[volfrag]
  3327. OPTION (RECOMPILE);
  3328. END
  3329. ELSE IF @frag IS NULL
  3330. BEGIN
  3331. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Check], '[WARNING: Could not gather information on Disk Fragmentation Analysis]' AS [Deviation]
  3332. END
  3333. ELSE
  3334. BEGIN
  3335. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Check], '[OK]' AS [Deviation]
  3336. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Information],
  3337. LEFT(t1.[volfrag],1) AS HD_Volume,
  3338. RIGHT(t1.[volfrag],(LEN(t1.[volfrag])-3)) AS [Fragmentation_Percent],
  3339. t1.fragrec AS [Defragmentation_Recommended]
  3340. FROM @output_hw_format_frag t1
  3341. ORDER BY t1.[volfrag]
  3342. OPTION (RECOMPILE);
  3343. END;
  3344. END
  3345. ELSE
  3346. BEGIN
  3347. RAISERROR('[WARNING: Only a sysadmin can run the "Disk Fragmentation Analysis" checks. A regular user can also run this check if a xp_cmdshell proxy account exists. Bypassing check]', 16, 1, N'xp_cmdshellproxy')
  3348. RAISERROR('[WARNING: If not sysadmin, then must be a granted EXECUTE permissions on the following extended sprocs to run checks: sp_OACreate, sp_OADestroy, sp_OAGetErrorInfo, xp_cmdshell, xp_instance_regread, xp_regread, xp_fileexist and xp_regenumvalues. Bypassing check]', 16, 1, N'extended_sprocs')
  3349. --RETURN
  3350. END
  3351. END
  3352. ELSE
  3353. BEGIN
  3354. RAISERROR(' |- [INFORMATION: "Disk Fragmentation Analysis" check was skipped: either xp_cmdshell or execution of PS scripts was not allowed]', 10, 1, N'disallow_xp_cmdshell')
  3355. --RETURN
  3356. END
  3357. END
  3358. ELSE
  3359. BEGIN
  3360. RAISERROR(' |- [INFORMATION: "Disk Fragmentation Analysis" check is disabled]', 10, 1, N'disallow_diskfrag')
  3361. --RETURN
  3362. END;
  3363. --------------------------------------------------------------------------------------------------------------------------------
  3364. -- Cluster Quorum Model subsection
  3365. --------------------------------------------------------------------------------------------------------------------------------
  3366. IF @clustered = 1 AND @winver <> '5.2'
  3367. BEGIN
  3368. RAISERROR (N' |-Starting Cluster Quorum Model', 10, 1) WITH NOWAIT
  3369. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted')) AND @psver > 1
  3370. BEGIN
  3371. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3372. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3373. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  3374. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3375. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  3376. BEGIN
  3377. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3378. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3379. RAISERROR (' |-Configuration options set for Cluster Quorum Model check', 10, 1) WITH NOWAIT
  3380. IF @sao = 0
  3381. BEGIN
  3382. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3383. END
  3384. IF @xcmd = 0
  3385. BEGIN
  3386. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3387. END
  3388. DECLARE /*@CMD NVARCHAR(4000), @line int, @linemax int, */ @CntNodes tinyint, @CntVotes tinyint
  3389. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  3390. DROP TABLE #xp_cmdshell_CluNodesOutput;
  3391. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  3392. CREATE TABLE #xp_cmdshell_CluNodesOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(50));
  3393. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  3394. DROP TABLE #xp_cmdshell_CluOutput;
  3395. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  3396. CREATE TABLE #xp_cmdshell_CluOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(50));
  3397. IF @winver <> '5.2'
  3398. BEGIN
  3399. SELECT @CMD = N'powershell -NoLogo -NoProfile "Import-Module FailoverClusters"; "Get-ClusterNode | Format-Table -Autosize -HideTableHeaders NodeWeight"'
  3400. INSERT INTO #xp_cmdshell_CluNodesOutput ([Output])
  3401. EXEC master.dbo.xp_cmdshell @CMD;
  3402. END
  3403. SELECT @CMD = N'powershell -NoLogo -NoProfile "Import-Module FailoverClusters"; "Get-ClusterQuorum | Format-Table -Autosize -HideTableHeaders QuorumType"'
  3404. INSERT INTO #xp_cmdshell_CluOutput ([Output])
  3405. EXEC master.dbo.xp_cmdshell @CMD;
  3406. IF (SELECT COUNT([Output]) FROM #xp_cmdshell_CluNodesOutput WHERE [Output] = '') > 0
  3407. BEGIN
  3408. SELECT @CntNodes = COUNT(NodeName) FROM sys.dm_os_cluster_nodes (NOLOCK)
  3409. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check],
  3410. CASE WHEN REPLACE([Output], CHAR(9), '') = 'DiskOnly' AND @winver <> '5.2' THEN '[WARNING: The current quorum model is not recommended since WS2003]'
  3411. WHEN REPLACE([Output], CHAR(9), '') = 'NodeAndDiskMajority' AND @CntNodes % 2 = 1 THEN '[WARNING: The current quorum model is not recommended for a cluster with ODD number of nodes]'
  3412. WHEN REPLACE([Output], CHAR(9), '') = 'NodeMajority' AND @CntNodes % 2 = 0 THEN '[WARNING: The current quorum model is not recommended for a cluster with EVEN number of nodes]'
  3413. WHEN REPLACE([Output], CHAR(9), '') = 'NodeAndFileShareMajority' THEN '[INFORMATION: The current quorum model is recommended for clusters with special configurations]'
  3414. ELSE '[OK]' END AS [Deviation],
  3415. QUOTENAME(REPLACE([Output], CHAR(9), '')) AS QuorumModel,
  3416. '[WARNING: No count of votes available, using count of nodes instead. Check if KB2494036 applies and is installed]' AS [Comment] -- http://support.microsoft.com/kb/2494036
  3417. FROM #xp_cmdshell_CluOutput WHERE [Output] IS NOT NULL
  3418. END
  3419. ELSE
  3420. BEGIN
  3421. SELECT @CntVotes = SUM(CONVERT(int, [Output])) FROM #xp_cmdshell_CluNodesOutput WHERE [Output] IS NOT NULL
  3422. IF EXISTS (SELECT TOP 1 [Output] FROM #xp_cmdshell_CluOutput WHERE [Output] LIKE '%Majority%' OR [Output] LIKE '%Disk%')
  3423. BEGIN
  3424. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check],
  3425. CASE WHEN REPLACE([Output], CHAR(9), '') = 'DiskOnly' AND @winver <> '5.2' THEN '[WARNING: The current quorum model is not recommended since WS2003]'
  3426. WHEN REPLACE([Output], CHAR(9), '') = 'NodeAndDiskMajority' AND @CntVotes % 2 = 1 THEN '[WARNING: The current quorum model is not recommended for a cluster with ODD number of node votes]'
  3427. WHEN REPLACE([Output], CHAR(9), '') = 'NodeMajority' AND @CntVotes % 2 = 0 THEN '[WARNING: The current quorum model is not recommended for a cluster with EVEN number of node votes]'
  3428. WHEN REPLACE([Output], CHAR(9), '') = 'NodeAndFileShareMajority' THEN '[INFORMATION: The current quorum model is recommended for clusters with special configurations]'
  3429. ELSE '[OK]' END AS [Deviation],
  3430. QUOTENAME(REPLACE([Output], CHAR(9), '')) AS QuorumModel
  3431. FROM #xp_cmdshell_CluOutput WHERE [Output] IS NOT NULL
  3432. END
  3433. END
  3434. IF @xcmd = 0
  3435. BEGIN
  3436. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3437. END
  3438. IF @sao = 0
  3439. BEGIN
  3440. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3441. END
  3442. END
  3443. ELSE
  3444. BEGIN
  3445. RAISERROR('[WARNING: Only a sysadmin can run the "Cluster Quorum Model" check. A regular user can also run this check if a xp_cmdshell proxy account exists. Bypassing check]', 16, 1, N'xp_cmdshellproxy')
  3446. RAISERROR('[WARNING: If not sysadmin, then must be a granted EXECUTE permissions on the following extended sprocs to run checks: xp_cmdshell. Bypassing check]', 16, 1, N'extended_sprocs')
  3447. --RETURN
  3448. END
  3449. END
  3450. ELSE IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted')) AND @psver = 1
  3451. BEGIN
  3452. RAISERROR(' |- [INFORMATION: "Cluster Quorum Model" check was skipped: cannot execute with PS v1]', 10, 1, N'disallow_ps')
  3453. --RETURN
  3454. END
  3455. ELSE
  3456. BEGIN
  3457. RAISERROR(' |- [INFORMATION: "Cluster Quorum Model" check was skipped: either xp_cmdshell or execution of PS scripts was not allowed]', 10, 1, N'disallow_xp_cmdshell')
  3458. --RETURN
  3459. END
  3460. END
  3461. ELSE
  3462. BEGIN
  3463. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3464. END;
  3465. IF @IsHadrEnabled = 1
  3466. BEGIN
  3467. SET @sqlcmd = N'DECLARE @winver VARCHAR(5), @CntNodes tinyint
  3468. SELECT @winver = windows_release FROM sys.dm_os_windows_info (NOLOCK)
  3469. SELECT @CntNodes = SUM(number_of_quorum_votes) FROM sys.dm_hadr_cluster_members (NOLOCK)
  3470. SELECT ''Server_checks'' AS [Category], ''AlwaysOn_Cluster_Quorum'' AS [Check], cluster_name,
  3471. CASE WHEN quorum_type = 3 AND @winver <> ''5.2'' THEN ''[WARNING: The current quorum model is not recommended since WS2003]''
  3472. WHEN quorum_type = 1 AND @CntNodes % 2 = 1 THEN ''[WARNING: The current quorum model is not recommended for a cluster with ODD number of nodes]''
  3473. WHEN quorum_type = 0 AND @CntNodes % 2 = 0 THEN ''[WARNING: The current quorum model is not recommended for a cluster with EVEN number of nodes]''
  3474. WHEN quorum_type = 2 THEN ''[INFORMATION: The current quorum model is recommended for clusters with special configurations]''
  3475. ELSE ''[OK]'' END AS [Deviation],
  3476. QUOTENAME(quorum_type_desc) AS QuorumModel
  3477. FROM sys.dm_hadr_cluster;'
  3478. EXECUTE sp_executesql @sqlcmd
  3479. END;
  3480. --------------------------------------------------------------------------------------------------------------------------------
  3481. -- Cluster NIC Binding order subsection
  3482. --------------------------------------------------------------------------------------------------------------------------------
  3483. IF @allow_xpcmdshell = 1 and @clustered = 1
  3484. BEGIN
  3485. RAISERROR (N' |-Starting Cluster NIC Binding order', 10, 1) WITH NOWAIT
  3486. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  3487. BEGIN
  3488. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3489. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3490. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  3491. AND (SELECT COUNT(l.name)
  3492. FROM sys.server_permissions p JOIN sys.server_principals l
  3493. ON p.grantee_principal_id = l.principal_id
  3494. AND p.class = 100 -- Server
  3495. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  3496. AND l.is_disabled = 0
  3497. AND p.permission_name = 'ALTER SETTINGS'
  3498. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  3499. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3500. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  3501. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  3502. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  3503. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  3504. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  3505. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  3506. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  3507. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  3508. BEGIN
  3509. DECLARE @clunic int, @maxnic int
  3510. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3511. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3512. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  3513. RAISERROR (' |-Configuration options set for Cluster NIC Binding Order check', 10, 1) WITH NOWAIT
  3514. IF @sao = 0
  3515. BEGIN
  3516. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3517. END
  3518. IF @xcmd = 0
  3519. BEGIN
  3520. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3521. END
  3522. IF @ole = 0
  3523. BEGIN
  3524. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  3525. END
  3526. DECLARE @output_hw_nics TABLE ([PS_OUTPUT] VARCHAR(2048));
  3527. DECLARE @output_hw_format_nics TABLE ([nicid] smallint, [nicname] VARCHAR(255) NULL)
  3528. IF @custompath IS NULL
  3529. BEGIN
  3530. IF @sqlmajorver < 11
  3531. BEGIN
  3532. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  3533. SET @path = @path + '\LOG'
  3534. END
  3535. ELSE
  3536. BEGIN
  3537. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  3538. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  3539. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  3540. END
  3541. -- Create COM object with FSO
  3542. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  3543. IF @OLEResult <> 0
  3544. BEGIN
  3545. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3546. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3547. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3548. END
  3549. ELSE
  3550. BEGIN
  3551. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  3552. IF @OLEResult <> 0
  3553. BEGIN
  3554. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3555. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  3556. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3557. END
  3558. ELSE
  3559. BEGIN
  3560. IF @existout <> 1
  3561. BEGIN
  3562. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  3563. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  3564. END
  3565. END
  3566. EXEC @OLEResult = sp_OADestroy @FSO
  3567. END
  3568. END
  3569. ELSE
  3570. BEGIN
  3571. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  3572. END
  3573. SET @FileName = @path + '\checkbp_nics_' + RTRIM(@server) + '.ps1'
  3574. EXEC master.dbo.xp_fileexist @FileName, @existout out
  3575. IF @existout = 0
  3576. BEGIN -- Scan for nics
  3577. SET @Text1 = '[string] $serverName = ''localhost''
  3578. $nics = Get-WmiObject -Computername $serverName -query "SELECT Description, Index FROM Win32_NetworkAdapterConfiguration"
  3579. foreach ($nic in $nics)
  3580. {
  3581. [string] $allnics = "{0};{1}" -f $nic.Index,$nic.Description
  3582. Write-Output $allnics
  3583. }
  3584. '
  3585. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3586. IF @OLEResult <> 0
  3587. BEGIN
  3588. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3589. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3590. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3591. END
  3592. --Open file
  3593. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3594. IF @OLEResult <> 0
  3595. BEGIN
  3596. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3597. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3598. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3599. END
  3600. ELSE
  3601. BEGIN
  3602. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3603. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3604. END
  3605. --Write Text1
  3606. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3607. IF @OLEResult <> 0
  3608. BEGIN
  3609. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3610. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3611. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3612. END
  3613. EXEC @OLEResult = sp_OADestroy @FileID
  3614. EXEC @OLEResult = sp_OADestroy @FS
  3615. END
  3616. ELSE
  3617. BEGIN
  3618. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3619. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3620. END
  3621. IF @psver = 1
  3622. BEGIN
  3623. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3624. END
  3625. ELSE
  3626. BEGIN
  3627. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3628. END;
  3629. INSERT INTO @output_hw_nics
  3630. EXEC master.dbo.xp_cmdshell @CMD
  3631. SET @CMD = 'del /Q "' + @FileName + '"'
  3632. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3633. INSERT INTO @output_hw_format_nics ([nicid],nicname)
  3634. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3635. RIGHT(RTRIM([PS_OUTPUT]), LEN(RTRIM([PS_OUTPUT]))-CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT])) END)
  3636. FROM @output_hw_nics
  3637. WHERE [PS_OUTPUT] IS NOT NULL;
  3638. SET @CMD2 = 'del ' + @FileName
  3639. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3640. IF @xcmd = 0
  3641. BEGIN
  3642. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3643. END
  3644. IF @ole = 0
  3645. BEGIN
  3646. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3647. END
  3648. IF @sao = 0
  3649. BEGIN
  3650. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3651. END;
  3652. SELECT @maxnic = MAX(nicid) FROM @output_hw_format_nics;
  3653. SELECT TOP 1 @clunic = nicid FROM @output_hw_format_nics WHERE nicname LIKE '%Cluster Virtual Adapter%';
  3654. IF @clunic < @maxnic OR @clunic IS NULL --http://support2.microsoft.com/kb/955963
  3655. BEGIN
  3656. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], '[WARNING: The Microsoft Failover Cluster Virtual Adapter is not in the correct binding order. Should be the lowest of all present NICs]' AS [Deviation]
  3657. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Information], nicid AS NIC_ID, nicname AS NIC_Name
  3658. FROM @output_hw_format_nics t1
  3659. ORDER BY t1.[nicid]
  3660. OPTION (RECOMPILE);
  3661. END
  3662. ELSE IF @clunic = @maxnic
  3663. BEGIN
  3664. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], '[OK]' AS [Deviation]
  3665. END
  3666. ELSE
  3667. BEGIN
  3668. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], '[WARNING: Could not gather information on NIC binding order]' AS [Deviation]
  3669. END;
  3670. END
  3671. ELSE
  3672. BEGIN
  3673. RAISERROR('[WARNING: Only a sysadmin can run the "Cluster NIC Binding Order" checks. A regular user can also run this check if a xp_cmdshell proxy account exists. Bypassing check]', 16, 1, N'xp_cmdshellproxy')
  3674. RAISERROR('[WARNING: If not sysadmin, then must be a granted EXECUTE permissions on the following extended sprocs to run checks: sp_OACreate, sp_OADestroy, sp_OAGetErrorInfo, xp_cmdshell, xp_instance_regread, xp_regread, xp_fileexist and xp_regenumvalues. Bypassing check]', 16, 1, N'extended_sprocs')
  3675. --RETURN
  3676. END
  3677. END
  3678. ELSE
  3679. BEGIN
  3680. RAISERROR(' |- [INFORMATION: "Cluster NIC Binding Order" check was skipped: either xp_cmdshell or execution of PS scripts was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  3681. --RETURN
  3682. END
  3683. END
  3684. ELSE
  3685. BEGIN
  3686. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3687. END;
  3688. --------------------------------------------------------------------------------------------------------------------------------
  3689. -- Cluster QFE node equality subsection
  3690. --------------------------------------------------------------------------------------------------------------------------------
  3691. IF @clustered = 1
  3692. BEGIN
  3693. RAISERROR (N' |-Starting QFE node equality', 10, 1) WITH NOWAIT
  3694. IF @allow_xpcmdshell = 1
  3695. BEGIN
  3696. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3697. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3698. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  3699. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3700. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  3701. BEGIN
  3702. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3703. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3704. RAISERROR (' |-Configuration options set for QFE node equality check', 10, 1) WITH NOWAIT
  3705. IF @sao = 0
  3706. BEGIN
  3707. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3708. END
  3709. IF @xcmd = 0
  3710. BEGIN
  3711. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3712. END
  3713. DECLARE /* @CMD NVARCHAR(4000), @line int, @linemax int, */ @Node VARCHAR(50)
  3714. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  3715. DROP TABLE #xp_cmdshell_Nodes;
  3716. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  3717. CREATE TABLE #xp_cmdshell_Nodes (NodeName VARCHAR(50), isdone bit NOT NULL);
  3718. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  3719. DROP TABLE #xp_cmdshell_QFEOutput;
  3720. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  3721. CREATE TABLE #xp_cmdshell_QFEOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(150));
  3722. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  3723. DROP TABLE #xp_cmdshell_QFEFinal;
  3724. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  3725. CREATE TABLE #xp_cmdshell_QFEFinal (NodeName VARCHAR(50), [QFE] VARCHAR(150));
  3726. INSERT INTO #xp_cmdshell_Nodes
  3727. SELECT NodeName, 0 FROM sys.dm_os_cluster_nodes (NOLOCK);
  3728. WHILE (SELECT COUNT(NodeName) FROM #xp_cmdshell_Nodes WHERE isdone = 0) > 0
  3729. BEGIN
  3730. SELECT TOP 1 @Node = NodeName FROM #xp_cmdshell_Nodes WHERE isdone = 0;
  3731. SET @CMD = 'wmic /node:"' + @Node + '" qfe get hotfixid'
  3732. INSERT INTO #xp_cmdshell_QFEOutput ([Output])
  3733. EXEC master.dbo.xp_cmdshell @CMD;
  3734. IF (SELECT COUNT([Output]) FROM #xp_cmdshell_QFEOutput WHERE [Output] LIKE '%Access is denied%') = 0
  3735. BEGIN
  3736. INSERT INTO #xp_cmdshell_QFEFinal
  3737. SELECT @Node, RTRIM(REPLACE([Output],CHAR(13),'')) FROM #xp_cmdshell_QFEOutput WHERE RTRIM(REPLACE([Output],CHAR(13),'')) NOT IN ('','HotFixID');
  3738. END
  3739. ELSE
  3740. BEGIN
  3741. SET @ErrorMessage = '[WARNING: Access Denied error while trying to get updates from node ' + @Node + ']'
  3742. RAISERROR (@ErrorMessage,16,1);
  3743. END;
  3744. TRUNCATE TABLE #xp_cmdshell_QFEOutput;
  3745. UPDATE #xp_cmdshell_Nodes
  3746. SET isdone = 1
  3747. WHERE NodeName = @Node;
  3748. END;
  3749. IF (SELECT COUNT(DISTINCT NodeName) FROM #xp_cmdshell_QFEFinal) = (SELECT COUNT(DISTINCT NodeName) FROM #xp_cmdshell_Nodes)
  3750. BEGIN
  3751. IF (SELECT COUNT(*) FROM #xp_cmdshell_QFEFinal t1 WHERE t1.[QFE] NOT IN (SELECT DISTINCT t2.[QFE] FROM #xp_cmdshell_QFEFinal t2 WHERE t2.NodeName <> t1.NodeName)) > 0
  3752. BEGIN
  3753. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], '[WARNING: Missing updates found in some of the nodes]' AS [Deviation]
  3754. SELECT t1.NodeName, t1.[QFE] AS MissingUpdates FROM #xp_cmdshell_QFEFinal t1
  3755. WHERE t1.[QFE] NOT IN (SELECT DISTINCT t2.[QFE] FROM #xp_cmdshell_QFEFinal t2 WHERE t2.NodeName <> t1.NodeName);
  3756. END
  3757. ELSE
  3758. BEGIN
  3759. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], '[OK]' AS [Deviation];
  3760. SELECT DISTINCT t1.[QFE] AS InstalledUpdates FROM #xp_cmdshell_QFEFinal t1;
  3761. END
  3762. END
  3763. ELSE
  3764. BEGIN
  3765. RAISERROR ('[WARNING: Could not collect data from all cluster nodes. Bypassing QFE node equality check]',16,1);
  3766. END
  3767. IF @xcmd = 0
  3768. BEGIN
  3769. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3770. END
  3771. IF @sao = 0
  3772. BEGIN
  3773. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3774. END
  3775. END
  3776. ELSE
  3777. BEGIN
  3778. RAISERROR('[WARNING: Only a sysadmin can run the "QFE node equality" check. A regular user can also run this check if a xp_cmdshell proxy account exists. Bypassing check]', 16, 1, N'xp_cmdshellproxy')
  3779. RAISERROR('[WARNING: If not sysadmin, then must be a granted EXECUTE permissions on the following extended sprocs to run checks: xp_cmdshell. Bypassing check]', 16, 1, N'extended_sprocs')
  3780. --RETURN
  3781. END
  3782. END
  3783. ELSE
  3784. BEGIN
  3785. RAISERROR(' |- [INFORMATION: "QFE node equality" check was skipped because xp_cmdshell was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  3786. --RETURN
  3787. END
  3788. END
  3789. ELSE
  3790. BEGIN
  3791. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3792. END;
  3793. RAISERROR (N'|-Starting Service Accounts Checks', 10, 1) WITH NOWAIT
  3794. --------------------------------------------------------------------------------------------------------------------------------
  3795. -- Service Accounts Status subsection
  3796. --------------------------------------------------------------------------------------------------------------------------------
  3797. RAISERROR (N' |-Starting Service Accounts Status', 10, 1) WITH NOWAIT
  3798. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1)
  3799. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1 AND
  3800. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_servicecontrol') = 1)
  3801. BEGIN
  3802. DECLARE @rc int, @profile NVARCHAR(128)
  3803. DECLARE @sqlservice NVARCHAR(128), @sqlagentservice NVARCHAR(128), @dtsservice NVARCHAR(128), @ftservice NVARCHAR(128)
  3804. DECLARE @browservice NVARCHAR(128), @olapservice NVARCHAR(128), @rsservice NVARCHAR(128)
  3805. DECLARE @statussqlservice NVARCHAR(20), @statussqlagentservice NVARCHAR(20), @statusdtsservice NVARCHAR(20), @statusftservice NVARCHAR(20)
  3806. DECLARE @statusbrowservice NVARCHAR(20), @statusolapservice NVARCHAR(20), @statusrsservice NVARCHAR(20)
  3807. DECLARE @regkeysqlservice NVARCHAR(256), @regkeysqlagentservice NVARCHAR(256), @regkeydtsservice NVARCHAR(256), @regkeyftservice NVARCHAR(256)
  3808. DECLARE @regkeybrowservice NVARCHAR(256), @regkeyolapservice NVARCHAR(256), @regkeyrsservice NVARCHAR(256)
  3809. DECLARE @accntsqlservice NVARCHAR(128), @accntsqlagentservice NVARCHAR(128), @accntdtsservice NVARCHAR(128), @accntftservice NVARCHAR(128)
  3810. DECLARE @accntbrowservice NVARCHAR(128), @accntolapservice NVARCHAR(128), @accntrsservice NVARCHAR(128)
  3811. -- Get service names
  3812. IF (@instancename IS NULL)
  3813. BEGIN
  3814. IF @sqlmajorver < 11
  3815. BEGIN
  3816. SELECT @sqlservice = N'MSSQLServer'
  3817. SELECT @sqlagentservice = N'SQLServerAgent'
  3818. END
  3819. SELECT @olapservice = N'MSSQLServerOLAPService'
  3820. SELECT @rsservice = N'ReportServer'
  3821. END
  3822. ELSE
  3823. BEGIN
  3824. IF @sqlmajorver < 11
  3825. BEGIN
  3826. SELECT @sqlservice = N'MSSQL$' + @instancename
  3827. SELECT @sqlagentservice = N'SQLAgent$' + @instancename
  3828. END
  3829. SELECT @olapservice = N'MSOLAP$' + @instancename
  3830. SELECT @rsservice = N'ReportServer$' + @instancename
  3831. END
  3832. IF @sqlmajorver = 9
  3833. BEGIN
  3834. SELECT @dtsservice = N'MsDtsServer'
  3835. END
  3836. ELSE
  3837. BEGIN
  3838. SELECT @dtsservice = N'MsDtsServer' + CONVERT(VARCHAR, @sqlmajorver) + '0'
  3839. END
  3840. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3841. BEGIN
  3842. IF (@instancename IS NULL) AND @sqlmajorver = 10
  3843. BEGIN
  3844. SELECT @ftservice = N'MSSQLFDLauncher'
  3845. END
  3846. ELSE IF (@instancename IS NOT NULL) AND @sqlmajorver = 10
  3847. BEGIN
  3848. SELECT @ftservice = N'MSSQLFDLauncher$' + @instancename
  3849. END
  3850. ELSE IF (@instancename IS NULL) AND @sqlmajorver = 9
  3851. BEGIN
  3852. SELECT @ftservice = N'msftesql'
  3853. END
  3854. ELSE IF (@instancename IS NOT NULL) AND @sqlmajorver = 9
  3855. BEGIN
  3856. SELECT @ftservice = N'msftesql$' + @instancename
  3857. END
  3858. END
  3859. SELECT @browservice = N'SQLBrowser'
  3860. IF @sqlmajorver < 11
  3861. BEGIN
  3862. SELECT @regkeysqlservice = N'SYSTEM\CurrentControlSet\Services\' + @sqlservice
  3863. SELECT @regkeysqlagentservice = N'SYSTEM\CurrentControlSet\Services\' + @sqlagentservice
  3864. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3865. BEGIN
  3866. SELECT @regkeyftservice = N'SYSTEM\CurrentControlSet\Services\' + @ftservice
  3867. END
  3868. END
  3869. SELECT @regkeyolapservice = N'SYSTEM\CurrentControlSet\Services\' + @olapservice
  3870. SELECT @regkeyrsservice = N'SYSTEM\CurrentControlSet\Services\' + @rsservice
  3871. SELECT @regkeydtsservice = N'SYSTEM\CurrentControlSet\Services\' + @dtsservice
  3872. SELECT @regkeybrowservice = N'SYSTEM\CurrentControlSet\Services\' + @browservice
  3873. -- Service status
  3874. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#RegResult'))
  3875. CREATE TABLE #RegResult (ResultValue bit)
  3876. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ServiceStatus'))
  3877. CREATE TABLE #ServiceStatus (ServiceStatus VARCHAR(128))
  3878. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3879. BEGIN
  3880. BEGIN TRY
  3881. INSERT INTO #RegResult (ResultValue)
  3882. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlservice
  3883. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3884. BEGIN
  3885. INSERT INTO #ServiceStatus (ServiceStatus)
  3886. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @sqlservice
  3887. SELECT @statussqlservice = ServiceStatus FROM #ServiceStatus
  3888. TRUNCATE TABLE #ServiceStatus;
  3889. END
  3890. ELSE
  3891. BEGIN
  3892. SET @statussqlservice = 'Not Installed'
  3893. END
  3894. TRUNCATE TABLE #RegResult;
  3895. END TRY
  3896. BEGIN CATCH
  3897. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3898. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  3899. RAISERROR (@ErrorMessage, 16, 1);
  3900. END CATCH
  3901. END
  3902. ELSE
  3903. BEGIN
  3904. SET @sqlcmd = N'SELECT @statussqlserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server%'' AND servicename NOT LIKE ''SQL Server Agent%''';
  3905. SET @params = N'@statussqlserviceOUT NVARCHAR(20) OUTPUT';
  3906. EXECUTE sp_executesql @sqlcmd, @params, @statussqlserviceOUT=@statussqlservice OUTPUT;
  3907. IF @statussqlservice IS NULL
  3908. BEGIN
  3909. SET @statussqlservice = 'Not Installed'
  3910. END
  3911. END
  3912. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3913. BEGIN
  3914. BEGIN TRY
  3915. INSERT INTO #RegResult (ResultValue)
  3916. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlagentservice
  3917. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3918. BEGIN
  3919. INSERT INTO #ServiceStatus (ServiceStatus)
  3920. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @sqlagentservice
  3921. SELECT @statussqlagentservice = ServiceStatus FROM #ServiceStatus
  3922. TRUNCATE TABLE #ServiceStatus;
  3923. END
  3924. ELSE
  3925. BEGIN
  3926. SET @statussqlagentservice = 'Not Installed'
  3927. END
  3928. TRUNCATE TABLE #RegResult;
  3929. END TRY
  3930. BEGIN CATCH
  3931. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3932. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  3933. RAISERROR (@ErrorMessage, 16, 1);
  3934. END CATCH
  3935. END
  3936. ELSE
  3937. BEGIN
  3938. SET @sqlcmd = N'SELECT @statussqlagentserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server Agent%''';
  3939. SET @params = N'@statussqlagentserviceOUT NVARCHAR(20) OUTPUT';
  3940. EXECUTE sp_executesql @sqlcmd, @params, @statussqlagentserviceOUT=@statussqlagentservice OUTPUT;
  3941. IF @statussqlagentservice IS NULL
  3942. BEGIN
  3943. SET @statussqlagentservice = 'Not Installed'
  3944. END
  3945. END
  3946. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3947. BEGIN
  3948. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3949. BEGIN
  3950. BEGIN TRY
  3951. INSERT INTO #RegResult (ResultValue)
  3952. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyftservice
  3953. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3954. BEGIN
  3955. INSERT INTO #ServiceStatus (ServiceStatus)
  3956. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @ftservice
  3957. SELECT @statusftservice = ServiceStatus FROM #ServiceStatus
  3958. TRUNCATE TABLE #ServiceStatus;
  3959. END
  3960. ELSE
  3961. BEGIN
  3962. SET @statusftservice = '[INFORMATION: Service is not installed]'
  3963. END
  3964. TRUNCATE TABLE #RegResult;
  3965. END TRY
  3966. BEGIN CATCH
  3967. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3968. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  3969. RAISERROR (@ErrorMessage, 16, 1);
  3970. END CATCH
  3971. END
  3972. END
  3973. ELSE
  3974. BEGIN
  3975. SET @sqlcmd = N'SELECT @statusftserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Full-text Filter Daemon Launcher%''';
  3976. SET @params = N'@statusftserviceOUT NVARCHAR(20) OUTPUT';
  3977. EXECUTE sp_executesql @sqlcmd, @params, @statusftserviceOUT=@statusftservice OUTPUT;
  3978. IF @statusftservice IS NULL
  3979. BEGIN
  3980. SET @statusftservice = '[INFORMATION: Service is not installed]'
  3981. END
  3982. END
  3983. BEGIN TRY
  3984. INSERT INTO #RegResult (ResultValue)
  3985. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyolapservice
  3986. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3987. BEGIN
  3988. INSERT INTO #ServiceStatus (ServiceStatus)
  3989. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @olapservice
  3990. SELECT @statusolapservice = ServiceStatus FROM #ServiceStatus
  3991. TRUNCATE TABLE #ServiceStatus;
  3992. END
  3993. ELSE
  3994. BEGIN
  3995. SET @statusolapservice = 'Not Installed'
  3996. END
  3997. TRUNCATE TABLE #RegResult;
  3998. END TRY
  3999. BEGIN CATCH
  4000. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4001. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 4. ' + ERROR_MESSAGE()
  4002. RAISERROR (@ErrorMessage, 16, 1);
  4003. END CATCH
  4004. BEGIN TRY
  4005. INSERT INTO #RegResult (ResultValue)
  4006. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyrsservice
  4007. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4008. BEGIN
  4009. INSERT INTO #ServiceStatus (ServiceStatus)
  4010. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @rsservice
  4011. SELECT @statusrsservice = ServiceStatus FROM #ServiceStatus
  4012. TRUNCATE TABLE #ServiceStatus;
  4013. END
  4014. ELSE
  4015. BEGIN
  4016. SET @statusrsservice = 'Not Installed'
  4017. END
  4018. TRUNCATE TABLE #RegResult;
  4019. END TRY
  4020. BEGIN CATCH
  4021. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4022. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 5. ' + ERROR_MESSAGE()
  4023. RAISERROR (@ErrorMessage, 16, 1);
  4024. END CATCH
  4025. BEGIN TRY
  4026. INSERT INTO #RegResult (ResultValue)
  4027. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeydtsservice
  4028. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4029. BEGIN
  4030. INSERT INTO #ServiceStatus (ServiceStatus)
  4031. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @dtsservice
  4032. SELECT @statusdtsservice = ServiceStatus FROM #ServiceStatus
  4033. TRUNCATE TABLE #ServiceStatus;
  4034. END
  4035. ELSE
  4036. BEGIN
  4037. SET @statusdtsservice = 'Not Installed'
  4038. END
  4039. TRUNCATE TABLE #RegResult;
  4040. END TRY
  4041. BEGIN CATCH
  4042. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4043. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 6. ' + ERROR_MESSAGE()
  4044. RAISERROR (@ErrorMessage, 16, 1);
  4045. END CATCH
  4046. BEGIN TRY
  4047. INSERT INTO #RegResult (ResultValue)
  4048. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeybrowservice
  4049. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4050. BEGIN
  4051. INSERT INTO #ServiceStatus (ServiceStatus)
  4052. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @browservice
  4053. SELECT @statusbrowservice = ServiceStatus FROM #ServiceStatus
  4054. TRUNCATE TABLE #ServiceStatus;
  4055. END
  4056. ELSE
  4057. BEGIN
  4058. SET @statusbrowservice = 'Not Installed'
  4059. END
  4060. END TRY
  4061. BEGIN CATCH
  4062. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4063. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 7. ' + ERROR_MESSAGE()
  4064. RAISERROR (@ErrorMessage, 16, 1);
  4065. END CATCH
  4066. DROP TABLE #RegResult;
  4067. DROP TABLE #ServiceStatus;
  4068. -- Accounts
  4069. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  4070. BEGIN
  4071. BEGIN TRY
  4072. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlservice, N'ObjectName', @accntsqlservice OUTPUT, NO_OUTPUT
  4073. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlagentservice, N'ObjectName', @accntsqlagentservice OUTPUT, NO_OUTPUT
  4074. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyftservice, N'ObjectName', @accntftservice OUTPUT, NO_OUTPUT
  4075. END TRY
  4076. BEGIN CATCH
  4077. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4078. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 8. ' + ERROR_MESSAGE()
  4079. RAISERROR (@ErrorMessage, 16, 1);
  4080. END CATCH
  4081. END
  4082. ELSE
  4083. BEGIN
  4084. BEGIN TRY
  4085. SET @sqlcmd = N'SELECT @accntsqlserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server%'' AND servicename NOT LIKE ''SQL Server Agent%''';
  4086. SET @params = N'@accntsqlserviceOUT NVARCHAR(128) OUTPUT';
  4087. EXECUTE sp_executesql @sqlcmd, @params, @accntsqlserviceOUT=@accntsqlservice OUTPUT;
  4088. SET @sqlcmd = N'SELECT @accntsqlagentserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server Agent%''';
  4089. SET @params = N'@accntsqlagentserviceOUT NVARCHAR(128) OUTPUT';
  4090. EXECUTE sp_executesql @sqlcmd, @params, @accntsqlagentserviceOUT=@accntsqlagentservice OUTPUT;
  4091. SET @sqlcmd = N'SELECT @accntftserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Full-text Filter Daemon Launcher%''';
  4092. SET @params = N'@accntftserviceOUT NVARCHAR(128) OUTPUT';
  4093. EXECUTE sp_executesql @sqlcmd, @params, @accntftserviceOUT=@accntftservice OUTPUT;
  4094. END TRY
  4095. BEGIN CATCH
  4096. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4097. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 9. ' + ERROR_MESSAGE()
  4098. RAISERROR (@ErrorMessage, 16, 1);
  4099. END CATCH
  4100. END
  4101. BEGIN TRY
  4102. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyolapservice, N'ObjectName', @accntolapservice OUTPUT, NO_OUTPUT
  4103. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyrsservice, N'ObjectName', @accntrsservice OUTPUT, NO_OUTPUT
  4104. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeydtsservice, N'ObjectName', @accntdtsservice OUTPUT, NO_OUTPUT
  4105. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeybrowservice, N'ObjectName', @accntbrowservice OUTPUT, NO_OUTPUT
  4106. END TRY
  4107. BEGIN CATCH
  4108. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4109. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 10. ' + ERROR_MESSAGE()
  4110. RAISERROR (@ErrorMessage, 16, 1);
  4111. END CATCH
  4112. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server' AS [Service], @statussqlservice AS [Status], @accntsqlservice AS [Account],
  4113. CASE WHEN @statussqlservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4114. WHEN @statussqlservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4115. WHEN @accntsqlservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4116. WHEN @accntsqlservice = 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4117. WHEN @clustered = 1 AND @accntsqlservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4118. WHEN @clustered = 1 AND @accntsqlservice = 'LocalSystem' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4119. WHEN @clustered = 1 AND @accntsqlservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4120. WHEN @clustered = 0 AND @accntsqlservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4121. WHEN @clustered = 0 AND @accntsqlservice = 'LocalSystem' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4122. WHEN @clustered = 0 AND @accntsqlservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4123. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher, non-clustered (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4124. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntsqlservice <> 'NT SERVICE\MSSQLSERVER' AND @accntsqlservice NOT LIKE 'NT SERVICE\MSSQL$%' THEN '[INFORMATION: SQL Server is not running with the default account]'
  4125. ELSE '[OK]'
  4126. END AS [Deviation]
  4127. UNION ALL
  4128. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Agent' AS [Service], @statussqlagentservice AS [Status], @accntsqlagentservice AS [Account],
  4129. CASE WHEN @statussqlagentservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4130. WHEN @statussqlagentservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4131. WHEN @accntsqlagentservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4132. WHEN @accntsqlagentservice = 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4133. WHEN @accntsqlagentservice = @accntsqlservice THEN '[WARNING: Running SQL Server Agent under the same account as SQL Server is not recommended]'
  4134. WHEN @clustered = 1 AND @accntsqlagentservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4135. WHEN @clustered = 1 AND @accntsqlagentservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4136. WHEN @clustered = 0 AND @accntsqlagentservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server Agent under this account is not recommended]'
  4137. WHEN @clustered = 0 AND @accntsqlagentservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not recommended]'
  4138. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4139. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher, non-clustered (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4140. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntsqlagentservice <> 'NT SERVICE\SQLSERVERAGENT' AND @accntsqlagentservice NOT LIKE 'NT SERVICE\SQLAGENT$%' THEN '[INFORMATION: SQL Server Agent is not running with the default account]'
  4141. ELSE '[OK]'
  4142. END AS [Deviation]
  4143. UNION ALL
  4144. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Analysis_Services' AS [Service], @statusolapservice AS [Status], @accntolapservice AS [Account],
  4145. CASE WHEN @statusolapservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4146. WHEN @statusolapservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4147. WHEN @accntolapservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4148. WHEN @accntolapservice = @accntsqlservice THEN '[WARNING: Running SQL Server Analysis Services under the same account as SQL Server is not recommended]'
  4149. WHEN @clustered = 0 AND @sqlmajorver <= 10 AND @accntolapservice <> 'NT AUTHORITY\NETWORKSERVICE' AND @accntdtsservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[INFORMATION: SQL Server Analysis Services is not running with the default account]'
  4150. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4151. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND @winver <= 6.0 AND @accntolapservice <> 'NT AUTHORITY\NETWORKSERVICE' THEN '[INFORMATION: SQL Server Analysis Services is not running with the default account]'
  4152. -- MSA for WS2008R2 or higher, SQL Server 2005 or higher, non-clustered (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4153. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntolapservice <> 'NT SERVICE\MSSQLServerOLAPService' AND @accntolapservice NOT LIKE 'NT SERVICE\MSOLAP$%' THEN '[INFORMATION: SQL Server Analysis Services is not running with the default account]'
  4154. ELSE '[OK]'
  4155. END AS [Deviation]
  4156. UNION ALL
  4157. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Integration_Services' AS [Service], @statusdtsservice AS [Status], @accntdtsservice AS [Account],
  4158. CASE WHEN @statusdtsservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4159. WHEN @statusdtsservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4160. WHEN @accntdtsservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4161. WHEN @accntdtsservice = @accntsqlservice THEN '[WARNING: Running SQL Server Integration Services under the same account as SQL Server is not recommended]'
  4162. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4163. WHEN @winver <= 6.0 AND @accntdtsservice <> 'NT AUTHORITY\NETWORKSERVICE' AND @accntdtsservice <> 'NT AUTHORITY\LOCALSYSTEM' THEN '[INFORMATION: SQL Server Integration Services is not running with the default account]'
  4164. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4165. WHEN @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntdtsservice NOT IN ('NT SERVICE\MSDTSSERVER100', 'NT SERVICE\MSDTSSERVER110') THEN '[INFORMATION: SQL Server Integration Services is not running with the default account]'
  4166. ELSE '[OK]'
  4167. END AS [Deviation]
  4168. UNION ALL
  4169. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Reporting_Services' AS [Service], @statusrsservice AS [Status], @accntrsservice AS [Account],
  4170. CASE WHEN @statusrsservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4171. WHEN @statusrsservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4172. WHEN @accntrsservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4173. WHEN @accntrsservice = @accntsqlservice THEN '[WARNING: Running SQL Server Reporting Services under the same account as SQL Server is not recommended]'
  4174. WHEN @clustered = 0 AND @sqlmajorver <= 10 AND @accntrsservice <> 'NT AUTHORITY\NETWORKSERVICE' AND @accntdtsservice <> 'NT AUTHORITY\LOCALSYSTEM' THEN '[INFORMATION: SQL Server Reporting Services is not running with the default account]'
  4175. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4176. WHEN @sqlmajorver >= 11 AND @winver <= 6.0 AND @accntrsservice <> 'NT AUTHORITY\NETWORKSERVICE' THEN '[INFORMATION: SQL Server Reporting Services is not running with the default account]'
  4177. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4178. WHEN @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntrsservice <> 'NT SERVICE\ReportServer' AND @accntrsservice NOT LIKE 'NT SERVICE\ReportServer$%' THEN '[INFORMATION: SQL Server Reporting Services is not running with the default account]'
  4179. ELSE '[OK]'
  4180. END AS [Deviation]
  4181. UNION ALL
  4182. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'Full-Text' AS [Service], ISNULL(@statusftservice, 'Not Installed') AS [Status], ISNULL(@accntftservice,'') AS [Account],
  4183. CASE WHEN (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1 THEN
  4184. CASE WHEN @statusftservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4185. WHEN @statusftservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4186. WHEN @accntftservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4187. WHEN @accntftservice = @accntsqlservice THEN '[WARNING: Running Full-Text Daemon under the same account as SQL Server is not recommended]'
  4188. WHEN @accntftservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running Full-Text Service under this account is not recommended]'
  4189. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4190. WHEN @sqlmajorver <= 10 AND @accntftservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running Full-Text Service under this account is not recommended]'
  4191. WHEN @sqlmajorver <= 10 AND @accntftservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4192. WHEN @sqlmajorver >= 11 AND @winver <= 6.0 AND @accntftservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4193. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4194. WHEN @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntftservice <> 'NT SERVICE\MSSQLFDLauncher' AND @accntftservice NOT LIKE 'NT SERVICE\MSSQLFDLauncher$%' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4195. ELSE '[OK]' END
  4196. ELSE '[INFORMATION: Service is not installed]'
  4197. END AS [Deviation]
  4198. UNION ALL
  4199. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Browser' AS [Service], @statusbrowservice AS [Status], @accntbrowservice AS [Account],
  4200. CASE WHEN @statusbrowservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4201. WHEN @statusbrowservice LIKE 'Stopped%' AND @instancename IS NOT NULL THEN '[WARNING: Service is stopped on a named instance]'
  4202. WHEN @statusbrowservice LIKE 'Stopped%' AND @instancename IS NULL THEN '[WARNING: Service is stopped]'
  4203. WHEN @accntbrowservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4204. WHEN @accntbrowservice = @accntsqlservice THEN '[WARNING: Running SQL Server Browser under the same account as SQL Server is not recommended]'
  4205. WHEN @accntbrowservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: SQL Server Browser is not running with the default account]'
  4206. ELSE '[OK]'
  4207. END AS [Deviation];
  4208. END
  4209. ELSE
  4210. BEGIN
  4211. RAISERROR('[WARNING: Only a sysadmin can run the "Service Accounts Status" checks. Otherwise, you must be a granted EXECUTE permissions on xp_regread and xp_servicecontrol. Bypassing check]', 16, 1, N'sysadmin')
  4212. --RETURN
  4213. END;
  4214. --------------------------------------------------------------------------------------------------------------------------------
  4215. -- Service Accounts and SPN registration subsection
  4216. --------------------------------------------------------------------------------------------------------------------------------
  4217. RAISERROR (N' |-Starting Service Accounts and SPN registration', 10, 1) WITH NOWAIT
  4218. IF @accntsqlservice IS NOT NULL AND @accntsqlservice NOT IN ('NT AUTHORITY\LOCALSERVICE','NT AUTHORITY\SYSTEM','LocalSystem','NT AUTHORITY\NETWORKSERVICE') AND @allow_xpcmdshell = 1 AND @spn_check = 1
  4219. BEGIN
  4220. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  4221. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  4222. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  4223. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  4224. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  4225. BEGIN
  4226. RAISERROR (' |-Configuration options set for SPN check', 10, 1) WITH NOWAIT
  4227. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  4228. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  4229. IF @sao = 0
  4230. BEGIN
  4231. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  4232. END
  4233. IF @xcmd = 0
  4234. BEGIN
  4235. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  4236. END
  4237. BEGIN TRY
  4238. DECLARE /*@CMD NVARCHAR(4000),*/ @line int, @linemax int, @SPN VARCHAR(8000), @SPNMachine VARCHAR(8000)
  4239. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  4240. DROP TABLE #xp_cmdshell_AcctSPNoutput;
  4241. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  4242. CREATE TABLE #xp_cmdshell_AcctSPNoutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR (8000));
  4243. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  4244. DROP TABLE #xp_cmdshell_DupSPNoutput;
  4245. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  4246. CREATE TABLE #xp_cmdshell_DupSPNoutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR (8000));
  4247. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  4248. DROP TABLE #FinalDupSPN;
  4249. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  4250. CREATE TABLE #FinalDupSPN ([SPN] VARCHAR (8000), [Accounts] VARCHAR (8000));
  4251. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  4252. DROP TABLE #ScopedDupSPN;
  4253. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  4254. CREATE TABLE #ScopedDupSPN ([SPN] VARCHAR (8000), [Accounts] VARCHAR (8000));
  4255. SELECT @CMD = N'SETSPN -P -L ' + @accntsqlservice
  4256. INSERT INTO #xp_cmdshell_AcctSPNoutput ([Output])
  4257. EXEC master.dbo.xp_cmdshell @CMD;
  4258. SET @CMD = N'SETSPN -P -X'
  4259. INSERT INTO #xp_cmdshell_DupSPNoutput ([Output])
  4260. EXEC master.dbo.xp_cmdshell @CMD;
  4261. SELECT @SPNMachine = '%MSSQLSvc/' + CONVERT(NVARCHAR(100),SERVERPROPERTY('MachineName')) + '%';
  4262. IF EXISTS (SELECT TOP 1 b.line FROM #xp_cmdshell_AcctSPNoutput a INNER JOIN #xp_cmdshell_DupSPNoutput b ON REPLACE(UPPER(a.[Output]),CHAR(9), '') = LEFT(REPLACE(UPPER(b.[Output]),CHAR(9), ''), LEN(REPLACE(UPPER(a.[Output]),' ', ''))))
  4263. BEGIN
  4264. DECLARE curSPN CURSOR FAST_FORWARD FOR SELECT b.line, REPLACE(a.[Output], CHAR(9), '') FROM #xp_cmdshell_AcctSPNoutput a INNER JOIN #xp_cmdshell_DupSPNoutput b ON REPLACE(UPPER(a.[Output]),CHAR(9), '') = LEFT(REPLACE(UPPER(b.[Output]),CHAR(9), ''), LEN(REPLACE(UPPER(a.[Output]),' ', ''))) WHERE a.[Output] LIKE '%MSSQLSvc%'
  4265. OPEN curSPN
  4266. FETCH NEXT FROM curSPN INTO @line, @SPN
  4267. WHILE @@FETCH_STATUS = 0
  4268. BEGIN
  4269. SELECT TOP 1 @linemax = line FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND [Output] IS NULL;
  4270. INSERT INTO #FinalDupSPN
  4271. SELECT QUOTENAME(@SPN), QUOTENAME(REPLACE([Output], CHAR(9), '')) FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND line < @linemax;
  4272. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_DupSPNoutput WHERE line = @line AND [Output] LIKE @SPNMachine)
  4273. BEGIN
  4274. INSERT INTO #ScopedDupSPN
  4275. SELECT QUOTENAME(@SPN), QUOTENAME(REPLACE([Output], CHAR(9), '')) FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND line < @linemax;
  4276. END
  4277. FETCH NEXT FROM curSPN INTO @line, @SPN
  4278. END
  4279. CLOSE curSPN
  4280. DEALLOCATE curSPN
  4281. END
  4282. IF EXISTS (SELECT TOP 1 [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%')
  4283. BEGIN
  4284. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%' AND [Output] LIKE @SPNMachine)
  4285. BEGIN
  4286. SELECT 'Service_Account_checks' AS [Category], 'MSSQLSvc_SPNs_SvcAcct_CurrServer' AS [Check], '[OK]' AS [Deviation], QUOTENAME(REPLACE([Output], CHAR(9), '')) AS SPN FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE @SPNMachine
  4287. END
  4288. ELSE
  4289. BEGIN
  4290. SELECT 'Service_Account_checks' AS [Category], 'MSSQLSvc_SPNs_SvcAcct_CurrServer' AS [Check], '[WARNING: There is no registered MSSQLSvc SPN for the current service account in the scoped server name, preventing the use of Kerberos authentication]' AS [Deviation];
  4291. END
  4292. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%' AND [Output] NOT LIKE @SPNMachine)
  4293. BEGIN
  4294. SELECT 'Service_Account_checks' AS [Category], 'MSSQLSvc_SPNs_SvcAcct' AS [Check], '[INFORMATION: There are other MSSQLSvc SPNs registered for the current service account]' AS [Deviation], QUOTENAME(REPLACE([Output], CHAR(9), '')) AS SPN FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%' AND [Output] NOT LIKE @SPNMachine
  4295. END
  4296. END
  4297. ELSE
  4298. BEGIN
  4299. SELECT 'Service_Account_checks' AS [Category], 'MSSQLSvc_SPNs_SvcAcct' AS [Check], '[WARNING: There is no registered MSSQLSvc SPN for the current service account, preventing the use of Kerberos authentication]' AS [Deviation];
  4300. END
  4301. IF (SELECT COUNT(*) FROM #ScopedDupSPN) > 0
  4302. BEGIN
  4303. SELECT 'Service_Account_checks' AS [Category], 'Dup_MSSQLSvc_SPNs_Acct_CurrServer' AS [Check], '[WARNING: There are duplicate registered MSSQLSvc SPNs in the domain, for the SPN in the scoped server name]' AS [Deviation], REPLACE([SPN], CHAR(9), ''), [Accounts] AS [Information] FROM #ScopedDupSPN
  4304. END
  4305. ELSE
  4306. BEGIN
  4307. SELECT 'Service_Account_checks' AS [Category], 'Dup_MSSQLSvc_SPNs_Acct_CurrServer' AS [Check], '[OK]' AS [Deviation];
  4308. END
  4309. IF (SELECT COUNT(*) FROM #FinalDupSPN) > 0
  4310. BEGIN
  4311. SELECT 'Service_Account_checks' AS [Category], 'Dup_MSSQLSvc_SPNs_Acct' AS [Check], '[WARNING: There are duplicate registered MSSQLSvc SPNs in the domain]' AS [Deviation], [SPN], [Accounts] FROM #FinalDupSPN
  4312. END
  4313. ELSE
  4314. BEGIN
  4315. SELECT 'Service_Account_checks' AS [Category], 'Dup_MSSQLSvc_SPNs_Acct' AS [Check], '[OK]' AS [Deviation];
  4316. END
  4317. END TRY
  4318. BEGIN CATCH
  4319. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4320. SELECT @ErrorMessage = 'Service Accounts and SPN registration subsection - Error raised in TRY block 9. ' + ERROR_MESSAGE()
  4321. RAISERROR (@ErrorMessage, 16, 1);
  4322. END CATCH
  4323. IF @xcmd = 0
  4324. BEGIN
  4325. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  4326. END
  4327. IF @sao = 0
  4328. BEGIN
  4329. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  4330. END
  4331. END
  4332. ELSE
  4333. BEGIN
  4334. RAISERROR('[WARNING: Only a sysadmin can run the "Service Accounts and SPN registration" check. A regular user can also run this check if a xp_cmdshell proxy account exists. Bypassing check]', 16, 1, N'xp_cmdshellproxy')
  4335. RAISERROR('[WARNING: If not sysadmin, then must be a granted EXECUTE permissions on the following extended sprocs to run checks: xp_cmdshell. Bypassing check]', 16, 1, N'extended_sprocs')
  4336. --RETURN
  4337. END
  4338. END
  4339. ELSE
  4340. BEGIN
  4341. RAISERROR(' |- [INFORMATION: "Service Accounts and SPN registration" check was skipped: either spn checks were not allowed, xp_cmdshell was not allowed or the service account is not a domain account.]', 10, 1, N'disallow_xp_cmdshell')
  4342. --RETURN
  4343. END;
  4344. RAISERROR (N'|-Starting Instance Checks', 10, 1) WITH NOWAIT
  4345. --------------------------------------------------------------------------------------------------------------------------------
  4346. -- Recommended build check subsection
  4347. --------------------------------------------------------------------------------------------------------------------------------
  4348. RAISERROR (N' |-Starting Recommended build check', 10, 1) WITH NOWAIT
  4349. SELECT 'Instance_checks' AS [Category], 'Recommended_Build' AS [Check],
  4350. CASE WHEN (@sqlmajorver = 9 AND @sqlbuild < 5000)
  4351. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild < 6000)
  4352. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild < 6000)
  4353. OR (@sqlmajorver = 11 AND @sqlbuild < 6020)
  4354. OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  4355. OR (@sqlmajorver = 13 AND @sqlbuild < 4000)
  4356. THEN '[WARNING: current service pack has been superseded in the current SQL Server version. Install the latest service pack as soon as possible.]'
  4357. ELSE '[OK]'
  4358. END AS [Deviation],
  4359. CASE WHEN @sqlmajorver = 9 THEN '2005'
  4360. WHEN @sqlmajorver = 10 AND @sqlminorver = 0 THEN '2008'
  4361. WHEN @sqlmajorver = 10 AND @sqlminorver = 50 THEN '2008R2'
  4362. WHEN @sqlmajorver = 11 THEN '2012'
  4363. WHEN @sqlmajorver = 12 THEN '2014'
  4364. WHEN @sqlmajorver = 13 THEN '2016'
  4365. END AS [Product_Major_Version],
  4366. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductLevel')) AS Product_Level,
  4367. CASE WHEN @sqlmajorver >= 13 OR (@sqlmajorver = 12 AND @sqlbuild >= 2556 AND @sqlbuild < 4100) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427) THEN CONVERT(VARCHAR(128), SERVERPROPERTY('ProductBuildType')) ELSE 'NA' END AS Product_Build_Type,
  4368. CASE WHEN @sqlmajorver >= 13 OR (@sqlmajorver = 12 AND @sqlbuild >= 2556 AND @sqlbuild < 4100) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427) THEN CONVERT(VARCHAR(128), SERVERPROPERTY('ProductUpdateLevel')) ELSE 'NA' END AS Product_Update_Level,
  4369. CASE WHEN @sqlmajorver >= 13 OR (@sqlmajorver = 12 AND @sqlbuild >= 2556 AND @sqlbuild < 4100) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427) THEN CONVERT(VARCHAR(128), SERVERPROPERTY('ProductUpdateReference')) ELSE 'NA' END AS Product_Update_Ref_KB;
  4370. --------------------------------------------------------------------------------------------------------------------------------
  4371. -- Backup checks subsection
  4372. --------------------------------------------------------------------------------------------------------------------------------
  4373. RAISERROR (N' |-Starting Backup checks', 10, 1) WITH NOWAIT
  4374. DECLARE @nolog int, @nobck int, @nolog24h int, @neverlog int, @neverbck int
  4375. -- No Full backups
  4376. SELECT @neverbck = COUNT(DISTINCT d.name)
  4377. FROM master.sys.databases d (NOLOCK)
  4378. INNER JOIN #tmpdbs_userchoice tuc ON d.database_id = tuc.[dbid]
  4379. WHERE database_id NOT IN (2,3)
  4380. AND source_database_id IS NULL -- no snapshots
  4381. AND d.name NOT IN (SELECT b.database_name FROM msdb.dbo.backupset b WHERE b.type = 'D' AND b.is_copy_only = 0) -- Full backup and no COPY_ONLY backups
  4382. -- No Full backups in last 7 days
  4383. ;WITH cteFullBcks (cnt) AS (SELECT DISTINCT database_name AS cnt
  4384. FROM msdb.dbo.backupset b (NOLOCK)
  4385. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4386. WHERE b.type = 'D' -- Full backup
  4387. AND b.is_copy_only = 0 -- No COPY_ONLY backups
  4388. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4389. WHERE database_id NOT IN (2,3)
  4390. AND source_database_id IS NULL) -- no snapshots
  4391. GROUP BY database_name
  4392. HAVING MAX(backup_finish_date) <= DATEADD(dd, -7, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) + 1, 0)))
  4393. SELECT @nobck = COUNT(cnt)
  4394. FROM cteFullBcks;
  4395. -- Last Log backup precedes last full or diff backup, and DB in Full or Bulk-logged RM
  4396. ;WITH cteLogBcks (cnt) AS (SELECT DISTINCT database_name
  4397. FROM msdb.dbo.backupset b (NOLOCK)
  4398. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4399. WHERE b.type = 'L' -- Log backup
  4400. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4401. WHERE database_id NOT IN (2,3)
  4402. AND source_database_id IS NULL -- no snapshots
  4403. AND recovery_model < 3) -- not SIMPLE recovery model
  4404. GROUP BY [database_name]
  4405. HAVING MAX(backup_finish_date) < (SELECT MAX(backup_finish_date) FROM msdb.dbo.backupset c (NOLOCK) WHERE c.type IN ('D','I') -- Full or Differential backup
  4406. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4407. AND c.database_name = b.database_name))
  4408. SELECT @nolog = COUNT(cnt)
  4409. FROM cteLogBcks;
  4410. -- No Log backup since last full or diff backup, and DB in Full or Bulk-logged RM
  4411. SELECT @neverlog = COUNT(DISTINCT database_name)
  4412. FROM msdb.dbo.backupset b (NOLOCK)
  4413. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4414. WHERE database_name IN (SELECT name
  4415. FROM master.sys.databases (NOLOCK)
  4416. WHERE database_id NOT IN (2,3)
  4417. AND source_database_id IS NULL -- no snapshots
  4418. AND recovery_model < 3) -- not SIMPLE recovery model
  4419. AND EXISTS (SELECT DISTINCT database_name
  4420. FROM msdb.dbo.backupset c (NOLOCK)
  4421. WHERE c.type IN ('D','I') -- Full or Differential backup
  4422. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4423. AND c.database_name = b.database_name) -- Log backup
  4424. AND NOT EXISTS (SELECT DISTINCT database_name
  4425. FROM msdb.dbo.backupset c (NOLOCK)
  4426. WHERE c.type = 'L' -- Log Backup
  4427. AND c.database_name = b.database_name);
  4428. -- Log backup since last full or diff backup is older than 24h, and DB in Full ar Bulk-logged RM
  4429. ;WITH cteLogBcks2 (cnt) AS (SELECT DISTINCT database_name
  4430. FROM msdb.dbo.backupset b (NOLOCK)
  4431. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4432. WHERE b.type = 'L' -- Log backup
  4433. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4434. WHERE database_id NOT IN (2,3)
  4435. AND source_database_id IS NULL -- no snapshots
  4436. AND recovery_model < 3) -- not SIMPLE recovery model
  4437. GROUP BY database_name
  4438. HAVING MAX(backup_finish_date) > (SELECT MAX(backup_finish_date) FROM msdb.dbo.backupset c (NOLOCK) WHERE c.type IN ('D','I') -- Full or Differential backup
  4439. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4440. AND c.database_name = b.database_name)
  4441. AND MAX(backup_finish_date) <= DATEADD(hh, -24, GETDATE()))
  4442. SELECT @nolog24h = COUNT(cnt)
  4443. FROM cteLogBcks2;
  4444. IF @nobck > 0 OR @neverbck > 0
  4445. BEGIN
  4446. SELECT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Check], '[WARNING: Some databases do not have any Full backups, or the last Full backup is over 7 days]' AS [Deviation]
  4447. -- No full backups in last 7 days
  4448. SELECT DISTINCT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Information], database_name AS [Database_Name], MAX(backup_finish_date) AS Lst_Full_Backup
  4449. FROM msdb.dbo.backupset b (NOLOCK)
  4450. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4451. WHERE b.type = 'D' -- Full backup
  4452. AND b.is_copy_only = 0 -- No COPY_ONLY backups
  4453. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4454. WHERE database_id NOT IN (2,3)
  4455. AND source_database_id IS NULL) -- no snapshots
  4456. GROUP BY database_name
  4457. HAVING MAX(backup_finish_date) <= DATEADD(dd, -7, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) + 1, 0))
  4458. UNION ALL
  4459. -- No full backups in history
  4460. SELECT DISTINCT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Information], d.name AS [Database_Name], NULL AS Lst_Full_Backup
  4461. FROM master.sys.databases d (NOLOCK)
  4462. INNER JOIN #tmpdbs_userchoice tuc ON d.database_id = tuc.[dbid]
  4463. WHERE database_id NOT IN (2,3)
  4464. AND source_database_id IS NULL -- no snapshots
  4465. AND recovery_model < 3 -- not SIMPLE recovery model
  4466. AND d.name NOT IN (SELECT b.database_name FROM msdb.dbo.backupset b WHERE b.type = 'D' AND b.is_copy_only = 0) -- Full backup and no COPY_ONLY backups
  4467. AND d.name NOT IN (SELECT b.database_name FROM msdb.dbo.backupset b WHERE b.type = 'L') -- Log backup
  4468. ORDER BY [Database_Name]
  4469. END
  4470. ELSE
  4471. BEGIN
  4472. SELECT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Check], '[OK]' AS [Deviation]
  4473. END;
  4474. IF @nolog > 0 OR @neverlog > 0
  4475. BEGIN
  4476. SELECT 'Instance_checks' AS [Category], 'No_Log_Bcks_since_LstFullorDiff' AS [Check], '[WARNING: Some databases in Full or Bulk-Logged recovery model do not have any corresponding transaction Log backups since the last Full or Differential backup]' AS [Deviation]
  4477. ;WITH Bck AS (SELECT database_name, MAX(backup_finish_date) AS backup_finish_date
  4478. FROM msdb.dbo.backupset (NOLOCK) b
  4479. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4480. WHERE [type] IN ('D','I') -- Full or Differential backup
  4481. GROUP BY database_name)
  4482. -- Log backups since last full or diff is older than 24h
  4483. SELECT DISTINCT 'Instance_checks' AS [Category], 'No_Log_Bcks_since_LstFullorDiff' AS [Information], database_name AS [Database_Name], MAX(backup_finish_date) AS Lst_Log_Backup,
  4484. (SELECT backup_finish_date FROM Bck c WHERE c.database_name = b.database_name) AS Lst_FullDiff_Backup
  4485. FROM msdb.dbo.backupset b (NOLOCK)
  4486. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4487. WHERE b.type = 'L' -- Log backup
  4488. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4489. WHERE database_id NOT IN (2,3)
  4490. AND source_database_id IS NULL -- no snapshots
  4491. AND recovery_model < 3) -- not SIMPLE recovery model
  4492. GROUP BY [database_name]
  4493. HAVING MAX(backup_finish_date) < (SELECT backup_finish_date FROM Bck c WHERE c.database_name = b.database_name)
  4494. UNION ALL
  4495. -- No log backup in history but full backup exists
  4496. SELECT DISTINCT 'Instance_checks' AS [Category], 'No_Log_Bcks_since_LstFullorDiff' AS [Information], database_name AS [Database_Name], NULL AS Lst_Log_Backup, MAX(backup_finish_date) AS Lst_FullDiff_Backup
  4497. FROM msdb.dbo.backupset b (NOLOCK)
  4498. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4499. WHERE database_name IN (SELECT name
  4500. FROM master.sys.databases (NOLOCK)
  4501. WHERE database_id NOT IN (2,3)
  4502. AND source_database_id IS NULL -- no snapshots
  4503. AND recovery_model < 3) -- not SIMPLE recovery model
  4504. AND EXISTS (SELECT DISTINCT database_name
  4505. FROM msdb.dbo.backupset c (NOLOCK)
  4506. WHERE c.type IN ('D','I') -- Full or Differential backup
  4507. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4508. AND c.database_name = b.database_name) -- Log backup
  4509. AND NOT EXISTS (SELECT DISTINCT database_name
  4510. FROM msdb.dbo.backupset c (NOLOCK)
  4511. WHERE c.type = 'L' -- Log Backup
  4512. AND c.database_name = b.database_name)
  4513. GROUP BY database_name
  4514. ORDER BY database_name;
  4515. END
  4516. ELSE
  4517. BEGIN
  4518. SELECT 'Instance_checks' AS [Category], 'No_Log_Bcks_since_LstFullorDiff' AS [Check], '[OK]' AS [Deviation]
  4519. END;
  4520. IF @nolog24h > 0
  4521. BEGIN
  4522. SELECT 'Instance_checks' AS [Category], 'Log_Bcks_since_LstFullorDiff_are_older_than_24H' AS [Check], '[WARNING: Some databases in Full or Bulk-Logged recovery model have their latest log backup older than 24H]' AS [Deviation]
  4523. SELECT DISTINCT 'Instance_checks' AS [Category], 'Log_Bcks_since_LstFullorDiff_are_older_than_24H' AS [Information], database_name AS [Database_Name], MAX(backup_finish_date) AS Lst_Log_Backup
  4524. FROM msdb.dbo.backupset b (NOLOCK)
  4525. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4526. WHERE b.type = 'L' -- Log backup
  4527. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4528. WHERE database_id NOT IN (2,3)
  4529. AND recovery_model < 3) -- not SIMPLE recovery model
  4530. GROUP BY database_name
  4531. HAVING MAX(backup_finish_date) > (SELECT MAX(backup_finish_date) FROM msdb.dbo.backupset c (NOLOCK) WHERE c.type IN ('D', 'I') -- Full or Differential backup
  4532. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4533. AND c.database_name = b.database_name)
  4534. AND MAX(backup_finish_date) <= DATEADD(hh, -24, GETDATE())
  4535. ORDER BY [database_name];
  4536. END
  4537. ELSE
  4538. BEGIN
  4539. SELECT 'Instance_checks' AS [Category], 'Log_Bcks_since_LstFullorDiff_are_older_than_24H' AS [Check], '[OK]' AS [Deviation]
  4540. END;
  4541. --------------------------------------------------------------------------------------------------------------------------------
  4542. -- Global trace flags subsection
  4543. --------------------------------------------------------------------------------------------------------------------------------
  4544. RAISERROR (N' |-Starting Global trace flags', 10, 1) WITH NOWAIT
  4545. DECLARE @tracestatus TABLE (TraceFlag NVARCHAR(40), [Status] tinyint, [Global] tinyint, [Session] tinyint);
  4546. INSERT INTO @tracestatus
  4547. EXEC ('DBCC TRACESTATUS WITH NO_INFOMSGS')
  4548. IF @sqlmajorver >= 11
  4549. BEGIN
  4550. DECLARE @dbname0 VARCHAR(1000), @dbid0 int, @sqlcmd0 NVARCHAR(4000), @has_colstrix int
  4551. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  4552. DROP TABLE #tblColStoreIXs;
  4553. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  4554. CREATE TABLE #tblColStoreIXs ([DBName] VARCHAR(1000), [Schema] VARCHAR(100), [Table] VARCHAR(255), [Object] VARCHAR(255));
  4555. UPDATE #tmpdbs0
  4556. SET isdone = 0;
  4557. UPDATE #tmpdbs0
  4558. SET isdone = 1
  4559. WHERE [state] <> 0 OR [dbid] < 5;
  4560. UPDATE #tmpdbs0
  4561. SET isdone = 1
  4562. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  4563. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  4564. BEGIN
  4565. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  4566. BEGIN
  4567. SELECT TOP 1 @dbname0 = [dbname], @dbid0 = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  4568. SET @sqlcmd0 = 'USE ' + QUOTENAME(@dbname0) + ';
  4569. SELECT ''' + @dbname0 + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), i.name
  4570. FROM sys.indexes AS i (NOLOCK)
  4571. INNER JOIN sys.objects AS o (NOLOCK) ON o.[object_id] = i.[object_id]
  4572. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = i.[object_id]
  4573. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  4574. WHERE i.[type] IN (5,6,7)' -- 5 = Clustered columnstore; 6 = Nonclustered columnstore; 7 = Nonclustered hash
  4575. BEGIN TRY
  4576. INSERT INTO #tblColStoreIXs
  4577. EXECUTE sp_executesql @sqlcmd0
  4578. END TRY
  4579. BEGIN CATCH
  4580. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4581. SELECT @ErrorMessage = 'Global trace flags subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  4582. RAISERROR (@ErrorMessage, 16, 1);
  4583. END CATCH
  4584. UPDATE #tmpdbs0
  4585. SET isdone = 1
  4586. WHERE [dbid] = @dbid0
  4587. END
  4588. END;
  4589. SELECT @has_colstrix = COUNT(*) FROM #tblColStoreIXs
  4590. END;
  4591. IF (SELECT COUNT(TraceFlag) FROM @tracestatus WHERE [Global]=1) = 0
  4592. BEGIN
  4593. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check], '[There are no Global Trace Flags active]' AS [Deviation]
  4594. END;
  4595. -- Plan affecting TFs: http://support.microsoft.com/kb/2801413 and https://support.microsoft.com/en-us/kb/2964518
  4596. -- All supported TFs: http://msdn.microsoft.com/library/ms188396.aspx
  4597. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1)
  4598. BEGIN
  4599. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 634)
  4600. BEGIN
  4601. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4602. '[INFORMATION: TF634 disables the background columnstore compression task]'
  4603. AS [Deviation], TraceFlag
  4604. FROM @tracestatus
  4605. WHERE [Global] = 1 AND TraceFlag = 634
  4606. END;
  4607. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 652)
  4608. BEGIN
  4609. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4610. '[INFORMATION: TF652 disables read-aheads during scans]' --http://support.microsoft.com/en-us/kb/920093
  4611. AS [Deviation], TraceFlag
  4612. FROM @tracestatus
  4613. WHERE [Global] = 1 AND TraceFlag = 634
  4614. END;
  4615. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 661)
  4616. BEGIN
  4617. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4618. '[INFORMATION: TF661 disables the ghost cleanup background task]'
  4619. AS [Deviation], TraceFlag
  4620. FROM @tracestatus
  4621. WHERE [Global] = 1 AND TraceFlag = 661
  4622. END;
  4623. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 834)
  4624. BEGIN
  4625. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4626. CASE WHEN @sqlmajorver >= 11
  4627. AND @has_colstrix > 0
  4628. THEN '[WARNING: TF834 (Large Page Support for BP) is discouraged when Columnstore Indexes are used]'
  4629. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4630. END AS [Deviation], TraceFlag
  4631. FROM @tracestatus
  4632. WHERE [Global] = 1 AND TraceFlag = 834
  4633. END;
  4634. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 845)
  4635. BEGIN
  4636. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4637. CASE WHEN SERVERPROPERTY('EngineEdition') = 2 --Standard SKU
  4638. AND ((@sqlmajorver = 10 AND ((@sqlminorver = 0 AND @sqlbuild >= 2714) OR @sqlminorver = 50))
  4639. OR (@sqlmajorver = 9 AND @sqlbuild >= 4226))
  4640. THEN '[INFORMATION: TF845 supports locking pages in memory in SQL Server Standard Editions]'
  4641. WHEN SERVERPROPERTY('EngineEdition') = 2 --Standard SKU
  4642. AND @sqlmajorver = 11
  4643. THEN '[WARNING: TF845 is not needed in SQL 2012 and above]'
  4644. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4645. END AS [Deviation], TraceFlag
  4646. FROM @tracestatus
  4647. WHERE [Global] = 1 AND TraceFlag = 845
  4648. END;
  4649. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 902)
  4650. BEGIN
  4651. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4652. '[WARNING: TF902 Bypasses execution of database upgrade script when installing a Cumulative Update or Service Pack]'
  4653. AS [Deviation], TraceFlag
  4654. FROM @tracestatus
  4655. WHERE [Global] = 1 AND TraceFlag = 902
  4656. END;
  4657. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1117)
  4658. BEGIN
  4659. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4660. '[INFORMATION: TF1117 autogrows all files at the same time and affects all databases]'
  4661. AS [Deviation], TraceFlag
  4662. FROM @tracestatus
  4663. WHERE [Global] = 1 AND TraceFlag = 1117
  4664. END;
  4665. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1118)
  4666. BEGIN
  4667. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4668. '[INFORMATION: TF1118 forces uniform extent allocations instead of mixed page allocations]'
  4669. AS [Deviation], TraceFlag
  4670. FROM @tracestatus
  4671. WHERE [Global] = 1 AND TraceFlag = 1118
  4672. END;
  4673. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1204)
  4674. BEGIN
  4675. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4676. '[INFORMATION: TF1204 returns the resources and types of locks participating in a deadlock and also the current command affected]'
  4677. AS [Deviation], TraceFlag
  4678. FROM @tracestatus
  4679. WHERE [Global] = 1 AND TraceFlag = 1204
  4680. END;
  4681. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1211)
  4682. BEGIN
  4683. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4684. '[WARNING: TF1211 disables lock escalation based on memory pressure, or based on number of locks, increasing the amount of locks held]'
  4685. AS [Deviation], TraceFlag
  4686. FROM @tracestatus
  4687. WHERE [Global] = 1 AND TraceFlag = 1211
  4688. END;
  4689. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1222)
  4690. BEGIN
  4691. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4692. '[INFORMATION: TF1222 returns the resources and types of locks participating in a deadlock and also the current command affected]'
  4693. AS [Deviation], TraceFlag
  4694. FROM @tracestatus
  4695. WHERE [Global] = 1 AND TraceFlag = 1222
  4696. END;
  4697. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1224)
  4698. BEGIN
  4699. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4700. '[WARNING: TF1224 disables lock escalation based on the number of locks, and only escalates locks under memory pressure, increasing the amount of locks held]'
  4701. AS [Deviation], TraceFlag
  4702. FROM @tracestatus
  4703. WHERE [Global] = 1 AND TraceFlag = 1224
  4704. END;
  4705. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1229)
  4706. BEGIN
  4707. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4708. '[WARNING: TF1229 disables lock partitioning, which is a locking mechanism optimization on 16+ CPU servers]' --http://blogs.msdn.com/b/psssql/archive/2012/08/31/strange-sch-s-sch-m-deadlock-on-machines-with-16-or-more-schedulers.aspx
  4709. AS [Deviation], TraceFlag
  4710. FROM @tracestatus
  4711. WHERE [Global] = 1 AND TraceFlag = 1229
  4712. END;
  4713. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1236)
  4714. BEGIN
  4715. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4716. CASE WHEN @sqlmajorver = 9 OR @sqlmajorver = 10 OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 4100)
  4717. THEN '[INFORMATION: TF1236 enables database lock partitioning]'
  4718. WHEN (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 4100) OR @sqlmajorver = 13
  4719. THEN '[WARNING: TF1236 is not needed in SQL 2012 SP3, SQL Server 2014 SP1 and above]'
  4720. END AS [Deviation], TraceFlag
  4721. FROM @tracestatus
  4722. WHERE [Global] = 1 AND TraceFlag = 1236
  4723. END;
  4724. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1462)
  4725. BEGIN
  4726. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4727. '[WARNING: TF1462 disables log stream compression for asynchronous availability groups]'
  4728. AS [Deviation], TraceFlag
  4729. FROM @tracestatus
  4730. WHERE [Global] = 1 AND TraceFlag = 1462
  4731. END;
  4732. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2312)
  4733. BEGIN
  4734. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4735. CASE WHEN @sqlmajorver = 12
  4736. THEN '[INFORMATION: TF2312 enables New CE model, SQL Server 2014 version]'
  4737. WHEN @sqlmajorver = 13
  4738. THEN '[INFORMATION: TF2312 enables New CE model to SQL Server 2014 or SQL Server 2016 versions, dependent of the compatibility level of the database]'
  4739. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4740. END AS [Deviation], TraceFlag
  4741. FROM @tracestatus
  4742. WHERE [Global] = 1 AND TraceFlag = 2312
  4743. END;
  4744. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2330)
  4745. BEGIN
  4746. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4747. CASE WHEN @sqlmajorver = 9
  4748. THEN '[INFORMATION: TF2330 supresses data collection into sys.dm_db_index_usage_stats, which can lead to a non-yielding condition in SQL 2005]' --http://support.microsoft.com/default.aspx?scid=kb;en-US;2003031
  4749. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4750. END AS [Deviation], TraceFlag
  4751. FROM @tracestatus
  4752. WHERE [Global] = 1 AND TraceFlag = 2330
  4753. END;
  4754. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2335)
  4755. BEGIN
  4756. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4757. CASE WHEN @sqlmajorver >= 9
  4758. AND @maxservermem >= 100000 * 1024 -- 100GB
  4759. AND @maxservermem <> 2147483647
  4760. THEN '[INFORMATION: TF2335 assumes a fixed amount of memory is available during query optimization. Recommended when server has more than 100GB of memory]'
  4761. WHEN @sqlmajorver >= 9
  4762. AND @maxservermem < 100000 * 1024 -- 100GB
  4763. AND @maxservermem <> 2147483647
  4764. THEN '[WARNING: TF2335 should not be set on servers with less than 100GB of memory]'
  4765. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4766. END AS [Deviation], TraceFlag
  4767. FROM @tracestatus
  4768. WHERE [Global] = 1 AND TraceFlag = 2335
  4769. END;
  4770. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2335)
  4771. AND @sqlmajorver >= 9
  4772. AND @maxservermem >= 100000 * 1024 -- 100GB
  4773. AND @maxservermem <> 2147483647
  4774. BEGIN
  4775. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4776. '[INFORMATION: Consider enabling TF2335 to use a fixed amount of memory is available during query optimization. Recommended when server has more than 100GB of memory]' --http://support.microsoft.com/kb/2413549/en-us
  4777. AS [Deviation]
  4778. END;
  4779. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2340)
  4780. BEGIN
  4781. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4782. '[INFORMATION: TF2340 causes SQL Server not to use a sort operation (batch sort) for optimized nested loop joins when generating a plan]'
  4783. AS [Deviation], TraceFlag
  4784. FROM @tracestatus
  4785. WHERE [Global] = 1 AND TraceFlag = 2340
  4786. END;
  4787. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2371)
  4788. BEGIN
  4789. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4790. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500) OR @sqlmajorver >= 11
  4791. THEN '[INFORMATION: TF2371 changes the fixed rate of the 20pct threshold for update statistics into a dynamic percentage rate]'
  4792. WHEN @sqlmajorver = 13
  4793. THEN '[WARNING: TF2371 is not needed in SQL 2016 and above]'
  4794. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4795. END AS [Deviation], TraceFlag
  4796. FROM @tracestatus
  4797. WHERE [Global] = 1 AND TraceFlag = 2371
  4798. END;
  4799. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2371)
  4800. AND ((@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500) OR @sqlmajorver >= 11)
  4801. BEGIN
  4802. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4803. '[INFORMATION: Consider enabling TF2371 to change the 20pct fixed rate threshold for update statistics into a dynamic percentage rate]' --http://blogs.msdn.com/b/saponsqlserver/archive/2011/09/07/changes-to-automatic-update-statistics-in-sql-server-traceflag-2371.aspx
  4804. AS [Deviation]
  4805. END;
  4806. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2389)
  4807. BEGIN
  4808. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4809. '[INFORMATION: TF2389 enables automatically generated quick statistics for ascending keys (histogram amendment)]'
  4810. AS [Deviation], TraceFlag
  4811. FROM @tracestatus
  4812. WHERE [Global] = 1 AND TraceFlag = 2389
  4813. END;
  4814. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2528)
  4815. BEGIN
  4816. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4817. '[INFORMATION: TF2528 disables parallel checking of objects by DBCC CHECKDB, DBCC CHECKFILEGROUP, and DBCC CHECKTABLE]'
  4818. AS [Deviation], TraceFlag
  4819. FROM @tracestatus
  4820. WHERE [Global] = 1 AND TraceFlag = 2528
  4821. END;
  4822. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2549)
  4823. BEGIN
  4824. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4825. '[INFORMATION: TF2549 runs the DBCC CHECKDB command assuming each database file is on a unique disk drive]'
  4826. AS [Deviation], TraceFlag
  4827. FROM @tracestatus
  4828. WHERE [Global] = 1 AND TraceFlag = 2549
  4829. END;
  4830. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2562)
  4831. BEGIN
  4832. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4833. '[INFORMATION: TF2562 runs the DBCC CHECKDB command in a single batch regardless of the number of indexes in the database]'
  4834. AS [Deviation], TraceFlag
  4835. FROM @tracestatus
  4836. WHERE [Global] = 1 AND TraceFlag = 2562
  4837. END;
  4838. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2566)
  4839. BEGIN
  4840. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4841. '[INFORMATION: TF2566 runs the DBCC CHECKDB command without data purity check unless DATA_PURITY option is specified]'
  4842. AS [Deviation], TraceFlag
  4843. FROM @tracestatus
  4844. WHERE [Global] = 1 AND TraceFlag = 2566
  4845. END;
  4846. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3023)
  4847. BEGIN
  4848. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4849. '[INFORMATION: TF3023 enables CHECKSUM option as default for BACKUP command]'
  4850. AS [Deviation], TraceFlag
  4851. FROM @tracestatus
  4852. WHERE [Global] = 1 AND TraceFlag = 3023
  4853. END;
  4854. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3042)
  4855. BEGIN
  4856. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4857. '[INFORMATION: TF3042 bypasses the default backup compression pre-allocation algorithm to allow the backup file to grow only as needed to reach its final size]'
  4858. AS [Deviation], TraceFlag
  4859. FROM @tracestatus
  4860. WHERE [Global] = 1 AND TraceFlag = 3042
  4861. END;
  4862. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3226)
  4863. BEGIN
  4864. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4865. '[INFORMATION: TF3226 prevents SQL Server from recording an entry to Errorlog on every successful backup operation]'
  4866. AS [Deviation], TraceFlag
  4867. FROM @tracestatus
  4868. WHERE [Global] = 1 AND TraceFlag = 3226
  4869. END;
  4870. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4135)
  4871. BEGIN
  4872. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4873. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1818 AND 1835)
  4874. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1702)
  4875. THEN '[WARNING: TF4199 should be used instead of TF4135 in this SQL build]'
  4876. ELSE '[INFORMATION: TF4135 enables query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  4877. END AS [Deviation], TraceFlag
  4878. FROM @tracestatus
  4879. WHERE [Global] = 1 AND TraceFlag = 4135
  4880. END;
  4881. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4136)
  4882. BEGIN
  4883. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4884. CASE WHEN (@sqlmajorver = 9 AND @sqlbuild >= 4294)
  4885. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 2766)
  4886. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1720)
  4887. OR (@sqlmajorver = 11 AND @sqlbuild >= 2316)
  4888. OR @sqlmajorver >= 12
  4889. THEN '[INFORMATION: TF4136 disables parameter sniffing unless OPTION(RECOMPILE), WITH RECOMPILE or OPTIMIZE FOR value is used]'
  4890. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4891. END AS [Deviation], TraceFlag
  4892. FROM @tracestatus
  4893. WHERE [Global] = 1 AND TraceFlag = 4136
  4894. END;
  4895. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4137)
  4896. BEGIN
  4897. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4898. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 5794)
  4899. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 4326 AND 4371)
  4900. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2806)
  4901. OR (@sqlmajorver = 11 AND @sqlbuild >= 2316)
  4902. OR @sqlmajorver >= 12
  4903. THEN '[INFORMATION: TF4137 causes SQL Server to generate a plan using minimum selectivity when estimating AND predicates for filters to account for correlation, under the Legacy CE]'
  4904. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4905. END AS [Deviation], TraceFlag
  4906. FROM @tracestatus
  4907. WHERE [Global] = 1 AND TraceFlag = 4137
  4908. END;
  4909. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4138)
  4910. BEGIN
  4911. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4912. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4260)
  4913. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 2817 AND 2881)
  4914. OR (@sqlmajorver = 11 AND @sqlbuild >= 2325)
  4915. OR @sqlmajorver >= 12
  4916. THEN '[INFORMATION: TF4138 causes SQL Server to generate a plan that does not use row goal adjustments with queries that contain TOP, OPTION (FAST N), IN, or EXISTS keywords]'
  4917. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4918. END AS [Deviation], TraceFlag
  4919. FROM @tracestatus
  4920. WHERE [Global] = 1 AND TraceFlag = 4138
  4921. END;
  4922. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4139)
  4923. BEGIN
  4924. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4925. CASE WHEN (@sqlmajorver = 11 AND @sqlbuild >= 5532)
  4926. OR (@sqlmajorver = 11 AND @sqlbuild >= 3431 AND @sqlbuild < 5058)
  4927. OR @sqlmajorver >= 12
  4928. THEN '[INFORMATION: TF4139 enables automatically generated quick statistics (histogram amendment) regardless of key column status]'
  4929. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4930. END AS [Deviation], TraceFlag
  4931. FROM @tracestatus
  4932. WHERE [Global] = 1 AND TraceFlag = 4139
  4933. END;
  4934. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4199)
  4935. BEGIN
  4936. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4937. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1787 AND 1812)
  4938. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 2531 AND 2757)
  4939. OR (@sqlmajorver >= 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 1600 AND 1617)
  4940. THEN '[WARNING: TF4135 should be used instead of TF4199 in this SQL build]'
  4941. ELSE '[INFORMATION: TF4199 enables query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  4942. END AS [Deviation], TraceFlag
  4943. FROM @tracestatus
  4944. WHERE [Global] = 1 AND TraceFlag = 4199
  4945. END;
  4946. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 6498)
  4947. BEGIN
  4948. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4949. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 4416)
  4950. OR (@sqlmajorver = 12 AND @sqlbuild BETWEEN 2480 AND 2474)
  4951. THEN '[INFORMATION: TF6498 enables more than one large query compilation to gain access to the big gateway when there is sufficient memory available]'
  4952. WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver >= 13
  4953. THEN '[WARNING: TF6498 is not needed in SQL 2014 SP2, SQL Server 2016 and above]'
  4954. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4955. END AS [Deviation], TraceFlag
  4956. FROM @tracestatus
  4957. WHERE [Global] = 1 AND TraceFlag = 6498
  4958. END;
  4959. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag IN (6532,6533))
  4960. BEGIN
  4961. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4962. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000)
  4963. OR (@sqlmajorver = 11 AND @sqlbuild >= 6020)
  4964. THEN '[INFORMATION: TF6532 and TF 6533 enable performance improvement of query operations with spatial data types]'
  4965. WHEN @sqlmajorver = 13
  4966. THEN '[WARNING: TF6532 and TF 6533 are not needed in SQL Server 2016 and above]'
  4967. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4968. END AS [Deviation], TraceFlag
  4969. FROM @tracestatus
  4970. WHERE [Global] = 1 AND TraceFlag IN (6532,6533)
  4971. END;
  4972. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 6534)
  4973. BEGIN
  4974. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4975. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000)
  4976. OR (@sqlmajorver = 11 AND @sqlbuild >= 6020)
  4977. OR @sqlmajorver = 13
  4978. THEN '[INFORMATION: TF6534 enables performance improvement of query operations with spatial data types]'
  4979. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4980. END AS [Deviation], TraceFlag
  4981. FROM @tracestatus
  4982. WHERE [Global] = 1 AND TraceFlag = 6534
  4983. END;
  4984. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8015)
  4985. BEGIN
  4986. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4987. CASE WHEN (@sqlmajorver = 11 AND @sqlbuild >= 3349)
  4988. OR @sqlmajorver >= 12
  4989. THEN '[WARNING: TF8015 disables auto-detection and NUMA setup]' --http://blogs.msdn.com/b/psssql/archive/2010/04/02/how-it-works-soft-numa-i-o-completion-thread-lazy-writer-workers-and-memory-nodes.aspx
  4990. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4991. END AS [Deviation], TraceFlag
  4992. FROM @tracestatus
  4993. WHERE [Global] = 1 AND TraceFlag = 8015
  4994. END;
  4995. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8032)
  4996. BEGIN
  4997. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4998. CASE WHEN @sqlmajorver >= 10
  4999. THEN '[WARNING: TF8032 reverts the cache limit parameters to the SQL Server 2005 RTM setting but can cause poor performance if large caches make less memory available for other memory consumers like BP]'
  5000. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5001. END AS [Deviation], TraceFlag
  5002. FROM @tracestatus
  5003. WHERE [Global] = 1 AND TraceFlag = 8032
  5004. END;
  5005. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8048)
  5006. BEGIN
  5007. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5008. CASE WHEN ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5009. OR (@sqlmajorver BETWEEN 9 AND 11))
  5010. AND (@cpucount/@numa) > 8
  5011. THEN '[INFORMATION: TF8048 converts NUMA partitioned memory objects into CPU partitioned]' --http://blogs.msdn.com/b/psssql/archive/2011/09/01/sql-server-2008-2008-r2-on-newer-machines-with-more-than-8-cpus-presented-per-numa-node-may-need-trace-flag-8048.aspx
  5012. WHEN (@sqlmajorver = 12 AND @sqlbuild >= 4100) OR @sqlmajorver >= 13
  5013. THEN '[WARNING: TF8048 is not needed in SQL Server 2014 SP2, SQL Server 2016 and above]'
  5014. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5015. END AS [Deviation], TraceFlag
  5016. FROM @tracestatus
  5017. WHERE [Global] = 1 AND TraceFlag = 8048
  5018. END;
  5019. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8048)
  5020. AND ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5021. OR (@sqlmajorver BETWEEN 9 AND 11))
  5022. AND (@cpucount/@numa) > 8
  5023. BEGIN
  5024. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5025. '[INFORMATION: Consider enabling TF8048 to convert NUMA partitioned memory objects into CPU partitioned. Look in dm_os_wait_stats and dm_os_spin_stats for wait types (CMEMTHREAD and SOS_SUSPEND_QUEUE). Microsoft CSS usually sees the spins jump into the trillions and the waits become a hot spot]' --http://blogs.msdn.com/b/psssql/archive/2011/09/01/sql-server-2008-2008-r2-on-newer-machines-with-more-than-8-cpus-presented-per-numa-node-may-need-trace-flag-8048.aspx
  5026. AS [Deviation];
  5027. -- If the top consumers are partitioned by Node, then use startup trace flag 8048 to further partition by CPU.
  5028. IF @sqlmajorver < 11
  5029. BEGIN
  5030. SELECT 'Instance_checks' AS [Category], 'Is_TF8048_Applicable' AS [Check], [type],
  5031. SUM(page_size_in_bytes)/8192 AS [pages],
  5032. SUM(page_size_in_bytes)/1024 AS pages_in_KB,
  5033. CASE WHEN (0x20 = creation_options & 0x20) THEN 'Global PMO. Cannot be partitioned by CPU/NUMA Node. TF8048 not applicable.'
  5034. WHEN (0x40 = creation_options & 0x40) THEN 'Partitioned by CPU. TF8048 not applicable.'
  5035. WHEN (0x80 = creation_options & 0x80) THEN 'Partitioned by Node. Use TF8048 to further partition by CPU'
  5036. ELSE 'Unknown' END AS [Comment]
  5037. FROM sys.dm_os_memory_objects
  5038. GROUP BY [type], creation_options
  5039. ORDER BY SUM(page_size_in_bytes) DESC;
  5040. END
  5041. ELSE
  5042. BEGIN
  5043. SET @sqlcmd = N'SELECT ''Instance_checks'' AS [Category], ''Is_TF8048_Applicable'' AS [Check], [type],
  5044. SUM(pages_in_bytes)/8192 AS [pages],
  5045. SUM(pages_in_bytes)/1024 AS pages_in_KB,
  5046. CASE WHEN (0x20 = creation_options & 0x20) THEN ''Global PMO. Cannot be partitioned by CPU/NUMA Node. TF8048 not applicable.''
  5047. WHEN (0x40 = creation_options & 0x40) THEN ''Partitioned by CPU. TF8048 not applicable.''
  5048. WHEN (0x80 = creation_options & 0x80) THEN ''Partitioned by Node. Use TF8048 to further partition by CPU''
  5049. ELSE ''Unknown'' END AS [Comment]
  5050. FROM sys.dm_os_memory_objects
  5051. GROUP BY [type], creation_options
  5052. ORDER BY SUM(pages_in_bytes) DESC;'
  5053. EXECUTE sp_executesql @sqlcmd
  5054. END;
  5055. END;
  5056. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8744)
  5057. BEGIN
  5058. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5059. CASE WHEN @sqlmajorver >= 12 THEN
  5060. '[INFORMATION: TF8744 disables pre-fetching for the Nested Loop operator]'
  5061. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5062. END AS [Deviation], TraceFlag
  5063. FROM @tracestatus
  5064. WHERE [Global] = 1 AND TraceFlag = 8744
  5065. END;
  5066. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9024)
  5067. BEGIN
  5068. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5069. CASE WHEN ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5070. OR (@sqlmajorver = 11 AND @sqlbuild >= 3349 AND @sqlbuild < 6020))
  5071. AND (@cpucount/@numa) > 8
  5072. THEN '[INFORMATION: TF9024 converts a global log pool memory object into NUMA node partitioned memory object]'
  5073. WHEN (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427) OR @sqlmajorver > 12
  5074. THEN '[WARNING: TF9024 is not needed in SQL Server 2012 SP3, SQL Server 2014 SP1 and above]'
  5075. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5076. END AS [Deviation], TraceFlag
  5077. FROM @tracestatus
  5078. WHERE [Global] = 1 AND TraceFlag = 9024
  5079. END;
  5080. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9347)
  5081. BEGIN
  5082. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5083. CASE WHEN @sqlmajorver >= 13 THEN
  5084. '[INFORMATION: TF9347 disables batch mode for sort operator]'
  5085. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5086. END AS [Deviation], TraceFlag
  5087. FROM @tracestatus
  5088. WHERE [Global] = 1 AND TraceFlag = 9347
  5089. END;
  5090. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9349)
  5091. BEGIN
  5092. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5093. CASE WHEN @sqlmajorver >= 13 THEN
  5094. '[INFORMATION: TF9349 disables batch mode for top N sort operator]'
  5095. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5096. END AS [Deviation], TraceFlag
  5097. FROM @tracestatus
  5098. WHERE [Global] = 1 AND TraceFlag = 9349
  5099. END;
  5100. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9389)
  5101. BEGIN
  5102. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5103. CASE WHEN @sqlmajorver >= 13 THEN
  5104. '[INFORMATION: TF9389 enables dynamic memory grant for batch mode operators]'
  5105. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5106. END AS [Deviation], TraceFlag
  5107. FROM @tracestatus
  5108. WHERE [Global] = 1 AND TraceFlag = 9389
  5109. END;
  5110. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9476)
  5111. BEGIN
  5112. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5113. CASE WHEN @sqlmajorver >= 13 THEN
  5114. '[INFORMATION: TF9476 causes SQL Server to generate a plan using the Simple Containment instead of the default Base Containment under New CE]'
  5115. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5116. END AS [Deviation], TraceFlag
  5117. FROM @tracestatus
  5118. WHERE [Global] = 1 AND TraceFlag = 9476
  5119. END;
  5120. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9481)
  5121. BEGIN
  5122. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5123. CASE WHEN @sqlmajorver >= 12
  5124. THEN '[INFORMATION: TF9481 enables Legacy CE model, irrespective of the compatibility level of the database]'
  5125. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5126. END AS [Deviation], TraceFlag
  5127. FROM @tracestatus
  5128. WHERE [Global] = 1 AND TraceFlag = 9481
  5129. END;
  5130. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 10204)
  5131. BEGIN
  5132. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5133. CASE WHEN @sqlmajorver >= 13
  5134. THEN '[INFORMATION: TF10204 disables merge/recompress during columnstore index reorganization]'
  5135. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5136. END AS [Deviation], TraceFlag
  5137. FROM @tracestatus
  5138. WHERE [Global] = 1 AND TraceFlag = 10204
  5139. END;
  5140. END;
  5141. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag IN (4135,4199))
  5142. BEGIN
  5143. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5144. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1787 AND 1812)
  5145. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 2531 AND 2757)
  5146. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 2766)
  5147. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 1600 AND 1617)
  5148. THEN '[INFORMATION: Consider enabling TF4135 to support fixes and enhancements on the query optimizer]'
  5149. WHEN (@sqlmajorver = 9 AND @sqlbuild >= 4266)
  5150. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1818 AND 1835)
  5151. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1702) OR @sqlmajorver >= 11
  5152. THEN '[INFORMATION: Consider enabling TF4199 to enable query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  5153. END AS [Deviation]
  5154. END;
  5155. --------------------------------------------------------------------------------------------------------------------------------
  5156. -- System configurations subsection
  5157. --------------------------------------------------------------------------------------------------------------------------------
  5158. RAISERROR (N' |-Starting System configurations', 10, 1) WITH NOWAIT
  5159. -- Focus on:
  5160. -- backup compression default
  5161. -- clr enabled (only enable if needed)
  5162. -- lightweight pooling (should be zero)
  5163. -- max degree of parallelism
  5164. -- cost threshold for parallelism
  5165. -- max server memory (MB) (set to an appropriate value)
  5166. -- priority boost (should be zero)
  5167. -- remote admin connections (should be enabled in a cluster configuration, to allow remote DAC)
  5168. -- scan for startup procs (should be disabled unless business requirement, like replication)
  5169. -- min memory per query (default is 1024KB)
  5170. -- allow updates (no effect in 2005 or above, but should be off)
  5171. -- max worker threads (should be zero in 2005 or above)
  5172. -- affinity mask and affinity I/O mask (must not overlap)
  5173. DECLARE @awe tinyint, @ssp bit, @bckcomp bit, @clr bit, @costparallel tinyint, @chain bit, @lpooling bit
  5174. DECLARE @adhoc smallint, @pboost bit, @qtimeout int, @cmdshell bit, @deftrace bit, @remote bit, @autoNUMA bit
  5175. DECLARE @minmemqry int, @allowupd bit, @mwthreads int, @recinterval int, @netsize smallint
  5176. DECLARE @ixmem smallint, @adhocqry bit, @locks int, @qrywait int--, @mwthreads_count int
  5177. DECLARE @affin int, @affinIO int, @affin64 int, @affin64IO int, @block_threshold int, @oleauto int
  5178. --SELECT @mwthreads_count = max_workers_count FROM sys.dm_os_sys_info;
  5179. SELECT @adhocqry = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'Ad Hoc Distributed Queries';
  5180. SELECT @affin = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity mask';
  5181. SELECT @affinIO = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity I/O mask';
  5182. SELECT @affin64 = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity64 mask';
  5183. SELECT @affin64IO = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity64 I/O mask';
  5184. SELECT @allowupd = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'allow updates';
  5185. SELECT @block_threshold = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'blocked process threshold (s)';
  5186. SELECT @awe = CONVERT(tinyint, [value]) FROM sys.configurations WHERE [Name] = 'awe enabled';
  5187. SELECT @autoNUMA = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'automatic soft-NUMA disabled';
  5188. SELECT @bckcomp = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'backup compression default';
  5189. SELECT @clr = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'clr enabled';
  5190. SELECT @costparallel = CONVERT(tinyint, [value]) FROM sys.configurations WHERE [Name] = 'cost threshold for parallelism';
  5191. SELECT @chain = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'cross db ownership chaining';
  5192. SELECT @deftrace = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'default trace enabled';
  5193. SELECT @ixmem = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'index create memory (KB)';
  5194. SELECT @locks = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'locks';
  5195. SELECT @minmemqry = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'min memory per query (KB)';
  5196. SELECT @mwthreads = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'max worker threads';
  5197. SELECT @netsize = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'network packet size (B)';
  5198. SELECT @lpooling = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'lightweight pooling';
  5199. SELECT @recinterval = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'recovery interval (min)';
  5200. SELECT @remote = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'remote admin connections';
  5201. SELECT @qrywait = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'query wait (s)';
  5202. SELECT @adhoc = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'optimize for ad hoc workloads';
  5203. SELECT @oleauto = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'Ole Automation Procedures';
  5204. SELECT @pboost = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'priority boost';
  5205. SELECT @qtimeout = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'remote query timeout (s)';
  5206. SELECT @ssp = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'scan for startup procs';
  5207. SELECT @cmdshell = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'xp_cmdshell';
  5208. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Allow updates' AS [Setting], @allowupd AS [Current Value], CASE WHEN @allowupd = 0 THEN '[OK]' ELSE '[WARNING: Microsoft does not support direct catalog updates]' END AS [Deviation], '' AS [Comment]
  5209. UNION ALL
  5210. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Ad Hoc Distributed Queries' AS [Setting], @adhocqry AS [Current Value], CASE WHEN @adhocqry = 0 THEN '[OK]' ELSE '[WARNING: Ad Hoc Distributed Queries are enabled]' END AS [Deviation], '' AS [Comment]
  5211. UNION ALL
  5212. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Auto Soft NUMA Enabled' AS [Setting], @autoNUMA AS [Current Value], CASE WHEN @sqlmajorver >= 13 AND @autoNUMA = 0 THEN '[WARNING: Auto Soft NUMA is not enabled]' WHEN @sqlmajorver < 13 THEN '[NA]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5213. UNION ALL
  5214. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Affinity Mask' AS [Setting], @affin AS [Current Value], CASE WHEN (@affin & @affinIO <> 0) OR (@affin & @affinIO <> 0 AND @affin64 & @affin64IO <> 0) THEN '[WARNING: Current Affinity Mask and Affinity I/O Mask are overlaping]' ELSE '[OK]' END AS [Deviation], '[INFORMATION: Configured values for AffinityMask = ' + CONVERT(VARCHAR(10), @affin) + '; Affinity64Mask = ' + CONVERT(VARCHAR(10), @affin64) + '; AffinityIOMask = ' + CONVERT(VARCHAR(10), @affinIO) + '; Affinity64IOMask = ' + CONVERT(VARCHAR(10), @affin64IO) + ']' AS [Comment]
  5215. UNION ALL
  5216. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Affinity I/O Mask' AS [Setting], @affinIO AS [Current Value], CASE WHEN (@affin & @affinIO <> 0) OR (@affin & @affinIO <> 0 AND @affin64 & @affin64IO <> 0) THEN '[WARNING: Current Affinity Mask and Affinity I/O Mask are overlaping]' ELSE '[OK]' END AS [Deviation], '[INFORMATION: Configured values for AffinityMask = ' + CONVERT(VARCHAR(10), @affin) + '; Affinity64Mask = ' + CONVERT(VARCHAR(10), @affin64) + '; AffinityIOMask = ' + CONVERT(VARCHAR(10), @affinIO) + '; Affinity64IOMask = ' + CONVERT(VARCHAR(10), @affin64IO) + ']' AS [Comment]
  5217. UNION ALL
  5218. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'AWE' AS [Setting], @awe AS [Current Value], CASE WHEN @sqlmajorver < 11 AND @arch = 32 AND @systemmem >= 4000 AND @awe = 0 THEN '[WARNING: Current AWE setting is not optimal for this configuration]' WHEN @sqlmajorver < 11 AND @arch IS NULL THEN '[WARNING: Could not determine architecture needed for check]' WHEN @sqlmajorver > 10 THEN '[INFORMATION: AWE is not used from SQL Server 2012 onwards]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5219. UNION ALL
  5220. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Backup Compression' AS [Setting], @bckcomp AS [Current Value], CASE WHEN @sqlmajorver > 9 AND @bckcomp = 0 THEN '[INFORMATION: Backup compression setting is not the recommended value]' WHEN @sqlmajorver < 10 THEN '[NA]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5221. UNION ALL
  5222. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Blocked Process Threshold' AS [Setting], @block_threshold AS [Current Value], CASE WHEN @block_threshold > 0 AND @block_threshold < 5 THEN '[WARNING: Blocked Process Threshold setting is not the recommended value. If not disabled, value should be higher than 4]' WHEN @block_threshold >= 5 THEN '[INFORMATION: Blocked Process Threshold setting is not the default value]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5223. UNION ALL
  5224. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'CLR' AS [Setting], @clr AS [Current Value], CASE WHEN @clr = 1 THEN '[INFORMATION: CLR user code execution setting is enabled]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5225. UNION ALL
  5226. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Cost threshold for Parallelism' AS [Setting], @costparallel AS [Current Value], CASE WHEN @costparallel = 5 THEN '[OK]' ELSE '[WARNING: Cost threshold for Parallelism setting is not the default value]' END AS [Deviation], '' AS [Comment]
  5227. UNION ALL
  5228. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Cross DB ownership Chaining' AS [Setting], @chain AS [Current Value], CASE WHEN @chain = 1 THEN '[WARNING: Cross DB ownership chaining setting is not the recommended value]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5229. UNION ALL
  5230. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Default trace' AS [Setting], @deftrace AS [Current Value], CASE WHEN @deftrace = 0 THEN '[WARNING: Default trace setting is NOT enabled]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5231. UNION ALL
  5232. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Index create memory (KB)' AS [Setting], @ixmem AS [Current Value], CASE WHEN @ixmem = 0 THEN '[OK]' WHEN @ixmem > 0 AND @ixmem < @minmemqry THEN '[WARNING: Index create memory should not be less than Min memory per query]' ELSE '[WARNING: Index create memory is not the default value]' END AS [Deviation], '' AS [Comment]
  5233. UNION ALL
  5234. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Lightweight pooling' AS [Setting], @lpooling AS [Current Value], CASE WHEN @lpooling = 1 THEN '[WARNING: Lightweight pooling setting is not the recommended value]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5235. UNION ALL
  5236. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Locks' AS [Setting], @locks AS [Current Value], CASE WHEN @locks = 0 THEN '[OK]' ELSE '[WARNING: Locks option is not set with the default value]' END AS [Deviation], '' AS [Comment]
  5237. UNION ALL
  5238. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Max worker threads' AS [Setting], @mwthreads AS [Current Value], CASE WHEN @mwthreads = 0 THEN '[OK]' WHEN @mwthreads > 2048 AND @arch = 64 THEN '[WARNING: Max worker threads is larger than 2048 on a x64 system]' WHEN @mwthreads > 1024 AND @arch = 32 THEN '[WARNING: Max worker threads is larger than 1024 on a x86 system]' ELSE '[WARNING: Max worker threads is not the default value]' END AS [Deviation], CASE WHEN @mwthreads = 0 THEN '[INFORMATION: Configured workers = ' + CONVERT(VARCHAR(10),@mwthreads_count) + ']' ELSE '' END AS [Comment]
  5239. UNION ALL
  5240. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Min memory per query (KB)' AS [Setting], @minmemqry AS [Current Value], CASE WHEN @minmemqry = 1024 THEN '[OK]' ELSE '[WARNING: Min memory per query (KB) setting is not the default value]' END AS [Deviation], '' AS [Comment]
  5241. UNION ALL
  5242. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Network packet size (B)' AS [Setting], @netsize AS [Current Value], CASE WHEN @netsize = 4096 THEN '[OK]' ELSE '[WARNING: Network packet size is not the default value]' END AS [Deviation], '' AS [Comment]
  5243. UNION ALL
  5244. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Ole Automation Procedures' AS [Setting], @oleauto AS [Current Value], CASE WHEN @oleauto = 1 THEN '[WARNING: Ole Automation Procedures setting is not the recommended value]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5245. UNION ALL
  5246. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Optimize for ad-hoc workloads' AS [Setting], @adhoc AS [Current Value], CASE WHEN @sqlmajorver > 9 AND @adhoc = 0 THEN '[INFORMATION: Consider enabling the Optimize for ad hoc workloads setting on heavy OLTP ad-hoc workloads to conserve resources]' WHEN @sqlmajorver < 10 THEN '[NA]' ELSE '[OK]' END AS [Deviation], CASE WHEN @sqlmajorver > 9 AND @adhoc = 0 THEN '[INFORMATION: Should be ON if SQL Server 2008 or higher and OLTP workload]' ELSE '' END AS [Comment]
  5247. UNION ALL
  5248. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Priority Boost' AS [Setting], @pboost AS [Current Value], CASE WHEN @pboost = 1 THEN '[CRITICAL: Priority boost setting is not the recommended value]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5249. UNION ALL
  5250. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Query wait (s)' AS [Setting], @qrywait AS [Current Value], CASE WHEN @qrywait = -1 THEN '[OK]' ELSE '[CRITICAL: Query wait is not the default value]' END AS [Deviation], '' AS [Comment]
  5251. UNION ALL
  5252. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Recovery Interval (min)' AS [Setting], @recinterval AS [Current Value], CASE WHEN @recinterval = 0 THEN '[OK]' ELSE '[WARNING: Recovery interval is not the default value]' END AS [Deviation], '' AS [Comment]
  5253. UNION ALL
  5254. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Remote Admin Connections' AS [Setting], @remote AS [Current Value], CASE WHEN @remote = 0 AND @clustered = 1 THEN '[WARNING: Consider enabling the DAC listener to access a remote connections on a clustered configuration]' WHEN @remote = 0 AND @clustered = 0 THEN '[INFORMATION: Consider enabling remote connections access to the DAC listener on a stand-alone configuration, should local resources be exhausted]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5255. UNION ALL
  5256. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Remote query timeout' AS [Setting], @qtimeout AS [Current Value], CASE WHEN @qtimeout = 600 THEN '[OK]' ELSE '[WARNING: Remote query timeout is not the default value]' END AS [Deviation], '' AS [Comment]
  5257. UNION ALL
  5258. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'Startup Stored Procedures' AS [Setting], @ssp AS [Current Value], CASE WHEN @ssp = 1 AND (@replication IS NULL OR @replication = 0) THEN '[WARNING: Scanning for startup stored procedures setting is not the recommended value]' ELSE '[OK]' END AS [Deviation], '' AS [Comment]
  5259. UNION ALL
  5260. SELECT 'Instance_checks' AS [Category], 'System_Configurations' AS [Check], 'xp_cmdshell' AS [Setting], @cmdshell AS [Current Value], CASE WHEN @cmdshell = 1 THEN '[WARNING: xp_cmdshell setting is enabled]' ELSE '[OK]' END AS [Deviation], '' AS [Comment];
  5261. IF (SELECT COUNT([Name]) FROM master.sys.configurations WHERE [value] <> [value_in_use] AND [is_dynamic] = 0) > 0
  5262. BEGIN
  5263. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Check], '[WARNING: There are system configurations with differences between running and configured values]' AS [Deviation]
  5264. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Information], [Name] AS [Setting],
  5265. [value] AS 'Config_Value',
  5266. [value_in_use] AS 'Run_Value'
  5267. FROM master.sys.configurations (NOLOCK)
  5268. WHERE [value] <> [value_in_use] AND [is_dynamic] = 0;
  5269. END
  5270. ELSE
  5271. BEGIN
  5272. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Check], '[OK]' AS [Deviation]
  5273. END;
  5274. --------------------------------------------------------------------------------------------------------------------------------
  5275. -- IFI subsection
  5276. --------------------------------------------------------------------------------------------------------------------------------
  5277. RAISERROR (N' |-Starting IFI', 10, 1) WITH NOWAIT
  5278. DECLARE @ifi bit, @IFIStatus NVARCHAR(256)
  5279. IF ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13)
  5280. BEGIN
  5281. IF @allow_xpcmdshell = 1
  5282. BEGIN
  5283. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  5284. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5285. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  5286. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5287. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  5288. BEGIN
  5289. RAISERROR (' |-Configuration options set for IFI check', 10, 1) WITH NOWAIT
  5290. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  5291. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  5292. IF @sao = 0
  5293. BEGIN
  5294. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  5295. END
  5296. IF @xcmd = 0
  5297. BEGIN
  5298. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  5299. END
  5300. BEGIN TRY
  5301. DECLARE @xp_cmdshell_output2 TABLE ([Output] VARCHAR (8000));
  5302. SET @CMD = ('whoami /priv')
  5303. INSERT INTO @xp_cmdshell_output2
  5304. EXEC master.dbo.xp_cmdshell @CMD;
  5305. IF EXISTS (SELECT * FROM @xp_cmdshell_output2 WHERE [Output] LIKE '%SeManageVolumePrivilege%')
  5306. BEGIN
  5307. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[OK]' AS [Deviation];
  5308. SET @ifi = 1;
  5309. END
  5310. ELSE
  5311. BEGIN
  5312. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[WARNING: Instant File Initialization is disabled. This can impact data file autogrowth times]' AS [Deviation];
  5313. SET @ifi = 0
  5314. END
  5315. END TRY
  5316. BEGIN CATCH
  5317. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  5318. SELECT @ErrorMessage = 'IFI subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  5319. RAISERROR (@ErrorMessage, 16, 1);
  5320. END CATCH
  5321. IF @xcmd = 0
  5322. BEGIN
  5323. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  5324. END
  5325. IF @sao = 0
  5326. BEGIN
  5327. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  5328. END
  5329. END
  5330. ELSE
  5331. BEGIN
  5332. RAISERROR('[WARNING: Only a sysadmin can run the "Instant Initialization" check. A regular user can also run this check if a xp_cmdshell proxy account exists. Bypassing check]', 16, 1, N'xp_cmdshellproxy')
  5333. RAISERROR('[WARNING: If not sysadmin, then must be a granted EXECUTE permissions on the following extended sprocs to run checks: xp_cmdshell. Bypassing check]', 16, 1, N'extended_sprocs')
  5334. --RETURN
  5335. END
  5336. END
  5337. ELSE
  5338. BEGIN
  5339. RAISERROR(' |- [INFORMATION: "Instant Initialization" check was skipped because xp_cmdshell was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  5340. --RETURN
  5341. END
  5342. END
  5343. ELSE IF ((@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13)
  5344. BEGIN
  5345. SET @sqlcmd = N'SELECT @IFIStatusOUT = instant_file_initialization_enabled FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server%'' AND servicename NOT LIKE ''SQL Server Agent%''';
  5346. SET @params = N'@IFIStatusOUT NVARCHAR(256) OUTPUT';
  5347. EXECUTE sp_executesql @sqlcmd, @params, @IFIStatusOUT=@IFIStatus OUTPUT;
  5348. IF @IFIStatus = 'Y'
  5349. BEGIN
  5350. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[OK]' AS [Deviation];
  5351. SET @ifi = 1;
  5352. END
  5353. ELSE
  5354. BEGIN
  5355. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[WARNING: Instant File Initialization is disabled. This can impact data file autogrowth times]' AS [Deviation];
  5356. SET @ifi = 0
  5357. END
  5358. END;
  5359. --------------------------------------------------------------------------------------------------------------------------------
  5360. -- Full Text Configurations subsection
  5361. --------------------------------------------------------------------------------------------------------------------------------
  5362. RAISERROR (N' |-Starting Full Text Configurations', 10, 1) WITH NOWAIT
  5363. DECLARE @FullTextDefaultPath NVARCHAR(512), @fterr tinyint
  5364. DECLARE @fttbl TABLE ([KeyExist] int)
  5365. DECLARE @FullTextDetails TABLE (FullText_ResourceUsage tinyint,
  5366. [DefaultPath] NVARCHAR(512),
  5367. [ConnectTimeout] int,
  5368. [DataTimeout] int,
  5369. [AllowUnsignedBinaries] bit,
  5370. [LoadOSResourcesEnabled] bit,
  5371. [CatalogUpgradeOption] tinyint)
  5372. SET @fterr = 0
  5373. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  5374. BEGIN
  5375. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 1)
  5376. BEGIN
  5377. BEGIN TRY
  5378. INSERT INTO @fttbl
  5379. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup' -- check if Full-Text path exists
  5380. IF (SELECT [KeyExist] FROM @fttbl) = 1
  5381. BEGIN
  5382. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup', N'FullTextDefaultPath', @FullTextDefaultPath OUTPUT, NO_OUTPUT;
  5383. END
  5384. END TRY
  5385. BEGIN CATCH
  5386. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  5387. SELECT @ErrorMessage = 'Full Text Configurations subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  5388. RAISERROR (@ErrorMessage, 16, 1);
  5389. END CATCH
  5390. END
  5391. ELSE
  5392. BEGIN
  5393. RAISERROR('[WARNING: Missing permissions for full "Full Text Configurations" checks. Bypassing Full Text path check]', 16, 1, N'sysadmin')
  5394. --RETURN
  5395. END
  5396. INSERT INTO @FullTextDetails
  5397. SELECT FULLTEXTSERVICEPROPERTY('ResourceUsage'), ISNULL(@FullTextDefaultPath, N'') AS [Default Path],
  5398. ISNULL(FULLTEXTSERVICEPROPERTY('ConnectTimeout'),0), ISNULL(FULLTEXTSERVICEPROPERTY('DataTimeout'),0),
  5399. CASE WHEN @sqlmajorver >= 9 THEN
  5400. FULLTEXTSERVICEPROPERTY('VerifySignature') ELSE NULL
  5401. END AS [AllowUnsignedBinaries],
  5402. CASE WHEN @sqlmajorver >= 9 THEN
  5403. FULLTEXTSERVICEPROPERTY('LoadOSResources') ELSE NULL
  5404. END AS [LoadOSResourcesEnabled],
  5405. CASE WHEN @sqlmajorver >= 10 THEN
  5406. FULLTEXTSERVICEPROPERTY('UpgradeOption') ELSE NULL
  5407. END AS [CatalogUpgradeOption];
  5408. IF @sqlmajorver <= 9 AND (SELECT FullText_ResourceUsage FROM @FullTextDetails) <> 3
  5409. BEGIN
  5410. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[INFORMATION: FullText Resource usage setting is not default]' AS [Deviation],
  5411. CASE WHEN FullText_ResourceUsage < 3 THEN '[Least Aggressive Usage Level]'
  5412. WHEN FullText_ResourceUsage = 4 THEN '[More Aggressive Usage Level]'
  5413. WHEN FullText_ResourceUsage = 5 THEN '[Most Aggressive Usage Level]'
  5414. END AS [Comment]
  5415. FROM @FullTextDetails;
  5416. SET @fterr = @fterr + 1
  5417. END
  5418. IF @sqlmajorver >= 9 AND (SELECT [AllowUnsignedBinaries] FROM @FullTextDetails) = 0
  5419. BEGIN
  5420. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[WARNING: FullText Binaries verification setting is not default]' AS [Deviation],
  5421. '[Do not verify whether or not binaries are signed]' AS [Comment];
  5422. SET @fterr = @fterr + 1
  5423. END
  5424. IF @sqlmajorver >= 9 AND (SELECT [LoadOSResourcesEnabled] FROM @FullTextDetails) = 1
  5425. BEGIN
  5426. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[WARNING: FullText OS Resource utilization setting is not default]' AS [Deviation],
  5427. '[Load OS filters and word breakers]' AS [Comment];
  5428. SET @fterr = @fterr + 1
  5429. END
  5430. IF @fterr = 0
  5431. BEGIN
  5432. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[OK]' AS [Deviation],
  5433. '[All FullText settings are aligned with defaults]' AS [Comment];
  5434. END
  5435. END;
  5436. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 0
  5437. BEGIN
  5438. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], NULL AS [Deviation], '[FullText search is not installed]' AS [Comment];
  5439. END;
  5440. --------------------------------------------------------------------------------------------------------------------------------
  5441. -- Deprecated features subsection
  5442. --------------------------------------------------------------------------------------------------------------------------------
  5443. IF @ptochecks = 1
  5444. BEGIN
  5445. RAISERROR (N' |-Starting Deprecated features', 10, 1) WITH NOWAIT
  5446. IF (SELECT COUNT(instance_name) FROM sys.dm_os_performance_counters WHERE [object_name] = 'SQLServer:Deprecated Features' AND cntr_value > 0) > 0
  5447. BEGIN
  5448. SELECT 'Instance_checks' AS [Category], 'Deprecated_features' AS [Check], '[WARNING: Deprecated features are being used. These features are scheduled to be removed in a future release of SQL Server]' AS [Deviation]
  5449. SELECT 'Instance_checks' AS [Category], 'Deprecated_features' AS [Information], instance_name, cntr_value AS [Times_used_since_startup]
  5450. FROM sys.dm_os_performance_counters (NOLOCK)
  5451. WHERE [object_name] LIKE '%Deprecated Features%' AND cntr_value > 0
  5452. ORDER BY instance_name;
  5453. END
  5454. ELSE
  5455. BEGIN
  5456. SELECT 'Instance_checks' AS [Category], 'Deprecated_features' AS [Check], '[OK]' AS [Deviation]
  5457. END;
  5458. END;
  5459. --------------------------------------------------------------------------------------------------------------------------------
  5460. -- Default data collections subsection
  5461. --------------------------------------------------------------------------------------------------------------------------------
  5462. RAISERROR (N' |-Starting default data collections', 10, 1) WITH NOWAIT
  5463. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE is_default = 1 AND status = 1)
  5464. BEGIN
  5465. SELECT 'Instance_checks' AS [Category], 'Default_Trace' AS [Check], '[OK]' AS [Deviation]
  5466. END
  5467. ELSE
  5468. BEGIN
  5469. SELECT 'Instance_checks' AS [Category], 'Default_Trace' AS [Information], '[WARNING: No default trace was found or is not active]' AS [Deviation], '[Default trace provides troubleshooting assistance to database administrators by ensuring that they have the log data necessary to diagnose problems the first time they occur]' AS [Comment]
  5470. END;
  5471. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE [path] LIKE '%blackbox%.trc' AND status = 1)
  5472. BEGIN
  5473. SELECT 'Instance_checks' AS [Category], 'Blackbox_Trace' AS [Check], '[WARNING: Blackbox trace is configured and running]' AS [Deviation], '[This trace is designed to behave similarly to an airplane black box, to help you diagnose intermittent server crashes. It is quite a bit heavier than the default trace]' AS [Comment]
  5474. END
  5475. ELSE
  5476. BEGIN
  5477. SELECT 'Instance_checks' AS [Category], 'Blackbox_Trace' AS [Information], '[OK]' AS [Deviation]
  5478. END;
  5479. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE (is_default = 1 OR [path] LIKE '%blackbox%.trc') AND status = 1)
  5480. BEGIN
  5481. SELECT 'Instance_checks' AS [Category], 'Default_or_Blackbox_Trace' AS [Information], [id] As trace_id, [path], max_size, max_files, buffer_count, buffer_size, is_default, event_count, dropped_event_count, start_time, last_event_time
  5482. FROM sys.traces
  5483. WHERE (is_default = 1 OR [path] LIKE '%blackbox%.trc') AND status = 1
  5484. END;
  5485. IF @sqlmajorver > 10
  5486. BEGIN
  5487. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] = 'system_health')
  5488. BEGIN
  5489. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_SystemHealth' AS [Check], '[OK]' AS [Deviation]
  5490. END
  5491. ELSE
  5492. BEGIN
  5493. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_SystemHealth' AS [Information], '[WARNING: The system_health xEvent session is not active]' AS [Deviation], '[This session starts automatically when the SQL Server Database Engine starts, and runs without any noticeable performance effects. The session collects system data that you can use to help troubleshoot performance issues in the Database Engine]' AS [Comment]
  5494. END;
  5495. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] = 'sp_server_diagnostics session')
  5496. BEGIN
  5497. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_sp_server_diagnostics' AS [Check], '[OK]' AS [Deviation]
  5498. END
  5499. ELSE
  5500. BEGIN
  5501. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_sp_server_diagnostics' AS [Information], '[WARNING: The sp_server_diagnostics xEvent session is not active]' AS [Deviation], '[This session starts automatically when the SQL Server Database Engine starts, and runs without any noticeable performance effects. The session collects system data that you can use to help troubleshoot performance issues in the Database Engine]' AS [Comment]
  5502. END;
  5503. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] IN ('system_health', 'sp_server_diagnostics session'))
  5504. BEGIN
  5505. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_SystemHealth_sp_server_diagnostics' AS [Information], name, pending_buffers, total_regular_buffers, regular_buffer_size, total_large_buffers, large_buffer_size, total_buffer_size, buffer_policy_desc, flag_desc,
  5506. dropped_event_count, dropped_buffer_count, blocked_event_fire_time, create_time, largest_event_dropped_size
  5507. FROM sys.dm_xe_sessions
  5508. WHERE [name] IN ('system_health', 'sp_server_diagnostics session')
  5509. END;
  5510. END;
  5511. RAISERROR (N'|-Starting Database and tempDB Checks', 10, 1) WITH NOWAIT
  5512. --------------------------------------------------------------------------------------------------------------------------------
  5513. -- User objects in master DB
  5514. --------------------------------------------------------------------------------------------------------------------------------
  5515. RAISERROR (N' |-Starting User Objects in master DB', 10, 1) WITH NOWAIT
  5516. IF (SELECT COUNT(name) FROM master.sys.all_objects WHERE is_ms_shipped = 0 AND [type] IN ('AF','FN','P','IF','PC','TF','TR','T','V')) >= 1
  5517. BEGIN
  5518. SELECT 'Database_checks' AS [Category], 'User_Objects_in_master' AS [Check], '[WARNING: User objects are created in the master database]' AS [Deviation]
  5519. SELECT 'Database_checks' AS [Category], 'User_Objects_in_master' AS [Information], ss.name AS [Schema_Name], sao.name AS [Object_Name], sao.[type_desc] AS [Object_Type], sao.create_date, sao.modify_date
  5520. FROM master.sys.all_objects sao
  5521. INNER JOIN master.sys.schemas ss ON sao.[schema_id] = ss.[schema_id]
  5522. WHERE sao.is_ms_shipped = 0
  5523. AND sao.[type] IN ('AF','FN','P','IF','PC','TF','TR','T','V')
  5524. ORDER BY sao.name, sao.type_desc;
  5525. END
  5526. ELSE
  5527. BEGIN
  5528. SELECT 'Database_checks' AS [Category], 'User_Objects_in_master' AS [Check], '[OK]' AS [Deviation]
  5529. END;
  5530. --------------------------------------------------------------------------------------------------------------------------------
  5531. -- DBs with collation <> master subsection
  5532. --------------------------------------------------------------------------------------------------------------------------------
  5533. RAISERROR (N' |-Starting DBs with collation <> master', 10, 1) WITH NOWAIT
  5534. DECLARE @master_collate NVARCHAR(128), @dif_collate int
  5535. SELECT @master_collate = collation_name FROM master.sys.databases (NOLOCK) WHERE database_id = 1;
  5536. SELECT @dif_collate = COUNT(collation_name) FROM master.sys.databases (NOLOCK) WHERE collation_name <> @master_collate;
  5537. IF @dif_collate >= 1
  5538. BEGIN
  5539. SELECT 'Database_checks' AS [Category], 'Collations' AS [Check], '[WARNING: Some user databases collation differ from the master Database_Collation]' AS [Deviation]
  5540. SELECT 'Database_checks' AS [Category], 'Collations' AS [Information], name AS [Database_Name], collation_name AS [Database_Collation], @master_collate AS [Master_Collation]
  5541. FROM master.sys.databases (NOLOCK)
  5542. WHERE collation_name <> @master_collate;
  5543. END
  5544. ELSE
  5545. BEGIN
  5546. SELECT 'Database_checks' AS [Category], 'Collations' AS [Check], '[OK]' AS [Deviation]
  5547. END;
  5548. --------------------------------------------------------------------------------------------------------------------------------
  5549. -- DBs with skewed compatibility level subsection
  5550. --------------------------------------------------------------------------------------------------------------------------------
  5551. RAISERROR (N' |-Starting DBs with skewed compatibility level', 10, 1) WITH NOWAIT
  5552. DECLARE @dif_compat int
  5553. SELECT @dif_compat = COUNT([compatibility_level]) FROM master.sys.databases (NOLOCK) WHERE [compatibility_level] <> @sqlmajorver * 10;
  5554. IF @dif_compat >= 1
  5555. BEGIN
  5556. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Check], '[WARNING: Some user databases have a non-optimal compatibility level]' AS [Deviation]
  5557. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Information], name AS [Database_Name], [compatibility_level] AS [Compatibility_Level]
  5558. FROM master.sys.databases (NOLOCK)
  5559. WHERE [compatibility_level] <> @sqlmajorver * 10;
  5560. END
  5561. ELSE
  5562. BEGIN
  5563. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Check], '[OK]' AS [Deviation]
  5564. END;
  5565. --------------------------------------------------------------------------------------------------------------------------------
  5566. -- User DBs with non-default options subsection
  5567. --------------------------------------------------------------------------------------------------------------------------------
  5568. RAISERROR (N' |-Starting User DBs with non-default options', 10, 1) WITH NOWAIT
  5569. DECLARE @cnt int, @cnt_i int
  5570. DECLARE @is_auto_close_on bit, @is_auto_shrink_on bit, @page_verify_option bit
  5571. DECLARE @is_auto_create_stats_on bit, @is_auto_update_stats_on bit
  5572. DECLARE @is_db_chaining_on bit, @is_auto_create_stats_incremental_on bit--, @is_indirect_checkpoint_on bit
  5573. DECLARE @is_trustworthy_on bit, @is_parameterization_forced bit
  5574. DECLARE @dbopterrtb TABLE (id int,
  5575. name sysname,
  5576. is_auto_close_on bit,
  5577. is_auto_shrink_on bit,
  5578. page_verify_option tinyint,
  5579. page_verify_option_desc NVARCHAR(60),
  5580. is_auto_create_stats_on bit,
  5581. is_auto_update_stats_on bit,
  5582. is_db_chaining_on bit,
  5583. --is_indirect_checkpoint_on bit,
  5584. is_auto_create_stats_incremental_on bit NULL,
  5585. is_trustworthy_on bit,
  5586. is_parameterization_forced bit)
  5587. IF @sqlmajorver < 11
  5588. BEGIN
  5589. SET @sqlcmd = 'SELECT ROW_NUMBER() OVER(ORDER BY name), name, is_auto_close_on,
  5590. is_auto_shrink_on, page_verify_option, page_verify_option_desc,
  5591. is_auto_create_stats_on, is_auto_update_stats_on, is_db_chaining_on,
  5592. --0 AS is_indirect_checkpoint_on,
  5593. NULL AS is_auto_create_stats_incremental_on,
  5594. is_trustworthy_on, is_parameterization_forced
  5595. FROM master.sys.databases (NOLOCK)
  5596. WHERE database_id > 4 OR name = ''model'''
  5597. END
  5598. ELSE
  5599. BEGIN
  5600. SET @sqlcmd = 'SELECT ROW_NUMBER() OVER(ORDER BY name), name, is_auto_close_on,
  5601. is_auto_shrink_on, page_verify_option, page_verify_option_desc,
  5602. is_auto_create_stats_on, is_auto_update_stats_on,
  5603. is_db_chaining_on,
  5604. --CASE WHEN target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  5605. is_auto_create_stats_incremental_on,
  5606. is_trustworthy_on, is_parameterization_forced
  5607. FROM master.sys.databases (NOLOCK)
  5608. WHERE database_id > 4 OR name = ''model'''
  5609. END;
  5610. INSERT INTO @dbopterrtb
  5611. EXECUTE sp_executesql @sqlcmd;
  5612. SET @cnt = (SELECT COUNT(id) FROM @dbopterrtb)
  5613. SET @cnt_i = 1
  5614. SELECT @is_auto_close_on = 0, @is_auto_shrink_on = 0, @page_verify_option = 0, @is_auto_create_stats_on = 0, @is_auto_update_stats_on = 0, @is_db_chaining_on = 0, @is_trustworthy_on = 0, @is_parameterization_forced = 0, @is_auto_create_stats_incremental_on = NULL--, @is_indirect_checkpoint_on = 0
  5615. WHILE @cnt_i <> @cnt
  5616. BEGIN
  5617. SELECT @is_auto_close_on = CASE WHEN is_auto_close_on = 1 AND @is_auto_close_on = 0 THEN 1 ELSE @is_auto_close_on END,
  5618. @is_auto_shrink_on = CASE WHEN is_auto_shrink_on = 1 AND @is_auto_shrink_on = 0 THEN 1 ELSE @is_auto_shrink_on END,
  5619. @page_verify_option = CASE WHEN page_verify_option <> 2 AND @page_verify_option = 0 THEN 1 ELSE @page_verify_option END,
  5620. @is_auto_create_stats_on = CASE WHEN is_auto_create_stats_on = 0 AND @is_auto_create_stats_on = 0 THEN 1 ELSE @is_auto_create_stats_on END,
  5621. @is_auto_update_stats_on = CASE WHEN is_auto_update_stats_on = 0 AND @is_auto_update_stats_on = 0 THEN 1 ELSE @is_auto_update_stats_on END,
  5622. @is_db_chaining_on = CASE WHEN is_db_chaining_on = 1 AND @is_db_chaining_on = 0 THEN 1 ELSE @is_db_chaining_on END,
  5623. --@is_indirect_checkpoint_on = CASE WHEN is_indirect_checkpoint_on = 1 AND @is_indirect_checkpoint_on = 0 THEN 1 ELSE @is_indirect_checkpoint_on END,
  5624. @is_auto_create_stats_incremental_on = CASE WHEN is_auto_create_stats_incremental_on = 1 AND @is_auto_create_stats_incremental_on IS NULL THEN 1 ELSE @is_auto_create_stats_incremental_on END,
  5625. @is_trustworthy_on = CASE WHEN is_trustworthy_on = 1 AND @is_trustworthy_on = 0 THEN 1 ELSE @is_trustworthy_on END,
  5626. @is_parameterization_forced = CASE WHEN is_parameterization_forced = 1 AND @is_parameterization_forced = 0 THEN 1 ELSE @is_parameterization_forced END
  5627. FROM @dbopterrtb
  5628. WHERE id = @cnt_i;
  5629. SET @cnt_i = @cnt_i + 1
  5630. END
  5631. IF @is_auto_close_on = 1 OR @is_auto_shrink_on = 1 OR @page_verify_option = 1 OR @is_auto_create_stats_on = 1 OR @is_auto_update_stats_on = 1 OR @is_db_chaining_on = 1 OR @is_auto_create_stats_incremental_on = 0 --OR @is_indirect_checkpoint_on = 1
  5632. BEGIN
  5633. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Check], '[WARNING: Some user databases may have Non-optimal_Settings]' AS [Deviation]
  5634. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Information],
  5635. name AS [Database_Name],
  5636. RTRIM(
  5637. CASE WHEN is_auto_close_on = 1 THEN 'Auto_Close;' ELSE '' END +
  5638. CASE WHEN is_auto_shrink_on = 1 THEN 'Auto_Shrink;' ELSE '' END +
  5639. CASE WHEN page_verify_option <> 2 THEN 'Page_Verify;' ELSE '' END +
  5640. CASE WHEN is_auto_create_stats_on = 0 THEN 'Auto_Create_Stats;' ELSE '' END +
  5641. CASE WHEN is_auto_update_stats_on = 0 THEN 'Auto_Update_Stats;' ELSE '' END +
  5642. CASE WHEN is_db_chaining_on = 1 THEN 'DB_Chaining;' ELSE '' END +
  5643. --CASE WHEN is_indirect_checkpoint_on = 1 THEN 'Indirect_Checkpoint;' ELSE '' END +
  5644. CASE WHEN is_auto_create_stats_incremental_on = 0 THEN 'Incremental_Stats;' ELSE '' END +
  5645. CASE WHEN is_trustworthy_on = 1 THEN 'Trustworthy_bit;' ELSE '' END +
  5646. CASE WHEN is_parameterization_forced = 1 THEN 'Forced_Parameterization;' ELSE '' END
  5647. ) AS [Non-optimal_Settings],
  5648. CASE WHEN is_auto_close_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Close],
  5649. CASE WHEN is_auto_shrink_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Shrink],
  5650. page_verify_option_desc AS [Page_Verify],
  5651. CASE WHEN is_auto_create_stats_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Create_Stats],
  5652. CASE WHEN is_auto_update_stats_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Update_Stats],
  5653. CASE WHEN is_db_chaining_on = 1 THEN 'ON' ELSE 'OFF' END AS [DB_Chaining],
  5654. --CASE WHEN is_indirect_checkpoint_on = 1 THEN 'ON' ELSE 'OFF' END AS [Indirect_Checkpoint], -- Meant just as a warning that Indirect_Checkpoint is ON. Should be OFF in OLTP systems. Check for high Background Writer Pages/sec counter.
  5655. CASE WHEN is_auto_create_stats_incremental_on = 1 THEN 'ON' WHEN is_auto_create_stats_incremental_on = 1 THEN 'NA' ELSE 'OFF' END AS [Incremental_Stats],
  5656. CASE WHEN is_trustworthy_on = 1 THEN 'ON' ELSE 'OFF' END AS [Trustworthy_bit],
  5657. CASE WHEN is_parameterization_forced = 1 THEN 'ON' ELSE 'OFF' END AS [Forced_Parameterization]
  5658. FROM @dbopterrtb
  5659. WHERE is_auto_close_on = 1 OR is_auto_shrink_on = 1 OR page_verify_option <> 2 OR is_db_chaining_on = 1 OR (is_auto_create_stats_on = 0 AND @sqlmajorver >= 12)
  5660. OR is_auto_update_stats_on = 0 OR is_trustworthy_on = 1 OR is_parameterization_forced = 1 OR is_auto_create_stats_incremental_on = 0--OR is_indirect_checkpoint_on = 1;
  5661. END
  5662. ELSE
  5663. BEGIN
  5664. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Check], '[OK]' AS [Deviation]
  5665. END;
  5666. IF (SELECT COUNT(*) FROM master.sys.databases (NOLOCK) WHERE is_auto_update_stats_on = 0 AND is_auto_update_stats_async_on = 1) > 0
  5667. BEGIN
  5668. SELECT 'Database_checks' AS [Category], 'Database_Options_Disabled_Async_AutoUpdate' AS [Check], '[WARNING: Some databases have Auto_Update_Statistics_Asynchronously ENABLED while Auto_Update_Statistics is DISABLED. If asynch auto statistics update is intended, also enable Auto_Update_Statistics]' AS [Deviation]
  5669. SELECT 'Database_checks' AS [Category], 'Database_Options_Disabled_Async_AutoUpdate' AS [Check], [name] FROM master.sys.databases (NOLOCK) WHERE is_auto_update_stats_on = 0 AND is_auto_update_stats_async_on = 1
  5670. END
  5671. ELSE
  5672. BEGIN
  5673. SELECT 'Database_checks' AS [Category], 'Database_Options_Disabled_Async_AutoUpdate' AS [Check], '[OK]' AS [Deviation]
  5674. END;
  5675. --------------------------------------------------------------------------------------------------------------------------------
  5676. -- DBs with Sparse files subsection
  5677. --------------------------------------------------------------------------------------------------------------------------------
  5678. RAISERROR (N' |-Starting DBs with Sparse files', 10, 1) WITH NOWAIT
  5679. -- http://blogs.msdn.com/b/psssql/archive/2011/02/21/did-your-backup-program-utility-leave-your-sql-server-running-in-an-squirrely-scenario-version-2.aspx
  5680. -- http://blogs.msdn.com/b/jorgepc/archive/2010/11/25/what-are-sparse-files-and-why-should-i-care-as-sql-server-dba.aspx
  5681. IF (SELECT COUNT(sd.database_id) FROM sys.databases sd INNER JOIN sys.master_files smf ON sd.database_id = smf.database_id WHERE sd.source_database_id IS NULL AND smf.is_sparse = 1) > 0
  5682. BEGIN
  5683. SELECT 'Database_checks' AS [Category], 'DB_nonSnap_Sparse' AS [Check], '[WARNING: Sparse files were detected that do not belong to a Database Snapshot. You might also notice unexplained performance degradation when query data from these files]' AS [Deviation]
  5684. SELECT 'Database_checks' AS [Category], 'DB_nonSnap_Sparse' AS [Information], DB_NAME(sd.database_id) AS database_name, smf.name, smf.physical_name
  5685. FROM sys.databases sd
  5686. INNER JOIN sys.master_files smf ON sd.database_id = smf.database_id
  5687. WHERE sd.source_database_id IS NULL AND smf.is_sparse = 1
  5688. END
  5689. ELSE
  5690. BEGIN
  5691. SELECT 'Database_checks' AS [Category], 'DB_nonSnap_Sparse' AS [Check], '[OK]' AS [Deviation]
  5692. END;
  5693. --------------------------------------------------------------------------------------------------------------------------------
  5694. -- DBs Autogrow in percentage subsection
  5695. --------------------------------------------------------------------------------------------------------------------------------
  5696. RAISERROR (N' |-Starting DBs Autogrow in percentage', 10, 1) WITH NOWAIT
  5697. IF (SELECT COUNT(is_percent_growth) FROM sys.master_files WHERE is_percent_growth = 1) > 0
  5698. BEGIN
  5699. SELECT 'Database_checks' AS [Category], 'Percent_Autogrows' AS [Check], '[WARNING: Some database files have a growth ratio set in percentage. Over time, this could lead to uncontrolled disk space allocation and extended time to perform these growths]' AS [Deviation]
  5700. SELECT 'Database_checks' AS [Category], 'Percent_Autogrows' AS [Information], database_id,
  5701. DB_NAME(database_id) AS [Database_Name],
  5702. mf.name AS [Logical_Name],
  5703. mf.size*8 AS [Current_Size_KB],
  5704. mf.type_desc AS [File_Type],
  5705. mf.[state_desc] AS [File_State],
  5706. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  5707. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount_KB],
  5708. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((mf.size*8)*CONVERT(bigint, mf.growth))/100
  5709. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  5710. ELSE 0 END AS [Next_Growth_KB],
  5711. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  5712. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  5713. ELSE '' END AS [Comments],
  5714. mf.is_read_only
  5715. FROM sys.master_files mf (NOLOCK)
  5716. WHERE is_percent_growth = 1
  5717. GROUP BY database_id, mf.name, mf.size, is_percent_growth, mf.growth, mf.type_desc, mf.[type], mf.[state_desc], mf.is_read_only
  5718. ORDER BY DB_NAME(mf.database_id), mf.name
  5719. END
  5720. ELSE
  5721. BEGIN
  5722. SELECT 'Database_checks' AS [Category], 'Percent_Autogrows' AS [Check], '[OK]' AS [Deviation]
  5723. END;
  5724. --------------------------------------------------------------------------------------------------------------------------------
  5725. -- DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled) subsection
  5726. --------------------------------------------------------------------------------------------------------------------------------
  5727. RAISERROR (N' |-Starting DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled)', 10, 1) WITH NOWAIT
  5728. IF (SELECT COUNT(growth) FROM sys.master_files (NOLOCK)
  5729. WHERE [type] >= CASE WHEN @ifi = 1 THEN 1 ELSE 0 END
  5730. AND [type] < 2
  5731. AND ((is_percent_growth = 1 AND ((CONVERT(bigint,size)*8)*growth)/100 > 1048576)
  5732. OR (is_percent_growth = 0 AND growth*8 > 1048576))) > 0
  5733. BEGIN
  5734. SELECT 'Database_checks' AS [Category], 'Large_Autogrows' AS [Check], '[WARNING: Some database files have set growth over 1GB. This could lead to extended growth times, slowing down your system]' AS [Deviation]
  5735. SELECT 'Database_checks' AS [Category], 'Large_Autogrows' AS [Information], database_id,
  5736. DB_NAME(database_id) AS [Database_Name],
  5737. mf.name AS [Logical_Name],
  5738. mf.size*8 AS [Current_Size_KB],
  5739. mf.[type_desc] AS [File_Type],
  5740. mf.[state_desc] AS [File_State],
  5741. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  5742. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount],
  5743. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((CONVERT(bigint,mf.size)*8)*mf.growth)/100
  5744. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  5745. ELSE 0 END AS [Next_Growth_KB],
  5746. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  5747. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  5748. ELSE '' END AS [Comments],
  5749. mf.is_read_only
  5750. FROM sys.master_files mf (NOLOCK)
  5751. WHERE mf.[type] >= CASE WHEN @ifi = 1 THEN 1 ELSE 0 END
  5752. AND mf.[type] < 2
  5753. AND ((is_percent_growth = 1 AND ((CONVERT(bigint,mf.size)*8)*mf.growth)/100 > 1048576)
  5754. OR (is_percent_growth = 0 AND mf.growth*8 > 1048576))
  5755. GROUP BY database_id, mf.name, mf.size, is_percent_growth, mf.growth, mf.[type_desc], mf.[type], mf.[state_desc], mf.is_read_only
  5756. ORDER BY DB_NAME(mf.database_id), mf.name
  5757. END
  5758. ELSE
  5759. BEGIN
  5760. SELECT 'Database_checks' AS [Category], 'Large_Autogrows' AS [Check], '[OK]' AS [Deviation]
  5761. END;
  5762. --------------------------------------------------------------------------------------------------------------------------------
  5763. -- VLF subsection
  5764. --------------------------------------------------------------------------------------------------------------------------------
  5765. RAISERROR (N' |-Starting VLF', 10, 1) WITH NOWAIT
  5766. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1
  5767. BEGIN
  5768. DECLARE /*@dbid int,*/ @query VARCHAR(1000)/*, @dbname VARCHAR(1000)*/, @count int, @count_used int, @logsize DECIMAL(20,1), @usedlogsize DECIMAL(20,1), @avgvlfsize DECIMAL(20,1)
  5769. DECLARE @potsize DECIMAL(20,1), @n_iter int, @n_iter_final int, @initgrow DECIMAL(20,1), @n_init_iter int
  5770. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  5771. DROP TABLE #log_info1;
  5772. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  5773. CREATE TABLE #log_info1 (dbname VARCHAR(100),
  5774. Current_log_size_MB DECIMAL(20,1),
  5775. Used_Log_size_MB DECIMAL(20,1),
  5776. Potential_log_size_MB DECIMAL(20,1),
  5777. Current_VLFs int,
  5778. Used_VLFs int,
  5779. Avg_VLF_size_KB DECIMAL(20,1),
  5780. Potential_VLFs int,
  5781. Growth_iterations int,
  5782. Log_Initial_size_MB DECIMAL(20,1),
  5783. File_autogrow_MB DECIMAL(20,1))
  5784. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  5785. DROP TABLE #log_info2;
  5786. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  5787. CREATE TABLE #log_info2 (dbname VARCHAR(100),
  5788. Current_VLFs int,
  5789. VLF_size_KB DECIMAL(20,1),
  5790. growth_iteration int)
  5791. UPDATE #tmpdbs0
  5792. SET isdone = 0;
  5793. UPDATE #tmpdbs0
  5794. SET isdone = 1
  5795. WHERE [state] <> 0;
  5796. UPDATE #tmpdbs0
  5797. SET isdone = 1
  5798. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  5799. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  5800. BEGIN
  5801. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  5802. BEGIN
  5803. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  5804. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info3'))
  5805. DROP TABLE #log_info3;
  5806. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info3'))
  5807. CREATE TABLE #log_info3 (recoveryunitid int NULL,
  5808. fileid tinyint,
  5809. file_size bigint,
  5810. start_offset bigint,
  5811. FSeqNo int,
  5812. [status] tinyint,
  5813. parity tinyint,
  5814. create_lsn numeric(25,0))
  5815. SET @query = 'DBCC LOGINFO (' + '''' + @dbname + ''') WITH NO_INFOMSGS'
  5816. IF @sqlmajorver < 11
  5817. BEGIN
  5818. INSERT INTO #log_info3 (fileid, file_size, start_offset, FSeqNo, [status], parity, create_lsn)
  5819. EXEC (@query)
  5820. END
  5821. ELSE
  5822. BEGIN
  5823. INSERT INTO #log_info3 (recoveryunitid, fileid, file_size, start_offset, FSeqNo, [status], parity, create_lsn)
  5824. EXEC (@query)
  5825. END
  5826. SET @count = @@ROWCOUNT
  5827. SET @count_used = (SELECT COUNT(fileid) FROM #log_info3 l WHERE l.[status] = 2)
  5828. SET @logsize = (SELECT (MIN(l.start_offset) + SUM(l.file_size))/1048576.00 FROM #log_info3 l)
  5829. SET @usedlogsize = (SELECT (MIN(l.start_offset) + SUM(CASE WHEN l.status <> 0 THEN l.file_size ELSE 0 END))/1048576.00 FROM #log_info3 l)
  5830. SET @avgvlfsize = (SELECT AVG(l.file_size)/1024.00 FROM #log_info3 l)
  5831. INSERT INTO #log_info2
  5832. SELECT @dbname, COUNT(create_lsn), MIN(l.file_size)/1024.00,
  5833. ROW_NUMBER() OVER(ORDER BY l.create_lsn) FROM #log_info3 l
  5834. GROUP BY l.create_lsn
  5835. ORDER BY l.create_lsn
  5836. DROP TABLE #log_info3;
  5837. -- Grow logs in MB instead of GB because of known issue prior to SQL 2012.
  5838. -- More detail here: http://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx
  5839. -- and http://connect.microsoft.com/SQLServer/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately
  5840. -- or https://connect.microsoft.com/SQLServer/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb
  5841. IF @sqlmajorver >= 11
  5842. BEGIN
  5843. SET @n_iter = (SELECT CASE WHEN @logsize <= 64 THEN 1
  5844. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)
  5845. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)
  5846. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)
  5847. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)
  5848. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4096, 0)
  5849. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8192, 0)
  5850. END)
  5851. SET @potsize = (SELECT CASE WHEN @logsize <= 64 THEN 1*64
  5852. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)*256
  5853. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)*512
  5854. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)*1024
  5855. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)*2048
  5856. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4096, 0)*4096
  5857. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8192, 0)*8192
  5858. END)
  5859. END
  5860. ELSE
  5861. BEGIN
  5862. SET @n_iter = (SELECT CASE WHEN @logsize <= 64 THEN 1
  5863. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)
  5864. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)
  5865. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)
  5866. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)
  5867. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4000, 0)
  5868. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8000, 0)
  5869. END)
  5870. SET @potsize = (SELECT CASE WHEN @logsize <= 64 THEN 1*64
  5871. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)*256
  5872. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)*512
  5873. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)*1024
  5874. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)*2048
  5875. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4000, 0)*4000
  5876. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8000, 0)*8000
  5877. END)
  5878. END
  5879. -- If the proposed log size is smaller than current log, and also smaller than 4GB,
  5880. -- and there is less than 512MB of diff between the current size and proposed size, add 1 grow.
  5881. SET @n_iter_final = @n_iter
  5882. IF @logsize > @potsize AND @potsize <= 4096 AND ABS(@logsize - @potsize) < 512
  5883. BEGIN
  5884. SET @n_iter_final = @n_iter + 1
  5885. END
  5886. -- If the proposed log size is larger than current log, and also larger than 50GB,
  5887. -- and there is less than 1GB of diff between the current size and proposed size, take 1 grow.
  5888. ELSE IF @logsize < @potsize AND @potsize <= 51200 AND ABS(@logsize - @potsize) > 1024
  5889. BEGIN
  5890. SET @n_iter_final = @n_iter - 1
  5891. END
  5892. IF @potsize = 0
  5893. BEGIN
  5894. SET @potsize = 64
  5895. END
  5896. IF @n_iter = 0
  5897. BEGIN
  5898. SET @n_iter = 1
  5899. END
  5900. SET @potsize = (SELECT CASE WHEN @n_iter < @n_iter_final THEN @potsize + (@potsize/@n_iter)
  5901. WHEN @n_iter > @n_iter_final THEN @potsize - (@potsize/@n_iter)
  5902. ELSE @potsize END)
  5903. SET @n_init_iter = @n_iter_final
  5904. IF @potsize >= 8192
  5905. BEGIN
  5906. SET @initgrow = @potsize/@n_iter_final
  5907. END
  5908. IF @potsize >= 64 AND @potsize <= 512
  5909. BEGIN
  5910. SET @n_init_iter = 1
  5911. SET @initgrow = 512
  5912. END
  5913. IF @potsize > 512 AND @potsize <= 1024
  5914. BEGIN
  5915. SET @n_init_iter = 1
  5916. SET @initgrow = 1023
  5917. END
  5918. IF @potsize > 1024 AND @potsize < 8192
  5919. BEGIN
  5920. SET @n_init_iter = 1
  5921. SET @initgrow = @potsize
  5922. END
  5923. INSERT INTO #log_info1
  5924. VALUES(@dbname, @logsize, @usedlogsize, @potsize, @count, @count_used, @avgvlfsize,
  5925. CASE WHEN @potsize <= 64 THEN (@potsize/(@potsize/@n_init_iter))*4
  5926. WHEN @potsize > 64 AND @potsize < 1024 THEN (@potsize/(@potsize/@n_init_iter))*8
  5927. WHEN @potsize >= 1024 THEN (@potsize/(@potsize/@n_init_iter))*16
  5928. END,
  5929. @n_init_iter, @initgrow,
  5930. CASE WHEN (@potsize/@n_iter_final) <= 1024 THEN (@potsize/@n_iter_final) ELSE 1024 END
  5931. );
  5932. UPDATE #tmpdbs0
  5933. SET isdone = 1
  5934. WHERE [dbid] = @dbid
  5935. END
  5936. END;
  5937. IF (SELECT COUNT(dbname) FROM #log_info1 WHERE Current_VLFs >= 50) > 0
  5938. BEGIN
  5939. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Check], '[WARNING: Some user databases have many VLFs. Please review these]' AS [Deviation]
  5940. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Information], dbname AS [Database_Name], Current_log_size_MB, Used_Log_size_MB,
  5941. Potential_log_size_MB, Current_VLFs, Used_VLFs, Potential_VLFs, Growth_iterations, Log_Initial_size_MB, File_autogrow_MB
  5942. FROM #log_info1
  5943. WHERE Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5944. ORDER BY dbname;
  5945. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files_per_growth' AS [Information], #log_info2.dbname AS [Database_Name], #log_info2.Current_VLFs AS VLFs_remain_per_spawn, VLF_size_KB, growth_iteration
  5946. FROM #log_info2
  5947. INNER JOIN #log_info1 ON #log_info2.dbname = #log_info1.dbname
  5948. WHERE #log_info1.Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5949. ORDER BY #log_info2.dbname, growth_iteration
  5950. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files_agg_per_size' AS [Information], #log_info2.dbname AS [Database_Name], SUM(#log_info2.Current_VLFs) AS VLFs_per_size, VLF_size_KB
  5951. FROM #log_info2
  5952. INNER JOIN #log_info1 ON #log_info2.dbname = #log_info1.dbname
  5953. WHERE #log_info1.Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5954. GROUP BY #log_info2.dbname, VLF_size_KB
  5955. ORDER BY #log_info2.dbname, VLF_size_KB DESC
  5956. END
  5957. ELSE
  5958. BEGIN
  5959. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Check], '[OK]' AS [Deviation]
  5960. /*
  5961. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Information], dbname AS [Database_Name], Current_log_size_MB, Used_Log_size_MB, Current_VLFs, Used_VLFs
  5962. FROM #log_info1
  5963. ORDER BY dbname;
  5964. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files_per_growth' AS [Information], dbname AS [Database_Name], Current_VLFs AS VLFs_remain_per_spawn, VLF_size_KB, growth_iteration
  5965. FROM #log_info2
  5966. ORDER BY dbname, growth_iteration
  5967. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files_agg_per_size' AS [Information], dbname AS [Database_Name], SUM(Current_VLFs) AS VLFs_per_size, VLF_size_KB
  5968. FROM #log_info2
  5969. GROUP BY dbname, VLF_size_KB
  5970. ORDER BY dbname, VLF_size_KB DESC
  5971. */
  5972. END
  5973. END
  5974. ELSE
  5975. BEGIN
  5976. RAISERROR('[WARNING: Only a sysadmin can run the "VLF" check. Bypassing check]', 16, 1, N'sysadmin')
  5977. --RETURN
  5978. END;
  5979. --------------------------------------------------------------------------------------------------------------------------------
  5980. -- Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware) subsection
  5981. --------------------------------------------------------------------------------------------------------------------------------
  5982. RAISERROR (N' |-Starting Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware)', 10, 1) WITH NOWAIT
  5983. IF @allow_xpcmdshell = 1
  5984. BEGIN
  5985. DECLARE /*@dbid int,*/ @ctr2 int, @ctr3 int, @ctr4 int, @pserr bit
  5986. SET @pserr = 0
  5987. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  5988. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5989. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  5990. AND (SELECT COUNT(l.name)
  5991. FROM sys.server_permissions p (NOLOCK) INNER JOIN sys.server_principals l (NOLOCK)
  5992. ON p.grantee_principal_id = l.principal_id
  5993. AND p.class = 100 -- Server
  5994. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  5995. AND l.is_disabled = 0
  5996. AND p.permission_name = 'ALTER SETTINGS'
  5997. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  5998. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5999. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  6000. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  6001. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  6002. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  6003. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  6004. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  6005. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  6006. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  6007. BEGIN
  6008. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild <= 2500)
  6009. BEGIN
  6010. DECLARE @pstbl TABLE ([KeyExist] int)
  6011. BEGIN TRY
  6012. INSERT INTO @pstbl
  6013. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\PowerShell\1' -- check if Powershell is installed
  6014. END TRY
  6015. BEGIN CATCH
  6016. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  6017. SELECT @ErrorMessage = 'Data files and Logs in same volume (Mountpoint aware) subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  6018. RAISERROR (@ErrorMessage, 16, 1);
  6019. END CATCH
  6020. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  6021. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  6022. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  6023. RAISERROR (' |-Configuration options set for Data and Log location check', 10, 1) WITH NOWAIT
  6024. IF @sao = 0
  6025. BEGIN
  6026. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  6027. END
  6028. IF @xcmd = 0
  6029. BEGIN
  6030. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  6031. END
  6032. IF @ole = 0
  6033. BEGIN
  6034. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  6035. END
  6036. IF (SELECT [KeyExist] FROM @pstbl) = 1
  6037. BEGIN
  6038. DECLARE @ctr int
  6039. DECLARE @output_hw_tot TABLE ([PS_OUTPUT] NVARCHAR(2048));
  6040. DECLARE @output_hw_format TABLE ([volid] smallint IDENTITY(1,1), [HD_Volume] NVARCHAR(2048) NULL)
  6041. IF @custompath IS NULL
  6042. BEGIN
  6043. IF @sqlmajorver < 11
  6044. BEGIN
  6045. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  6046. SET @path = @path + '\LOG'
  6047. END
  6048. ELSE
  6049. BEGIN
  6050. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  6051. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  6052. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  6053. END
  6054. -- Create COM object with FSO
  6055. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  6056. IF @OLEResult <> 0
  6057. BEGIN
  6058. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  6059. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  6060. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6061. END
  6062. ELSE
  6063. BEGIN
  6064. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  6065. IF @OLEResult <> 0
  6066. BEGIN
  6067. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  6068. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  6069. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6070. END
  6071. ELSE
  6072. BEGIN
  6073. IF @existout <> 1
  6074. BEGIN
  6075. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  6076. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  6077. END
  6078. END
  6079. EXEC @OLEResult = sp_OADestroy @FSO
  6080. END
  6081. END
  6082. ELSE
  6083. BEGIN
  6084. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  6085. END
  6086. SET @FileName = @path + '\checkbp_' + RTRIM(@server) + '.ps1'
  6087. EXEC master.dbo.xp_fileexist @FileName, @existout out
  6088. IF @existout = 0
  6089. BEGIN
  6090. -- Scan for local disks
  6091. SET @Text1 = '[string] $serverName = ''localhost''
  6092. $vols = Get-WmiObject -computername $serverName -query "select Name from Win32_Volume where Capacity <> NULL and DriveType = 3"
  6093. foreach($vol in $vols)
  6094. {
  6095. [string] $drive = "{0}" -f $vol.name
  6096. Write-Output $drive
  6097. }'
  6098. -- Create COM object with FSO
  6099. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  6100. IF @OLEResult <> 0
  6101. BEGIN
  6102. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6103. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  6104. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6105. END
  6106. --Open file
  6107. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  6108. IF @OLEResult <> 0
  6109. BEGIN
  6110. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6111. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  6112. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6113. END
  6114. ELSE
  6115. BEGIN
  6116. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  6117. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6118. END
  6119. --Write Text1
  6120. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  6121. IF @OLEResult <> 0
  6122. BEGIN
  6123. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6124. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  6125. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6126. END
  6127. EXEC @OLEResult = sp_OADestroy @FileID
  6128. EXEC @OLEResult = sp_OADestroy @FS
  6129. END;
  6130. ELSE
  6131. BEGIN
  6132. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  6133. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6134. END
  6135. IF @psver = 1
  6136. BEGIN
  6137. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  6138. END
  6139. ELSE
  6140. BEGIN
  6141. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  6142. END;
  6143. INSERT INTO @output_hw_tot
  6144. EXEC master.dbo.xp_cmdshell @CMD
  6145. SET @CMD = 'del /Q "' + @FileName + '"'
  6146. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  6147. IF (SELECT COUNT([PS_OUTPUT])
  6148. FROM @output_hw_tot WHERE [PS_OUTPUT] LIKE '%cannot be loaded because%'
  6149. OR [PS_OUTPUT] LIKE '%scripts is disabled%'
  6150. OR [PS_OUTPUT] LIKE '%scripts est désactivée%') = 0
  6151. BEGIN
  6152. INSERT INTO @output_hw_format ([HD_Volume])
  6153. SELECT RTRIM([PS_OUTPUT])
  6154. FROM @output_hw_tot
  6155. WHERE [PS_OUTPUT] IS NOT NULL
  6156. END
  6157. ELSE
  6158. BEGIN
  6159. SET @pserr = 1
  6160. RAISERROR ('[WARNING: Powershell script cannot be loaded because the execution of scripts is disabled on this system.
  6161. To change the execution policy, type the following command in Powershell console: Set-ExecutionPolicy RemoteSigned
  6162. The Set-ExecutionPolicy cmdlet enables you to determine which Windows PowerShell scripts (if any) will be allowed to run on your computer.
  6163. Windows PowerShell has four different execution policies:
  6164. Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  6165. AllSigned - Only scripts signed by a trusted publisher can be run.
  6166. RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  6167. |- REQUIRED by BP Check
  6168. Unrestricted - No restrictions; all Windows PowerShell scripts can be run.]
  6169. ',16,1);
  6170. END
  6171. SET @CMD2 = 'del ' + @FileName
  6172. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  6173. END
  6174. ELSE
  6175. BEGIN
  6176. SET @pserr = 1
  6177. RAISERROR ('[WARNING: Powershell is not present. Bypassing Data files and Logs in same volume check]',16,1);
  6178. END
  6179. IF @xcmd = 0
  6180. BEGIN
  6181. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  6182. END
  6183. IF @ole = 0
  6184. BEGIN
  6185. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  6186. END
  6187. IF @sao = 0
  6188. BEGIN
  6189. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  6190. END
  6191. END
  6192. ELSE
  6193. BEGIN
  6194. INSERT INTO @output_hw_format ([HD_Volume])
  6195. EXEC ('SELECT DISTINCT(volume_mount_point) FROM sys.master_files mf CROSS APPLY sys.dm_os_volume_stats (database_id, [file_id]) WHERE mf.[file_id] < 65537')
  6196. END;
  6197. IF @pserr = 0
  6198. BEGIN
  6199. -- select mountpoints only
  6200. DECLARE @intertbl TABLE (physical_name nvarchar(260))
  6201. INSERT INTO @intertbl
  6202. SELECT physical_name
  6203. FROM sys.master_files t1 (NOLOCK)
  6204. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6205. WHERE ([database_id] > 4 OR [database_id] = 2)
  6206. AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3
  6207. -- select database files in mountpoints
  6208. DECLARE @filetbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6209. INSERT INTO @filetbl
  6210. SELECT database_id, type, file_id, physical_name, volid
  6211. FROM sys.master_files t1 (NOLOCK)
  6212. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6213. WHERE ([database_id] > 4 OR [database_id] = 2) AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3
  6214. UNION ALL
  6215. -- select database files not in mountpoints
  6216. SELECT database_id, type, file_id, physical_name, volid
  6217. FROM sys.master_files t1 (NOLOCK)
  6218. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6219. WHERE ([database_id] > 4 OR [database_id] = 2) AND [database_id] <> 32767 AND physical_name NOT IN (SELECT physical_name FROM @intertbl)
  6220. SELECT @ctr = COUNT(DISTINCT(t1.[database_id])) FROM @filetbl t1
  6221. INNER JOIN @filetbl t2 ON t1.database_id = t2.database_id
  6222. AND t1.[type] <> t2.[type]
  6223. AND ((t1.[type] = 1 AND t2.[type] <> 1) OR (t2.[type] = 1 AND t1.[type] <> 1))
  6224. AND t1.volid = t2.volid;
  6225. IF @ctr > 0
  6226. BEGIN
  6227. SELECT 'Database_checks' AS [Category], 'Data_and_Log_locations' AS [Check], '[WARNING: Some user databases have Data and Log files in the same physical volume]' AS [Deviation]
  6228. SELECT DISTINCT 'Database_checks' AS [Category], 'Data_and_Log_locations' AS [Information], DB_NAME(mf.[database_id]) AS [Database_Name], type_desc AS [Type], mf.physical_name
  6229. FROM sys.master_files mf (NOLOCK) INNER JOIN @filetbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6230. INNER JOIN @filetbl t2 ON t1.database_id = t2.database_id
  6231. AND t1.[type] <> t2.[type]
  6232. AND ((t1.[type] = 1 AND t2.[type] <> 1) OR (t2.[type] = 1 AND t1.[type] <> 1))
  6233. AND t1.volid = t2.volid
  6234. ORDER BY mf.physical_name OPTION (RECOMPILE);
  6235. END
  6236. ELSE
  6237. BEGIN
  6238. SELECT 'Database_checks' AS [Category], 'Data_and_Log_locations' AS [Check], '[OK]' AS [Deviation]
  6239. END;
  6240. -- select backup mountpoints only
  6241. DECLARE @interbcktbl TABLE (physical_device_name nvarchar(260))
  6242. INSERT INTO @interbcktbl
  6243. SELECT physical_device_name
  6244. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6245. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6246. WHERE LEN(t2.HD_Volume) > 3
  6247. -- select backups in mountpoints only
  6248. DECLARE @bcktbl TABLE (physical_device_name nvarchar(260), HD_Volume nvarchar(260))
  6249. INSERT INTO @bcktbl
  6250. SELECT physical_device_name, RTRIM(t2.HD_Volume)
  6251. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6252. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6253. WHERE LEN(t2.HD_Volume) > 3
  6254. -- select backups not in mountpoints
  6255. UNION ALL
  6256. SELECT physical_device_name, RTRIM(t2.HD_Volume)
  6257. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6258. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6259. WHERE physical_device_name NOT IN (SELECT physical_device_name FROM @interbcktbl);
  6260. SELECT @ctr4 = COUNT(DISTINCT(physical_device_name)) FROM @bcktbl;
  6261. IF @ctr4 > 0
  6262. BEGIN
  6263. SELECT 'Database_checks' AS [Category], 'Backup_and_Database_locations' AS [Check], '[WARNING: Some backups and database files are in the same physical volume]' AS [Deviation]
  6264. SELECT DISTINCT 'Database_checks' AS [Category], 'Backup_and_Database_locations' AS [Information], physical_device_name AS [Backup_Location], HD_Volume AS [Volume_with_DB_Files]
  6265. FROM @bcktbl
  6266. OPTION (RECOMPILE);
  6267. END
  6268. ELSE
  6269. BEGIN
  6270. SELECT 'Database_checks' AS [Category], 'Backup_and_Database_locations' AS [Check], '[OK]' AS [Deviation]
  6271. END;
  6272. -- select tempDB mountpoints only
  6273. DECLARE @intertbl2 TABLE (physical_name nvarchar(260))
  6274. INSERT INTO @intertbl2
  6275. SELECT physical_name
  6276. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2
  6277. ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6278. WHERE [database_id] = 2 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6279. -- select user DBs mountpoints only
  6280. DECLARE @intertbl3 TABLE (physical_name nvarchar(260))
  6281. INSERT INTO @intertbl3
  6282. SELECT physical_name
  6283. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2
  6284. ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6285. WHERE [database_id] > 4 AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6286. -- select tempDB files in mountpoints
  6287. DECLARE @tempDBtbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6288. INSERT INTO @tempDBtbl
  6289. SELECT database_id, type, file_id, physical_name, volid
  6290. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6291. WHERE [database_id] = 2 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6292. UNION ALL
  6293. SELECT database_id, type, file_id, physical_name, volid
  6294. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6295. WHERE [database_id] = 2 AND [type] = 0 AND physical_name NOT IN (SELECT physical_name FROM @intertbl2)
  6296. -- select user DBs files in mountpoints
  6297. DECLARE @otherstbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6298. INSERT INTO @otherstbl
  6299. SELECT database_id, type, file_id, physical_name, volid
  6300. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6301. WHERE [database_id] > 4 AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6302. UNION ALL
  6303. SELECT database_id, type, file_id, physical_name, volid
  6304. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6305. WHERE [database_id] > 4 AND [database_id] <> 32767 AND [type] = 0 AND physical_name NOT IN (SELECT physical_name FROM @intertbl3)
  6306. SELECT @ctr2 = COUNT(*) FROM @tempDBtbl WHERE LEFT(physical_name, 1) = 'C'
  6307. SELECT @ctr3 = COUNT(DISTINCT(t1.[database_id])) FROM @otherstbl t1 INNER JOIN @tempDBtbl t2 ON t1.volid = t2.volid;
  6308. IF @ctr3 > 0
  6309. BEGIN
  6310. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: tempDB is on the same physical volume as user databases]' AS [Deviation];
  6311. END
  6312. ELSE IF @ctr2 > 0
  6313. BEGIN
  6314. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: tempDB is on C: drive]' AS [Deviation]
  6315. END
  6316. ELSE
  6317. BEGIN
  6318. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[OK]' AS [Deviation]
  6319. END;
  6320. IF @ctr2 > 0 OR @ctr3 > 0
  6321. BEGIN
  6322. SELECT DISTINCT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Information], DB_NAME(mf.[database_id]) AS [Database_Name], type_desc AS [Type], mf.physical_name
  6323. FROM sys.master_files mf (NOLOCK) INNER JOIN @otherstbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6324. INNER JOIN @tempDBtbl t2 ON t1.volid = t2.volid
  6325. UNION ALL
  6326. SELECT DISTINCT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Information], DB_NAME(mf.[database_id]) AS [Database_Name], type_desc AS [Type], mf.physical_name
  6327. FROM sys.master_files mf (NOLOCK) INNER JOIN @tempDBtbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6328. ORDER BY DB_NAME(mf.[database_id]) OPTION (RECOMPILE);
  6329. END
  6330. END
  6331. ELSE
  6332. BEGIN
  6333. SELECT 'Database_checks' AS [Category], 'Data_and_Log_locations' AS [Check], '[WARNING: Could not gather information on file locations]' AS [Deviation]
  6334. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: Could not gather information on file locations]' AS [Deviation]
  6335. END
  6336. END
  6337. ELSE
  6338. BEGIN
  6339. RAISERROR('[WARNING: Only a sysadmin can run the "Data files and Logs / tempDB and user Databases in same volume" checks. A regular user can also run this check if a xp_cmdshell proxy account exists. Bypassing check]', 16, 1, N'xp_cmdshellproxy')
  6340. RAISERROR('[WARNING: If not sysadmin, then must be a granted EXECUTE permissions on the following extended sprocs to run checks: sp_OACreate, sp_OADestroy, sp_OAGetErrorInfo, xp_cmdshell, xp_instance_regread, xp_regread, xp_fileexist and xp_regenumvalues. Bypassing check]', 16, 1, N'extended_sprocs')
  6341. --RETURN
  6342. END
  6343. END
  6344. ELSE
  6345. BEGIN
  6346. RAISERROR(' |- [INFORMATION: "Data files and Logs / tempDB and user Databases in same volume" check was skipped because xp_cmdshell was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  6347. --RETURN
  6348. END;
  6349. --------------------------------------------------------------------------------------------------------------------------------
  6350. -- tempDB data file configurations subsection
  6351. --------------------------------------------------------------------------------------------------------------------------------
  6352. RAISERROR (N' |-Starting tempDB data file configurations', 10, 1) WITH NOWAIT
  6353. DECLARE @tdb_files int, @online_count int, @filesizes smallint
  6354. SELECT @tdb_files = COUNT(physical_name) FROM sys.master_files (NOLOCK) WHERE database_id = 2 AND [type] = 0;
  6355. SELECT @online_count = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE is_online = 1 AND scheduler_id < 255 AND parent_node_id < 64;
  6356. SELECT @filesizes = COUNT(DISTINCT size) FROM tempdb.sys.database_files WHERE [type] = 0;
  6357. IF (SELECT CASE WHEN @filesizes = 1 AND ((@tdb_files >= 4 AND @tdb_files <= 8 AND @tdb_files % 4 = 0) /*OR (@tdb_files >= 8 AND @tdb_files % 4 = 0)*/
  6358. OR (@tdb_files >= (@online_count / 2) AND @tdb_files >= 8 AND @tdb_files % 4 = 0)) THEN 0 ELSE 1 END) = 0
  6359. BEGIN
  6360. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Check], '[OK]' AS [Deviation]
  6361. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Information], physical_name AS [tempDB_Files], CAST((size*8)/1024.0 AS DECIMAL(18,2)) AS [File_Size_MB]
  6362. FROM tempdb.sys.database_files (NOLOCK)
  6363. WHERE type = 0;
  6364. END
  6365. ELSE
  6366. BEGIN
  6367. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Check],
  6368. CASE WHEN @tdb_files < 4 THEN '[WARNING: tempDB has only ' + CONVERT(VARCHAR(10), @tdb_files) + ' file(s). Consider creating between 4 and 8 tempDB data files, 1 per each 2 cores, of the same size]'
  6369. WHEN @filesizes = 1 AND @tdb_files < (@online_count / 2) AND @tdb_files >= 8 AND @tdb_files % 4 = 0 THEN '[INFORMATION: Number of Data files to Scheduler ratio might not be Optimal. Consider creating 1 data file per each 2 cores, in multiples of 4, all of the same size]'
  6370. WHEN @filesizes > 1 AND @tdb_files >= 4 AND @tdb_files % 4 > 0 THEN '[WARNING: Data file sizes do not match and Number of data files is not multiple of 4]'
  6371. WHEN @filesizes = 1 AND @tdb_files >= 4 AND @tdb_files % 4 > 0 THEN '[WARNING: Number of data files is not multiple of 4]'
  6372. WHEN @filesizes > 1 AND @tdb_files >= 4 AND @tdb_files % 4 = 0 THEN '[WARNING: Data file sizes do not match]'
  6373. ELSE '[OK]' END AS [Deviation];
  6374. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Information], physical_name AS [tempDB_Files], CAST((size*8)/1024.0 AS DECIMAL(18,2)) AS [File_Size_MB]
  6375. FROM tempdb.sys.database_files (NOLOCK)
  6376. WHERE type = 0;
  6377. END;
  6378. --------------------------------------------------------------------------------------------------------------------------------
  6379. -- tempDB data files autogrow of equal size subsection
  6380. --------------------------------------------------------------------------------------------------------------------------------
  6381. RAISERROR (N' |-Starting tempDB Files autogrow of equal size', 10, 1) WITH NOWAIT
  6382. IF (SELECT COUNT(DISTINCT growth) FROM sys.master_files WHERE [database_id] = 2 AND [type] = 0) > 1
  6383. OR (SELECT COUNT(DISTINCT is_percent_growth) FROM sys.master_files WHERE [database_id] = 2 AND [type] = 0) > 1
  6384. BEGIN
  6385. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Check], '[WARNING: Some tempDB data files have different growth settings]' AS [Deviation]
  6386. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Information],
  6387. DB_NAME(2) AS [Database_Name],
  6388. mf.name AS [Logical_Name],
  6389. mf.[size]*8 AS [Current_Size_KB],
  6390. mf.type_desc AS [File_Type],
  6391. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  6392. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount],
  6393. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((mf.size*8)*CONVERT(bigint, mf.growth))/100
  6394. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  6395. ELSE 0 END AS [Next_Growth_KB],
  6396. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  6397. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  6398. ELSE '' END AS [Comments]
  6399. FROM tempdb.sys.database_files mf (NOLOCK)
  6400. WHERE [type] = 0
  6401. GROUP BY mf.name, mf.[size], is_percent_growth, mf.growth, mf.type_desc, mf.[type]
  6402. ORDER BY 3, 4
  6403. END
  6404. ELSE
  6405. BEGIN
  6406. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Check], '[OK]' AS [Deviation]
  6407. END;
  6408. IF @ptochecks = 1
  6409. RAISERROR (N'|-Starting Performance Checks', 10, 1) WITH NOWAIT
  6410. --------------------------------------------------------------------------------------------------------------------------------
  6411. -- Perf counters, Waits, Latches and Spinlocks subsection
  6412. --------------------------------------------------------------------------------------------------------------------------------
  6413. IF @ptochecks = 1
  6414. BEGIN
  6415. SELECT @ErrorMessage = ' |-Starting Perf counters, Waits and Latches (wait for ' + CONVERT(VARCHAR(3), @duration) + 's)'
  6416. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6417. DECLARE @minctr DATETIME, @maxctr DATETIME, @durationstr NVARCHAR(24)
  6418. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  6419. DROP TABLE #tblPerfCount;
  6420. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  6421. CREATE TABLE #tblPerfCount (
  6422. [retrieval_time] [datetime],
  6423. [object_name] [NVARCHAR](128),
  6424. [counter_name] [NVARCHAR](128),
  6425. [instance_name] [NVARCHAR](128),
  6426. [counter_name_type] int,
  6427. [cntr_value] float NULL
  6428. );
  6429. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  6430. DROP TABLE tempdb.dbo.tblPerfThresholds;
  6431. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  6432. CREATE TABLE tempdb.dbo.tblPerfThresholds (
  6433. [counter_family] [NVARCHAR](128),
  6434. [counter_name] [NVARCHAR](128),
  6435. [counter_instance] [NVARCHAR](128),
  6436. [counter_name_type] int,
  6437. [counter_value] float NULL
  6438. );
  6439. -- Create the helper function
  6440. EXEC ('USE tempdb; IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID(''tempdb.dbo.fn_perfctr'')) DROP FUNCTION dbo.fn_perfctr')
  6441. EXEC ('USE tempdb; EXEC(''
  6442. CREATE FUNCTION dbo.fn_perfctr (@ctr1Fam NVARCHAR(128), @ctr1 NVARCHAR(128))
  6443. RETURNS float
  6444. AS
  6445. BEGIN
  6446. DECLARE @ReturnVals float, @ctr1Val float, @ctr2Val float, @ctr2Fam NVARCHAR(128), @ctr2 NVARCHAR(128), @type tinyint
  6447. -- ctr1Fam = source counter object; ctr1 = source counter; ctr2Fam = counter object to compare with; ctr2 = counter to compare with
  6448. -- Type 1 = ratio between source and compare (Ex. 1 per each 10); 2 = pct ratio between source and compare (Ex. 10 pct of compare counter); 3 = ratio between compare and source; 4 = pct ratio between compare and source
  6449. IF @ctr1 IN (''''Forwarded Records/sec'''',''''FreeSpace Scans/sec'''',''''Page Splits/sec'''',''''Workfiles Created/sec'''',''''Page lookups/sec'''',''''SQL Compilations/sec'''')
  6450. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''Batch Requests/sec'''', @type = 1
  6451. ELSE IF @ctr1 = ''''Lock Requests/sec''''
  6452. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''Batch Requests/sec'''', @type = 0
  6453. ELSE IF @ctr1 = ''''Full Scans/sec''''
  6454. SELECT @ctr2Fam = ''''SQLServer:Access Methods'''', @ctr2 = ''''Index Searches/sec'''', @type = 1
  6455. ELSE IF @ctr1 = ''''Index Searches/sec''''
  6456. SELECT @ctr2Fam = ''''SQLServer:Access Methods'''', @ctr2 = ''''Full Scans/sec'''', @type = 3
  6457. ELSE IF @ctr1 = ''''Readahead pages/sec''''
  6458. SELECT @ctr2Fam = ''''SQLServer:Buffer Manager'''', @ctr2 = ''''Page reads/sec'''', @type = 1
  6459. ELSE IF @ctr1 = ''''Target Server Memory (KB)''''
  6460. SELECT @ctr2Fam = ''''SQLServer:Memory Manager'''', @ctr2 = ''''Total Server Memory (KB)'''', @type = 2
  6461. ELSE IF @ctr1 = ''''SQL Re-Compilations/sec''''
  6462. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''SQL Compilations/sec'''', @type = 1
  6463. ELSE IF @ctr1 = ''''Page writes/sec''''
  6464. SELECT @ctr2Fam = ''''SQLServer:Buffer Manager'''', @ctr2 = ''''Page reads/sec'''', @type = 3
  6465. SELECT @ctr1Val = [counter_value] FROM tempdb.dbo.tblPerfThresholds WHERE [counter_family] = @ctr1Fam AND [counter_name] = @ctr1
  6466. SELECT @ctr2Val = [counter_value] FROM tempdb.dbo.tblPerfThresholds WHERE [counter_family] = @ctr2Fam AND [counter_name] = @ctr2
  6467. IF @ctr1 = ''''Target Server Memory (KB)''''
  6468. SELECT @ctr1Val = @ctr1Val / 1024, @ctr2Val = @ctr2Val / 1024
  6469. --Find ratio between counter 1 and 2
  6470. IF @ctr1Val IS NULL OR @ctr2Val IS NULL
  6471. BEGIN
  6472. SELECT @ReturnVals = NULL
  6473. END
  6474. ELSE IF @ctr1Val > 1 AND @ctr2Val > 1
  6475. BEGIN
  6476. IF @type = 0
  6477. SELECT @ReturnVals = (@ctr1Val / @ctr2Val)
  6478. IF @type = 1
  6479. SELECT @ReturnVals = (@ctr1Val / @ctr2Val) * 100
  6480. If @type = 2
  6481. SELECT @ReturnVals = (@ctr1Val - @ctr2Val)
  6482. IF @type = 3
  6483. SELECT @ReturnVals = (@ctr2Val / @ctr1Val) * 100
  6484. END
  6485. ELSE
  6486. BEGIN
  6487. SELECT @ReturnVals = 0
  6488. END
  6489. RETURN (@ReturnVals)
  6490. END'')
  6491. ')
  6492. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  6493. DROP TABLE #tblWaits;
  6494. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  6495. CREATE TABLE [dbo].[#tblWaits](
  6496. [retrieval_time] [datetime],
  6497. [wait_type] [nvarchar](60) NOT NULL,
  6498. [wait_time_ms] bigint NULL,
  6499. [signal_wait_time_ms] bigint NULL,
  6500. [resource_wait_time_ms] bigint NULL
  6501. );
  6502. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  6503. DROP TABLE #tblFinalWaits;
  6504. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  6505. CREATE TABLE [dbo].[#tblFinalWaits](
  6506. [wait_type] [nvarchar](60) NOT NULL,
  6507. [wait_time_s] [numeric](16, 6) NULL,
  6508. [signal_wait_time_s] [numeric](16, 6) NULL,
  6509. [resource_wait_time_s] [numeric](16, 6) NULL,
  6510. [pct] [numeric](12, 2) NULL,
  6511. [rn] [bigint] NULL,
  6512. [signal_wait_pct] [numeric](12, 2) NULL,
  6513. [resource_wait_pct] [numeric](12, 2) NULL
  6514. );
  6515. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  6516. DROP TABLE #tblLatches;
  6517. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  6518. CREATE TABLE [dbo].[#tblLatches](
  6519. [retrieval_time] [datetime],
  6520. [latch_class] [nvarchar](60) NOT NULL,
  6521. [wait_time_ms] bigint NULL,
  6522. [waiting_requests_count] [bigint] NULL
  6523. );
  6524. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  6525. DROP TABLE #tblFinalLatches;
  6526. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  6527. CREATE TABLE [dbo].[#tblFinalLatches](
  6528. [latch_class] [nvarchar](60) NOT NULL,
  6529. [wait_time_s] [decimal](16, 6) NULL,
  6530. [waiting_requests_count] [bigint] NULL,
  6531. [pct] [decimal](12, 2) NULL,
  6532. [rn] [bigint] NULL
  6533. );
  6534. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  6535. DROP TABLE #tblSpinlocksBefore;
  6536. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  6537. CREATE TABLE [dbo].[#tblSpinlocksBefore](
  6538. [name] NVARCHAR(512) NOT NULL,
  6539. [collisions] bigint NULL,
  6540. [spins] bigint NULL,
  6541. [spins_per_collision] real NULL,
  6542. [sleep_time] bigint NULL,
  6543. [backoffs] int NULL
  6544. );
  6545. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  6546. DROP TABLE #tblSpinlocksAfter;
  6547. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  6548. CREATE TABLE [dbo].[#tblSpinlocksAfter](
  6549. [name] NVARCHAR(512) NOT NULL,
  6550. [collisions] bigint NULL,
  6551. [spins] bigint NULL,
  6552. [spins_per_collision] real NULL,
  6553. [sleep_time] bigint NULL,
  6554. [backoffs] int NULL
  6555. );
  6556. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  6557. DROP TABLE #tblFinalSpinlocks;
  6558. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  6559. CREATE TABLE [dbo].[#tblFinalSpinlocks](
  6560. [name] NVARCHAR(512) NOT NULL,
  6561. [collisions] bigint NULL,
  6562. [spins] bigint NULL,
  6563. [spins_per_collision] real NULL,
  6564. [sleep_time] bigint NULL,
  6565. [backoffs] int NULL,
  6566. [spins_pct] [decimal](12, 2) NULL,
  6567. [rn] [bigint] NULL
  6568. );
  6569. SELECT @minctr = GETDATE()
  6570. -- When counter type = 272696576 (find delta from two collection points)
  6571. -- When counter type = 65792 (face value)
  6572. -- When counter type = 1073939712 (base value, check next counter types)
  6573. -- When counter type = 1073874176 (find delta from current value and base value between two collection points). Base value is counter with type 1073939712.
  6574. -- When counter type = 537003264 (find delta from current value and base value). Base value is counter with type 1073939712.
  6575. INSERT INTO #tblPerfCount
  6576. SELECT @minctr, [object_name], counter_name, instance_name, cntr_type AS counter_name_type, cntr_value
  6577. FROM sys.dm_os_performance_counters pc0 (NOLOCK)
  6578. WHERE ([object_name] LIKE '%:Access Methods%'
  6579. OR [object_name] LIKE '%:Buffer Manager%'
  6580. OR [object_name] LIKE '%:Buffer Node%'
  6581. OR [object_name] LIKE '%:Latches%'
  6582. OR [object_name] LIKE '%:Locks%'
  6583. OR [object_name] LIKE '%:Memory Manager%'
  6584. OR [object_name] LIKE '%:Memory Node%'
  6585. OR [object_name] LIKE '%:Plan Cache%'
  6586. OR [object_name] LIKE '%:SQL Statistics%'
  6587. OR [object_name] LIKE '%:Wait Statistics%'
  6588. OR [object_name] LIKE '%:Workload Group Stats%'
  6589. OR [object_name] LIKE '%:Memory Broker Clerks%'
  6590. OR [object_name] LIKE '%:Databases%'
  6591. OR [object_name] LIKE '%:Database Replica%')
  6592. AND (counter_name LIKE '%FreeSpace Scans/sec%'
  6593. OR counter_name LIKE '%Forwarded Records/sec%'
  6594. OR counter_name LIKE '%Full Scans/sec%'
  6595. OR counter_name LIKE '%Index Searches/sec%'
  6596. OR counter_name LIKE '%Page Splits/sec%'
  6597. OR counter_name LIKE '%Scan Point Revalidations/sec%'
  6598. OR counter_name LIKE '%Table Lock Escalations/sec%'
  6599. OR counter_name LIKE '%Workfiles Created/sec%'
  6600. OR counter_name LIKE '%Worktables Created/sec%'
  6601. OR counter_name LIKE '%Worktables From Cache%'
  6602. OR counter_name LIKE '%Buffer cache hit ratio%'
  6603. OR counter_name LIKE '%Buffer cache hit ratio base%'
  6604. OR counter_name LIKE '%Checkpoint pages/sec%'
  6605. OR counter_name LIKE '%Background writer pages/sec%'
  6606. OR counter_name LIKE '%Lazy writes/sec%'
  6607. OR counter_name LIKE '%Free pages%'
  6608. OR counter_name LIKE '%Page life expectancy%'
  6609. OR counter_name LIKE '%Page lookups/sec%'
  6610. OR counter_name LIKE '%Page reads/sec%'
  6611. OR counter_name LIKE '%Page writes/sec%'
  6612. OR counter_name LIKE '%Readahead pages/sec%'
  6613. OR counter_name LIKE '%Average Latch Wait Time (ms)%'
  6614. OR counter_name LIKE '%Average Latch Wait Time Base%'
  6615. OR counter_name LIKE '%Total Latch Wait Time (ms)%'
  6616. OR counter_name LIKE '%Average Wait Time (ms)%'
  6617. OR counter_name LIKE '%Average Wait Time Base%'
  6618. OR counter_name LIKE '%Number of Deadlocks/sec%'
  6619. OR counter_name LIKE '%Free Memory (KB)%'
  6620. OR counter_name LIKE '%Stolen Server Memory (KB)%'
  6621. OR counter_name LIKE '%Target Server Memory (KB)%'
  6622. OR counter_name LIKE '%Total Server Memory (KB)%'
  6623. OR counter_name LIKE '%Free Node Memory (KB)%'
  6624. OR counter_name LIKE '%Foreign Node Memory (KB)%'
  6625. OR counter_name LIKE '%Stolen Node Memory (KB)%'
  6626. OR counter_name LIKE '%Target Node Memory (KB)%'
  6627. OR counter_name LIKE '%Total Node Memory (KB)%'
  6628. OR counter_name LIKE '%Batch Requests/sec%'
  6629. OR counter_name LIKE '%SQL Compilations/sec%'
  6630. OR counter_name LIKE '%SQL Re-Compilations/sec%'
  6631. OR counter_name LIKE '%Lock waits%'
  6632. OR counter_name LIKE '%Log buffer waits%'
  6633. OR counter_name LIKE '%Log write waits%'
  6634. OR counter_name LIKE '%Memory grant queue waits%'
  6635. OR counter_name LIKE '%Network IO waits%'
  6636. OR counter_name LIKE '%Non-Page latch waits%'
  6637. OR counter_name LIKE '%Page IO latch waits%'
  6638. OR counter_name LIKE '%Page latch waits%'
  6639. OR counter_name LIKE '%Active parallel threads%'
  6640. OR counter_name LIKE '%Blocked tasks%'
  6641. OR counter_name LIKE '%CPU usage %'
  6642. OR counter_name LIKE '%CPU usage % base%'
  6643. OR counter_name LIKE '%Query optimizations/sec%'
  6644. OR counter_name LIKE '%Requests completed/sec%'
  6645. OR counter_name LIKE '%Suboptimal plans/sec%'
  6646. OR counter_name LIKE '%Temporary Tables & Table Variables%'
  6647. OR counter_name LIKE '%Extended Stored Procedures%'
  6648. OR counter_name LIKE '%Bound Trees%'
  6649. OR counter_name LIKE '%SQL Plans%'
  6650. OR counter_name LIKE '%Object Plans%'
  6651. OR counter_name LIKE '%_Total%'
  6652. OR counter_name LIKE 'Transactions/sec%'
  6653. OR counter_name LIKE '%Log Flush Wait Time%'
  6654. OR counter_name LIKE '%Log Flush Waits/sec%'
  6655. OR counter_name LIKE '%Recovery Queue%'
  6656. OR counter_name LIKE '%Log Send Queue%'
  6657. OR counter_name LIKE '%Transaction Delay%'
  6658. OR counter_name LIKE '%Redo blocked/sec%'
  6659. OR counter_name LIKE '%Resent Messages/sec%'
  6660. OR instance_name LIKE '%Buffer Pool%'
  6661. OR instance_name LIKE '%Column store object pool%');
  6662. INSERT INTO #tblWaits
  6663. SELECT @minctr, wait_type, wait_time_ms, signal_wait_time_ms,(wait_time_ms-signal_wait_time_ms) AS resource_wait_time_ms
  6664. FROM sys.dm_os_wait_stats (NOLOCK)
  6665. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
  6666. 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT',
  6667. 'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH',
  6668. 'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6669. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6670. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6671. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6672. AND wait_type NOT LIKE N'SLEEP_%'
  6673. AND wait_time_ms > 0;
  6674. INSERT INTO #tblLatches
  6675. SELECT @minctr, latch_class, wait_time_ms, waiting_requests_count
  6676. FROM sys.dm_os_latch_stats (NOLOCK)
  6677. WHERE /*latch_class NOT IN ('BUFFER')
  6678. AND*/ wait_time_ms > 0;
  6679. IF @sqlmajorver > 9
  6680. BEGIN
  6681. INSERT INTO #tblSpinlocksBefore
  6682. SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs
  6683. FROM sys.dm_os_spinlock_stats;
  6684. END
  6685. ELSE IF @sqlmajorver = 9
  6686. BEGIN
  6687. INSERT INTO #tblSpinlocksBefore
  6688. EXEC ('DBCC SQLPERF(''spinlockstats'')');
  6689. END;
  6690. IF @duration > 255
  6691. SET @duration = 255;
  6692. IF @duration < 10
  6693. SET @duration = 10;
  6694. SELECT @durationstr = 'WAITFOR DELAY ''00:' + CASE WHEN LEN(CONVERT(VARCHAR(3),@duration/60%60)) = 1
  6695. THEN '0' + CONVERT(VARCHAR(3),@duration/60%60)
  6696. ELSE CONVERT(VARCHAR(3),@duration/60%60) END
  6697. + ':' + CONVERT(VARCHAR(3),@duration-(@duration/60)*60) + ''''
  6698. EXECUTE sp_executesql @durationstr;
  6699. SELECT @maxctr = GETDATE()
  6700. INSERT INTO #tblPerfCount
  6701. SELECT @maxctr, [object_name], counter_name, instance_name, cntr_type AS counter_name_type, cntr_value
  6702. FROM sys.dm_os_performance_counters pc0 (NOLOCK)
  6703. WHERE (cntr_type = 272696576 OR cntr_type = 1073874176 OR cntr_type = 1073939712) -- Get only counters whose delta between collection points matters
  6704. AND ([object_name] LIKE '%:Access Methods%'
  6705. OR [object_name] LIKE '%:Buffer Manager%'
  6706. OR [object_name] LIKE '%:Buffer Node%'
  6707. OR [object_name] LIKE '%:Latches%'
  6708. OR [object_name] LIKE '%:Locks%'
  6709. OR [object_name] LIKE '%:Memory Manager%'
  6710. OR [object_name] LIKE '%:Memory Node%'
  6711. OR [object_name] LIKE '%:Plan Cache%'
  6712. OR [object_name] LIKE '%:SQL Statistics%'
  6713. OR [object_name] LIKE '%:Wait Statistics%'
  6714. OR [object_name] LIKE '%:Workload Group Stats%'
  6715. OR [object_name] LIKE '%:Memory Broker Clerks%'
  6716. OR [object_name] LIKE '%:Databases%'
  6717. OR [object_name] LIKE '%:Database Replica%')
  6718. AND (counter_name LIKE '%FreeSpace Scans/sec%'
  6719. OR counter_name LIKE '%Forwarded Records/sec%'
  6720. OR counter_name LIKE '%Full Scans/sec%'
  6721. OR counter_name LIKE '%Index Searches/sec%'
  6722. OR counter_name LIKE '%Page Splits/sec%'
  6723. OR counter_name LIKE '%Scan Point Revalidations/sec%'
  6724. OR counter_name LIKE '%Table Lock Escalations/sec%'
  6725. OR counter_name LIKE '%Workfiles Created/sec%'
  6726. OR counter_name LIKE '%Worktables Created/sec%'
  6727. OR counter_name LIKE '%Worktables From Cache%'
  6728. OR counter_name LIKE '%Buffer cache hit ratio%'
  6729. OR counter_name LIKE '%Buffer cache hit ratio base%'
  6730. OR counter_name LIKE '%Checkpoint pages/sec%'
  6731. OR counter_name LIKE '%Background writer pages/sec%'
  6732. OR counter_name LIKE '%Lazy writes/sec%'
  6733. OR counter_name LIKE '%Free pages%'
  6734. OR counter_name LIKE '%Page life expectancy%'
  6735. OR counter_name LIKE '%Page lookups/sec%'
  6736. OR counter_name LIKE '%Page reads/sec%'
  6737. OR counter_name LIKE '%Page writes/sec%'
  6738. OR counter_name LIKE '%Readahead pages/sec%'
  6739. OR counter_name LIKE '%Average Latch Wait Time (ms)%'
  6740. OR counter_name LIKE '%Average Latch Wait Time Base%'
  6741. OR counter_name LIKE '%Total Latch Wait Time (ms)%'
  6742. OR counter_name LIKE '%Average Wait Time (ms)%'
  6743. OR counter_name LIKE '%Average Wait Time Base%'
  6744. OR counter_name LIKE '%Number of Deadlocks/sec%'
  6745. OR counter_name LIKE '%Free Memory (KB)%'
  6746. OR counter_name LIKE '%Stolen Server Memory (KB)%'
  6747. OR counter_name LIKE '%Target Server Memory (KB)%'
  6748. OR counter_name LIKE '%Total Server Memory (KB)%'
  6749. OR counter_name LIKE '%Free Node Memory (KB)%'
  6750. OR counter_name LIKE '%Foreign Node Memory (KB)%'
  6751. OR counter_name LIKE '%Stolen Node Memory (KB)%'
  6752. OR counter_name LIKE '%Target Node Memory (KB)%'
  6753. OR counter_name LIKE '%Total Node Memory (KB)%'
  6754. OR counter_name LIKE '%Batch Requests/sec%'
  6755. OR counter_name LIKE '%SQL Compilations/sec%'
  6756. OR counter_name LIKE '%SQL Re-Compilations/sec%'
  6757. OR counter_name LIKE '%Lock waits%'
  6758. OR counter_name LIKE '%Log buffer waits%'
  6759. OR counter_name LIKE '%Log write waits%'
  6760. OR counter_name LIKE '%Memory grant queue waits%'
  6761. OR counter_name LIKE '%Network IO waits%'
  6762. OR counter_name LIKE '%Non-Page latch waits%'
  6763. OR counter_name LIKE '%Page IO latch waits%'
  6764. OR counter_name LIKE '%Page latch waits%'
  6765. OR counter_name LIKE '%Active parallel threads%'
  6766. OR counter_name LIKE '%Blocked tasks%'
  6767. OR counter_name LIKE '%CPU usage %'
  6768. OR counter_name LIKE '%CPU usage % base%'
  6769. OR counter_name LIKE '%Query optimizations/sec%'
  6770. OR counter_name LIKE '%Requests completed/sec%'
  6771. OR counter_name LIKE '%Suboptimal plans/sec%'
  6772. OR counter_name LIKE '%Temporary Tables & Table Variables%'
  6773. OR counter_name LIKE '%Extended Stored Procedures%'
  6774. OR counter_name LIKE '%Bound Trees%'
  6775. OR counter_name LIKE '%SQL Plans%'
  6776. OR counter_name LIKE '%Object Plans%'
  6777. OR counter_name LIKE '%_Total%'
  6778. OR counter_name LIKE 'Transactions/sec%'
  6779. OR counter_name LIKE '%Log Flush Wait Time%'
  6780. OR counter_name LIKE '%Log Flush Waits/sec%'
  6781. OR counter_name LIKE '%Recovery Queue%'
  6782. OR counter_name LIKE '%Log Send Queue%'
  6783. OR counter_name LIKE '%Transaction Delay%'
  6784. OR counter_name LIKE '%Redo blocked/sec%'
  6785. OR counter_name LIKE '%Resent Messages/sec%'
  6786. OR instance_name LIKE '%Buffer Pool%'
  6787. OR instance_name LIKE '%Column store object pool%');
  6788. INSERT INTO #tblWaits
  6789. SELECT @maxctr, wait_type, wait_time_ms, signal_wait_time_ms,(wait_time_ms-signal_wait_time_ms) AS resource_wait_time_ms
  6790. FROM sys.dm_os_wait_stats (NOLOCK)
  6791. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
  6792. 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT',
  6793. 'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH',
  6794. 'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6795. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6796. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6797. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6798. AND wait_type NOT LIKE N'SLEEP_%'
  6799. AND wait_time_ms > 0;
  6800. INSERT INTO #tblLatches
  6801. SELECT @maxctr, latch_class, wait_time_ms, waiting_requests_count
  6802. FROM sys.dm_os_latch_stats (NOLOCK)
  6803. WHERE /*latch_class NOT IN ('BUFFER')
  6804. AND*/ wait_time_ms > 0;
  6805. IF @sqlmajorver > 9
  6806. BEGIN
  6807. INSERT INTO #tblSpinlocksAfter
  6808. SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs
  6809. FROM sys.dm_os_spinlock_stats;
  6810. END
  6811. ELSE IF @sqlmajorver = 9
  6812. BEGIN
  6813. INSERT INTO #tblSpinlocksAfter
  6814. EXEC ('DBCC SQLPERF(''spinlockstats'')');
  6815. END;
  6816. INSERT INTO tempdb.dbo.tblPerfThresholds
  6817. SELECT DISTINCT t1.[object_name], t1.counter_name, t1.instance_name, t1.[counter_name_type],
  6818. CASE WHEN t1.counter_name_type = 272696576
  6819. THEN CONVERT(float,(
  6820. (SELECT t2.cntr_value FROM #tblPerfCount t2 WHERE t2.[retrieval_time] = @maxctr AND t2.counter_name = t1.counter_name AND t2.instance_name = t1.instance_name) -
  6821. (SELECT t2.cntr_value FROM #tblPerfCount t2 WHERE t2.[retrieval_time] = @minctr AND t2.counter_name = t1.counter_name AND t2.instance_name = t1.instance_name)
  6822. ) / DATEDIFF(ss,@minctr,@maxctr)) -- Get value per s over last xx s
  6823. WHEN t1.counter_name_type = 537003264
  6824. THEN (SELECT CONVERT(float,(t2.cntr_value / CASE WHEN t3.cntr_value <= 0 THEN 1 ELSE t3.cntr_value END) * 100.0)
  6825. FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.instance_name = t3.instance_name AND t3.counter_name IN (RTRIM(t2.counter_name) + N' base', 'Worktables From Cache Base')
  6826. WHERE t2.counter_name_type = t1.counter_name_type AND t3.counter_name_type = 1073939712 AND t2.counter_name = t1.counter_name AND t2.instance_name = t1.instance_name AND t2.[retrieval_time] = @minctr AND t3.[retrieval_time] = @minctr
  6827. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6828. WHEN t1.counter_name_type = 1073874176 AND t1.counter_name = 'Average Latch Wait Time (ms)'
  6829. THEN CONVERT(float,(
  6830. (
  6831. (SELECT t2.cntr_value - t3.cntr_value
  6832. FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.counter_name = t3.counter_name
  6833. WHERE t2.counter_name = t1.counter_name /*AND t2.counter_name_type = t1.counter_name_type AND t2.instance_name = t1.instance_name*/ AND t2.[retrieval_time] = @maxctr AND t3.[retrieval_time] = @minctr
  6834. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6835. /
  6836. (SELECT CASE WHEN t2.cntr_value - t3.cntr_value <= 0 THEN 1 ELSE t2.cntr_value - t3.cntr_value END
  6837. FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.counter_name = t3.counter_name
  6838. WHERE t2.counter_name = 'Average Latch Wait Time Base' AND t2.counter_name_type = 1073939712 AND t2.instance_name = t1.instance_name AND t2.[retrieval_time] = @maxctr AND t3.[retrieval_time] = @minctr
  6839. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6840. )
  6841. / DATEDIFF(ss,@minctr,@maxctr))) -- Get value per s over last xx s
  6842. WHEN t1.counter_name_type = 1073874176 AND t1.counter_name = 'Average Wait Time (ms)'
  6843. THEN CONVERT(float,(
  6844. (
  6845. SELECT (t4.cntr_value / CASE WHEN t5.cntr_value <= 0 THEN 1 ELSE t5.cntr_value END) / DATEDIFF(ss,@minctr,@maxctr)
  6846. FROM
  6847. (SELECT t2.cntr_value - t3.cntr_value AS cntr_value, t2.instance_name FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.counter_name = t3.counter_name AND t2.instance_name = t3.instance_name
  6848. WHERE t2.counter_name = t1.counter_name /*AND t2.counter_name_type = t1.counter_name_type AND t2.instance_name = t1.instance_name*/ AND t2.[retrieval_time] = @maxctr AND t3.[retrieval_time] = @minctr
  6849. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name, t2.instance_name) AS t4
  6850. INNER JOIN
  6851. (SELECT t2.cntr_value - t3.cntr_value AS cntr_value, t2.instance_name FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.counter_name = t3.counter_name AND t2.instance_name = t3.instance_name
  6852. WHERE t2.counter_name = 'Average Wait Time Base' AND t2.counter_name_type = 1073939712 AND t2.instance_name = t1.instance_name AND t2.[retrieval_time] = @maxctr AND t3.[retrieval_time] = @minctr
  6853. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name, t2.instance_name) AS t5
  6854. ON t4.instance_name = t5.instance_name
  6855. ))) -- Get value per s over last xx s
  6856. ELSE CONVERT(float,t1.cntr_value)
  6857. END
  6858. FROM #tblPerfCount t1
  6859. WHERE (t1.counter_name_type <> 1073939712)
  6860. GROUP BY t1.[object_name], t1.[counter_name], t1.instance_name, t1.counter_name_type, t1.cntr_value
  6861. ORDER BY t1.[object_name], t1.[counter_name], t1.instance_name;
  6862. ;WITH ctectr AS (SELECT [counter_family],[counter_name],[counter_instance],[counter_value],
  6863. CASE WHEN [counter_name] IN ('Worktables Created/sec','Worktables From Cache Ratio','Buffer cache hit ratio',
  6864. 'Free list stalls/sec','Free pages','Free Memory (KB)','Lazy writes/sec','Page life expectancy',
  6865. 'Page reads/sec','Log Flush Wait Time','Log Flush Waits/sec','Average Latch Wait Time (ms)',
  6866. 'Total Latch Wait Time (ms)','Lock Waits/sec','Number of Deadlocks/sec','Batch Requests/sec') THEN [counter_value]
  6867. ELSE tempdb.dbo.fn_perfctr([counter_family],[counter_name]) END AS [counter_calculated_threshold_value]
  6868. FROM tempdb.dbo.tblPerfThresholds)
  6869. SELECT 'Performance_checks' AS [Category], 'Perf_Counters' AS [Check],[counter_family],[counter_name],[counter_instance],[counter_value],[counter_calculated_threshold_value],
  6870. CASE WHEN [counter_name] = 'Forwarded Records/sec' AND [counter_calculated_threshold_value] > 10 THEN '[WARNING: A ratio of more than 1 forwarded record for every 10 batch requests]'
  6871. WHEN [counter_name] = 'FreeSpace Scans/sec' AND [counter_calculated_threshold_value] > 10 THEN '[WARNING: A ratio of more than 1 freespace scan for every 10 batch requests]'
  6872. WHEN [counter_name] IN ('Full Scans/sec','Index Searches/sec') AND [counter_calculated_threshold_value] > 0.1 THEN '[WARNING: A ratio of more than 1 SQL Full Scan for every 1000 Index Searches]'
  6873. WHEN [counter_name] = 'Page Splits/sec' AND [counter_calculated_threshold_value] > 5 THEN '[WARNING: A ratio of more than 1 page split for every 20 batch requests]'
  6874. WHEN [counter_name] = 'Workfiles Created/sec' AND [counter_calculated_threshold_value] > 5 THEN '[WARNING: A ratio of more than 1 workfile created for every 20 batch requests]'
  6875. WHEN [counter_name] = 'Worktables Created/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: Greater than 20 Worktables created per second]'
  6876. WHEN [counter_name] = 'Worktables From Cache Ratio' AND [counter_calculated_threshold_value] < 90 THEN '[WARNING: Less than 90 percent Worktables from Cache Ratio]'
  6877. WHEN [counter_name] = 'Buffer cache hit ratio' AND [counter_calculated_threshold_value] < 97 THEN '[WARNING: Less than 97 percent buffer cache hit ratio]'
  6878. WHEN [counter_name] = 'Buffer cache hit ratio' AND [counter_calculated_threshold_value] < 90 THEN '[WARNING: Less than 90 percent buffer cache hit ratio]'
  6879. WHEN [counter_name] = 'Free list stalls/sec' AND [counter_calculated_threshold_value] < 2 THEN '[WARNING: Free list stalls per second is less than 2]'
  6880. WHEN [counter_name] = 'Free pages' AND [counter_calculated_threshold_value] < 640 THEN '[WARNING: Less than 640 Free Pages]'
  6881. WHEN [counter_name] = 'Free Memory (KB)' AND [counter_calculated_threshold_value] < 5 THEN '[WARNING: Less than 5MB]'
  6882. WHEN [counter_name] = 'Lazy writes/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: Greater than 20 Lazy Writes per second]'
  6883. WHEN [counter_name] = 'Page life expectancy' AND [counter_calculated_threshold_value] < 300 THEN '[WARNING: Less than 300 seconds of Page Life Expectancy]'
  6884. WHEN [counter_name] = 'Page life expectancy' AND [counter_calculated_threshold_value] < 700 THEN '[WARNING: Less than 700 seconds of Page Life Expectancy]'
  6885. WHEN [counter_name] = 'Page lookups/sec' AND [counter_calculated_threshold_value] > 1 THEN '[WARNING: A ratio of more than 1 page lookup for every 100 batch requests]'
  6886. WHEN [counter_name] = 'Page reads/sec' AND [counter_calculated_threshold_value] > 90 THEN '[WARNING: Greater than 90 page reads per second]'
  6887. WHEN [counter_name] = 'Page writes/sec' AND [counter_calculated_threshold_value] > 30 THEN '[WARNING: Page writes are more than 30 percent of page reads per second]'
  6888. WHEN [counter_name] = 'Page writes/sec' AND [counter_value] > 90 THEN '[WARNING: Greater than 90 page writes per second]'
  6889. WHEN [counter_name] = 'Readahead pages/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: More than 20 percent of page reads per second]'
  6890. WHEN [counter_name] IN ('Log Flush Wait Time','Log Flush Waits/sec','Lock Waits/sec','Number of Deadlocks/sec') AND [counter_calculated_threshold_value] > 0 THEN '[WARNING: Greater than 0]'
  6891. WHEN [counter_name] = 'Average Latch Wait Time (ms)' AND [counter_calculated_threshold_value] > 10 THEN '[WARNING: Latch wait is more than 10 milliseconds on average]'
  6892. WHEN [counter_name] = 'Total Latch Wait Time (ms)' AND [counter_calculated_threshold_value] > 500 THEN '[WARNING: Total latch wait time is above 500 ms per each second on average]'
  6893. WHEN [counter_name] = 'Total Latch Wait Time (ms)' AND [counter_calculated_threshold_value] > 750 THEN '[WARNING: Total latch wait time is above 750 ms per each second on average]'
  6894. WHEN [counter_name] = 'Lock Requests/sec' AND [counter_calculated_threshold_value] > 500 THEN '[WARNING: A ratio of more than 500 lock requests per batch request]'
  6895. WHEN [counter_name] = 'Target Server Memory (KB)' AND [counter_calculated_threshold_value] > 500 THEN '[WARNING: Target Server Memory is more than 500MBs above Total Server Memory]'
  6896. WHEN [counter_name] = 'Batch Requests/sec' AND [counter_calculated_threshold_value] > 1000 THEN '[WARNING: Greater than 1000 batch requests per second]'
  6897. WHEN [counter_name] = 'SQL Compilations/sec' AND [counter_calculated_threshold_value] > 10 THEN '[WARNING: A ratio of more than 1 SQL Compilation for every 10 Batch Requests per second]'
  6898. WHEN [counter_name] = 'SQL Re-Compilations/sec' AND [counter_calculated_threshold_value] > 10 THEN '[WARNING: A ratio of more than 1 SQL Re-Compilation for every 10 SQL Compilations]'
  6899. WHEN [counter_calculated_threshold_value] IS NULL THEN NULL
  6900. ELSE '[OK]' END AS [Deviation]
  6901. FROM ctectr
  6902. ORDER BY [counter_family],[counter_name],[counter_instance];
  6903. IF @sqlmajorver >= 11
  6904. BEGIN
  6905. SELECT 'Performance_checks' AS [Category], 'Perf_Counters' AS [Information], [counter_name] AS Counter_name, "CPU Time:Total(ms)", "CPU Time:Requests", "Elapsed Time:Total(ms)", "Elapsed Time:Requests"
  6906. FROM (SELECT [counter_name],[instance_name],[cntr_value] FROM #tblPerfCount WHERE [object_name] LIKE '%Batch Resp Statistics%') AS pc
  6907. PIVOT(AVG([cntr_value]) FOR [instance_name]
  6908. IN ("CPU Time:Total(ms)", "CPU Time:Requests", "Elapsed Time:Total(ms)", "Elapsed Time:Requests")
  6909. ) AS Pvt;
  6910. END
  6911. ;WITH cteWaits1 (wait_type,wait_time_ms,signal_wait_time_ms,resource_wait_time_ms) AS (SELECT wait_type,wait_time_ms,signal_wait_time_ms,resource_wait_time_ms FROM #tblWaits WHERE [retrieval_time] = @minctr),
  6912. cteWaits2 (wait_type,wait_time_ms,signal_wait_time_ms,resource_wait_time_ms) AS (SELECT wait_type,wait_time_ms,signal_wait_time_ms,resource_wait_time_ms FROM #tblWaits WHERE [retrieval_time] = @maxctr)
  6913. INSERT INTO #tblFinalWaits
  6914. SELECT DISTINCT t1.wait_type, (t2.wait_time_ms-t1.wait_time_ms) / 1000. AS wait_time_s,
  6915. (t2.signal_wait_time_ms-t1.signal_wait_time_ms) / 1000. AS signal_wait_time_s,
  6916. ((t2.wait_time_ms-t2.signal_wait_time_ms)-(t1.wait_time_ms-t1.signal_wait_time_ms)) / 1000. AS resource_wait_time_s,
  6917. 100.0 * (t2.wait_time_ms-t1.wait_time_ms) / SUM(t2.wait_time_ms-t1.wait_time_ms) OVER() AS pct,
  6918. ROW_NUMBER() OVER(ORDER BY (t2.wait_time_ms-t1.wait_time_ms) DESC) AS rn,
  6919. SUM(t2.signal_wait_time_ms-t1.signal_wait_time_ms) * 1.0 / SUM(t2.wait_time_ms-t1.wait_time_ms) * 100 AS signal_wait_pct,
  6920. (SUM(t2.wait_time_ms-t2.signal_wait_time_ms)-SUM(t1.wait_time_ms-t1.signal_wait_time_ms)) * 1.0 / (SUM(t2.wait_time_ms)-SUM(t1.wait_time_ms)) * 100 AS resource_wait_pct
  6921. FROM cteWaits1 t1 INNER JOIN cteWaits2 t2 ON t1.wait_type = t2.wait_type
  6922. GROUP BY t1.wait_type, t1.wait_time_ms, t1.signal_wait_time_ms, t1.resource_wait_time_ms, t2.wait_time_ms, t2.signal_wait_time_ms, t2.resource_wait_time_ms
  6923. HAVING (t2.wait_time_ms-t1.wait_time_ms) > 0
  6924. ORDER BY wait_time_s DESC;
  6925. SELECT 'Performance_checks' AS [Category], 'Waits_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], W1.wait_type,
  6926. CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s,
  6927. CAST(W1.signal_wait_time_s AS DECIMAL(12, 2)) AS signal_wait_time_s,
  6928. CAST(W1.resource_wait_time_s AS DECIMAL(12, 2)) AS resource_wait_time_s,
  6929. CAST(W1.pct AS DECIMAL(12, 2)) AS pct,
  6930. CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  6931. CAST(W1.signal_wait_pct AS DECIMAL(12, 2)) AS signal_wait_pct,
  6932. CAST(W1.resource_wait_pct AS DECIMAL(12, 2)) AS resource_wait_pct,
  6933. CASE WHEN W1.wait_type LIKE N'LCK_%' OR W1.wait_type = N'LOCK' THEN N'Lock'
  6934. WHEN W1.wait_type LIKE N'LATCH_%' THEN N'Latch'
  6935. WHEN W1.wait_type LIKE N'PAGELATCH_%' THEN N'Buffer Latch'
  6936. WHEN W1.wait_type LIKE N'PAGEIOLATCH_%' THEN N'Buffer IO'
  6937. WHEN W1.wait_type LIKE N'HADR_SYNC_COMMIT' THEN N'AlwaysOn - Secondary Synch'
  6938. WHEN W1.wait_type LIKE N'HADR_%' THEN N'AlwaysOn'
  6939. WHEN W1.wait_type LIKE N'FFT_%' THEN N'FileTable'
  6940. WHEN W1.wait_type LIKE N'PREEMPTIVE_%' THEN N'External APIs or XPs' -- Used to indicate a worker is running code that is not under the SQLOS Scheduling;
  6941. WHEN W1.wait_type IN (N'IO_COMPLETION', N'ASYNC_IO_COMPLETION', /*N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',*/ N'DISKIO_SUSPEND') THEN N'Other IO'
  6942. WHEN W1.wait_type IN(N'BACKUPIO', N'BACKUPBUFFER') THEN 'Backup IO'
  6943. WHEN W1.wait_type = N'THREADPOOL' THEN 'CPU - Unavailable Worker Threads'
  6944. WHEN W1.wait_type = N'SOS_SCHEDULER_YIELD' THEN N'CPU - Scheduler Yielding'
  6945. WHEN W1.wait_type IN (N'CXPACKET', N'EXCHANGE') THEN N'CPU - Parallelism'
  6946. WHEN W1.wait_type IN (N'LOGMGR', N'LOGBUFFER', N'LOGMGR_RESERVE_APPEND', N'LOGMGR_FLUSH', N'WRITELOG') THEN N'Logging'
  6947. WHEN W1.wait_type IN (N'NET_WAITFOR_PACKET',N'NETWORK_IO') THEN N'Network IO'
  6948. WHEN W1.wait_type = N'ASYNC_NETWORK_IO' THEN N'Client Network IO'
  6949. WHEN W1.wait_type IN (N'UTIL_PAGE_ALLOC',N'SOS_VIRTUALMEMORY_LOW',N'CMEMTHREAD', N'SOS_RESERVEDMEMBLOCKLIST') THEN N'Memory'
  6950. WHEN W1.wait_type IN (N'RESOURCE_SEMAPHORE_SMALL_QUERY', N'RESOURCE_SEMAPHORE') THEN N'Memory - Hash or Sort'
  6951. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Memory - Compilation'
  6952. WHEN W1.wait_type LIKE N'CLR_%' OR W1.wait_type LIKE N'SQLCLR%' THEN N'CLR'
  6953. WHEN W1.wait_type LIKE N'DBMIRROR%' OR W1.wait_type = N'MIRROR_SEND_MESSAGE' THEN N'Mirroring'
  6954. WHEN W1.wait_type LIKE N'XACT%' OR W1.wait_type LIKE N'DTC_%' OR W1.wait_type LIKE N'TRAN_MARKLATCH_%' OR W1.wait_type LIKE N'MSQL_XACT_%' OR W1.wait_type = N'TRANSACTION_MUTEX' THEN N'Transaction'
  6955. -- WHEN W1.wait_type LIKE N'SLEEP_%' OR W1.wait_type IN(N'LAZYWRITER_SLEEP', N'SQLTRACE_BUFFER_FLUSH', N'WAITFOR', N'WAIT_FOR_RESULTS', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SLEEP_TASK', N'SLEEP_SYSTEMTASK') THEN N'Sleep'
  6956. WHEN W1.wait_type LIKE N'FT_%' THEN N'Full Text'
  6957. WHEN W1.wait_type = N'REPLICA_WRITE' THEN 'Snapshots'
  6958. ELSE N'Other' END AS 'wait_category'
  6959. FROM #tblFinalWaits AS W1 INNER JOIN #tblFinalWaits AS W2 ON W2.rn <= W1.rn
  6960. GROUP BY W1.rn, W1.wait_type, W1.wait_time_s, W1.pct, W1.signal_wait_time_s, W1.resource_wait_time_s, W1.signal_wait_pct, W1.resource_wait_pct
  6961. HAVING W1.wait_time_s >= 0.01 AND (SUM(W2.pct)-W1.pct) < 100 -- percentage threshold
  6962. ORDER BY W1.rn;
  6963. ;WITH Waits AS
  6964. (SELECT wait_type, wait_time_ms / 1000. AS wait_time_s,
  6965. signal_wait_time_ms / 1000. AS signal_wait_time_s,
  6966. (wait_time_ms-signal_wait_time_ms) / 1000. AS resource_wait_time_s,
  6967. SUM(signal_wait_time_ms) * 1.0 / SUM(wait_time_ms) * 100 AS signal_wait_pct,
  6968. SUM(wait_time_ms-signal_wait_time_ms) * 1.0 / SUM(wait_time_ms) * 100 AS resource_wait_pct,
  6969. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  6970. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  6971. FROM sys.dm_os_wait_stats
  6972. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP'
  6973. , 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT'
  6974. ,'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH'
  6975. ,'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6976. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6977. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6978. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6979. AND wait_type NOT LIKE N'SLEEP_%'
  6980. GROUP BY wait_type, wait_time_ms, signal_wait_time_ms)
  6981. SELECT 'Performance_checks' AS [Category], 'Cumulative_Waits' AS [Information], W1.wait_type,
  6982. CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s,
  6983. CAST(W1.signal_wait_time_s AS DECIMAL(12, 2)) AS signal_wait_time_s,
  6984. CAST(W1.resource_wait_time_s AS DECIMAL(12, 2)) AS resource_wait_time_s,
  6985. CAST(W1.pct AS DECIMAL(12, 2)) AS pct,
  6986. CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  6987. CAST(W1.signal_wait_pct AS DECIMAL(12, 2)) AS signal_wait_pct,
  6988. CAST(W1.resource_wait_pct AS DECIMAL(12, 2)) AS resource_wait_pct,
  6989. CASE WHEN W1.wait_type LIKE N'LCK_%' OR W1.wait_type = N'LOCK' THEN N'Lock'
  6990. -- LATCH = indicates contention for access to some non-page structures. ACCESS_METHODS_DATASET_PARENT, ACCESS_METHODS_SCAN_RANGE_GENERATOR or NESTING_TRANSACTION_FULL latches indicate parallelism issues;
  6991. WHEN W1.wait_type LIKE N'LATCH_%' THEN N'Latch'
  6992. -- PAGELATCH = indicates contention for access to in-memory copies of pages, like PFS, SGAM and GAM;
  6993. -- PAGELATCH_UP = Does the filegroup have enough files? Contention in PFS?
  6994. -- PAGELATCH_EX = Contention while doing many UPDATE statements against small tables?
  6995. -- PAGELATCH_EX = Many concurrent INSERT statements into a table that has an index on an IDENTITY or NEWSEQUENTIALID column? -> http://blogs.msdn.com/b/blogdoezequiel/archive/2013/05/23/pagelatch-ex-waits-and-heavy-inserts.aspx
  6996. WHEN W1.wait_type LIKE N'PAGELATCH_%' THEN N'Buffer Latch'
  6997. -- PAGEIOLATCH = indicates IO problems, or BP pressure.
  6998. WHEN W1.wait_type LIKE N'PAGEIOLATCH_%' THEN N'Buffer IO'
  6999. WHEN W1.wait_type LIKE N'HADR_SYNC_COMMIT' THEN N'AlwaysOn - Secondary Synch'
  7000. WHEN W1.wait_type LIKE N'HADR_%' THEN N'AlwaysOn'
  7001. WHEN W1.wait_type LIKE N'FFT_%' THEN N'FileTable'
  7002. -- PREEMPTIVE_OS_WRITEFILEGATHERER (2008+) = usually autogrow scenarios, usually together with WRITELOG;
  7003. WHEN W1.wait_type LIKE N'PREEMPTIVE_%' THEN N'External APIs or XPs' -- Used to indicate a worker is running code that is not under the SQLOS Scheduling;
  7004. -- IO_COMPLETION = usually TempDB spilling;
  7005. -- ASYNC_IO_COMPLETION = usually when not using IFI, or waiting on backups.
  7006. -- DISKIO_SUSPEND = High wait times here indicate the SNAPSHOT BACKUP may be taking longer than expected. Typically the delay is within the VDI application perform the snapshot backup;
  7007. WHEN W1.wait_type IN (N'IO_COMPLETION', N'ASYNC_IO_COMPLETION', /*N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',*/ N'DISKIO_SUSPEND') THEN N'Other IO'
  7008. -- BACKUPIO = check for slow backup media slow, like Tapes or Disks;
  7009. -- BACKUPBUFFER = usually when backing up to Tape;
  7010. WHEN W1.wait_type IN(N'BACKUPIO', N'BACKUPBUFFER') THEN 'Backup IO'
  7011. -- THREADPOOL = Look for high blocking or contention problems with workers. This will not show up in sys.dm_exec_requests;
  7012. WHEN W1.wait_type = N'THREADPOOL' THEN 'CPU - Unavailable Worker Threads'
  7013. -- SOS_SCHEDULER_YIELD = Might indicate CPU pressure if very high overall percentage. Check yielding conditions in http://technet.microsoft.com/en-us/library/cc917684.aspx
  7014. WHEN W1.wait_type = N'SOS_SCHEDULER_YIELD' THEN N'CPU - Scheduler Yielding'
  7015. -- Check sys.dm_os_waiting_tasks for Exchange wait types in http://technet.microsoft.com/en-us/library/ms188743.aspx;
  7016. -- Wait Resource e_waitPipeNewRow in CXPACKET waits Producer waiting on consumer for a packet to fill;
  7017. -- Wait Resource e_waitPipeGetRow in CXPACKET waits Consumer waiting on producer to fill a packet;
  7018. -- CXPACKET = if OLTP, check for parallelism issues if above 20 pct. If combined with a high number of PAGEIOLATCH_XX waits, it could be large parallel table scans going on because of incorrect non-clustered indexes, or out-of-date statistics causing a bad query plan;
  7019. WHEN W1.wait_type IN (N'CXPACKET', N'EXCHANGE') THEN N'CPU - Parallelism'
  7020. -- WRITELOG = log management system waiting for a log flush to disk. Examine the IO latency for the log file
  7021. WHEN W1.wait_type IN (N'LOGMGR', N'LOGBUFFER', N'LOGMGR_RESERVE_APPEND', N'LOGMGR_FLUSH', N'WRITELOG') THEN N'Logging'
  7022. WHEN W1.wait_type IN (N'NET_WAITFOR_PACKET',N'NETWORK_IO') THEN N'Network IO'
  7023. WHEN W1.wait_type = N'ASYNC_NETWORK_IO' THEN N'Client Network IO'
  7024. -- CMEMTHREAD = indicates that the rate of insertion of entries into the plan cache is very high and there is contention -> http://blogs.msdn.com/b/psssql/archive/2012/12/20/how-it-works-cmemthread-and-debugging-them.aspx
  7025. -- SOS_RESERVEDMEMBLOCKLIST = look for procedures with a large number of parameters, or queries with a long list of expression values specified in an IN clause, which would require multi-page allocations
  7026. WHEN W1.wait_type IN (N'UTIL_PAGE_ALLOC',N'SOS_VIRTUALMEMORY_LOW',N'CMEMTHREAD', N'SOS_RESERVEDMEMBLOCKLIST') THEN N'Memory'
  7027. -- RESOURCE_SEMAPHORE_SMALL_QUERY or RESOURCE_SEMAPHORE = queries are waiting for execution memory. Look for plans with excessive hashing or sorts.
  7028. WHEN W1.wait_type IN (N'RESOURCE_SEMAPHORE_SMALL_QUERY', N'RESOURCE_SEMAPHORE') THEN N'Memory - Hash or Sort'
  7029. -- RESOURCE_SEMAPHORE_QUERY_COMPILE = usually high compilation or recompilation scenario (higher ratio of prepared plans vs. compiled plans). On x64 usually memory hungry queries and compiles. On x86 perhaps short on VAS. -> http://technet.microsoft.com/en-us/library/cc293620.aspx
  7030. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Memory - Compilation'
  7031. WHEN W1.wait_type LIKE N'CLR_%' OR W1.wait_type LIKE N'SQLCLR%' THEN N'CLR'
  7032. -- DBMIRROR_DBM_MUTEX = indicates contention for the send buffer that database mirroring shares between all the mirroring sessions.
  7033. WHEN W1.wait_type LIKE N'DBMIRROR%' OR W1.wait_type = N'MIRROR_SEND_MESSAGE' THEN N'Mirroring'
  7034. -- RESOURCE_SEMAPHORE_QUERY_COMPILE = usually high compilation or recompilation scenario (higher ratio of prepared plans vs. compiled plans). On x64 usually memory hungry queries and compiles. On x86 perhaps short on VAS.
  7035. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Compilation'
  7036. WHEN W1.wait_type LIKE N'XACT%' OR W1.wait_type LIKE N'DTC_%' OR W1.wait_type LIKE N'TRAN_MARKLATCH_%' OR W1.wait_type LIKE N'MSQL_XACT_%' OR W1.wait_type = N'TRANSACTION_MUTEX' THEN N'Transaction'
  7037. -- WHEN W1.wait_type LIKE N'SLEEP_%' OR W1.wait_type IN(N'LAZYWRITER_SLEEP', N'SQLTRACE_BUFFER_FLUSH', N'WAITFOR', N'WAIT_FOR_RESULTS', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SLEEP_TASK', N'SLEEP_SYSTEMTASK') THEN N'Sleep'
  7038. WHEN W1.wait_type LIKE N'FT_%' THEN N'Full Text'
  7039. WHEN W1.wait_type = N'REPLICA_WRITE' THEN 'Snapshots'
  7040. ELSE N'Other' END AS 'wait_category'
  7041. FROM Waits AS W1 INNER JOIN Waits AS W2 ON W2.rn <= W1.rn
  7042. GROUP BY W1.rn, W1.wait_type, W1.wait_time_s, W1.pct, W1.signal_wait_time_s, W1.resource_wait_time_s, W1.signal_wait_pct, W1.resource_wait_pct
  7043. HAVING W1.wait_time_s >= 0.01 AND (SUM(W2.pct)-W1.pct) < 100 -- percentage threshold
  7044. ORDER BY W1.rn;
  7045. ;WITH cteLatches1 (latch_class,wait_time_ms,waiting_requests_count) AS (SELECT latch_class,wait_time_ms,waiting_requests_count FROM #tblLatches WHERE [retrieval_time] = @minctr),
  7046. cteLatches2 (latch_class,wait_time_ms,waiting_requests_count) AS (SELECT latch_class,wait_time_ms,waiting_requests_count FROM #tblLatches WHERE [retrieval_time] = @maxctr)
  7047. INSERT INTO #tblFinalLatches
  7048. SELECT DISTINCT t1.latch_class,
  7049. (t2.wait_time_ms-t1.wait_time_ms) / 1000.0 AS wait_time_s,
  7050. (t2.waiting_requests_count-t1.waiting_requests_count) AS waiting_requests_count,
  7051. 100.0 * (t2.wait_time_ms-t1.wait_time_ms) / SUM(t2.wait_time_ms-t1.wait_time_ms) OVER() AS pct,
  7052. ROW_NUMBER() OVER(ORDER BY t1.wait_time_ms DESC) AS rn
  7053. FROM cteLatches1 t1 INNER JOIN cteLatches2 t2 ON t1.latch_class = t2.latch_class
  7054. GROUP BY t1.latch_class, t1.wait_time_ms, t2.wait_time_ms, t1.waiting_requests_count, t2.waiting_requests_count
  7055. HAVING (t2.wait_time_ms-t1.wait_time_ms) > 0
  7056. ORDER BY wait_time_s DESC;
  7057. SELECT 'Performance_checks' AS [Category], 'Latches_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], W1.latch_class,
  7058. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7059. W1.waiting_requests_count,
  7060. CAST (W1.pct AS DECIMAL(14, 2)) AS pct,
  7061. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7062. CAST ((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7063. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7064. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7065. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7066. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7067. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7068. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7069. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7070. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER' THEN N'[Parallelism - DBCC CHECK_]'
  7071. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7072. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION' THEN N'[Mirroring - Busy]'
  7073. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7074. ELSE N'[Other]' END AS 'latch_category'
  7075. FROM #tblFinalLatches AS W1 INNER JOIN #tblFinalLatches AS W2 ON W2.rn <= W1.rn
  7076. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7077. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7078. ;WITH Latches AS
  7079. (SELECT latch_class,
  7080. wait_time_ms / 1000.0 AS wait_time_s,
  7081. waiting_requests_count,
  7082. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  7083. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  7084. FROM sys.dm_os_latch_stats
  7085. WHERE /*latch_class NOT IN ('BUFFER')
  7086. AND*/ wait_time_ms > 0
  7087. )
  7088. SELECT 'Performance_checks' AS [Category], 'Cumulative_Latches' AS [Information], W1.latch_class,
  7089. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7090. W1.waiting_requests_count,
  7091. CAST(W1.pct AS DECIMAL(14, 2)) AS pct,
  7092. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7093. CAST((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7094. -- ACCESS_METHODS_HOBT_VIRTUAL_ROOT = This latch is used to access the metadata for an index that contains the page ID of the index's root page. Contention on this latch can occur when a B-tree root page split occurs (requiring the latch in EX mode) and threads wanting to navigate down the B-tree (requiring the latch in SH mode) have to wait. This could be from very fast population of a small index using many concurrent connections, with or without page splits from random key values causing cascading page splits (from leaf to root).
  7095. -- ACCESS_METHODS_HOBT_COUNT = This latch is used to flush out page and row count deltas for a HoBt (Heap-or-B-tree) to the Storage Engine metadata tables. Contention would indicate *lots* of small, concurrent DML operations on a single table.
  7096. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7097. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7098. -- ACCESS_METHODS_DATASET_PARENT and ACCESS_METHODS_SCAN_RANGE_GENERATOR = These two latches are used during parallel scans to give each thread a range of page IDs to scan. The LATCH_XX waits for these latches will typically appear with CXPACKET waits and PAGEIOLATCH_XX waits (if the data being scanned is not memory-resident). Use normal parallelism troubleshooting methods to investigate further (e.g. is the parallelism warranted? maybe increase 'cost threshold for parallelism', lower MAXDOP, use a MAXDOP hint, use Resource Governor to limit DOP using a workload group with a MAX_DOP limit. Did a plan change from index seeks to parallel table scans because a tipping point was reached or a plan recompiled with an atypical SP parameter or poor statistics? Do NOT knee-jerk and set server MAXDOP to 1 – that's some of the worst advice I see on the Internet.);
  7099. -- NESTING_TRANSACTION_FULL = This latch, along with NESTING_TRANSACTION_READONLY, is used to control access to transaction description structures (called an XDES) for parallel nested transactions. The _FULL is for a transaction that's 'active', i.e. it's changed the database (usually for an index build/rebuild), and that makes the _READONLY description obvious. A query that involves a parallel operator must start a sub-transaction for each parallel thread that is used – these transactions are sub-transactions of the parallel nested transaction. For contention on these, I'd investigate unwanted parallelism but I don't have a definite "it's usually this problem". Also check out the comments for some info about these also sometimes being a problem when RCSI is used.
  7100. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7101. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7102. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7103. -- LOG_MANAGER = you see this latch it is almost certainly because a transaction log is growing because it could not clear/truncate for some reason. Find the database where the log is growing and then figure out what's preventing log clearing using sys.databases.
  7104. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7105. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7106. -- DBCC_MULTIOBJECT_SCANNER = This latch appears on Enterprise Edition when DBCC CHECK_ commands are allowed to run in parallel. It is used by threads to request the next data file page to process. Late last year this was identified as a major contention point inside DBCC CHECK* and there was work done to reduce the contention and make DBCC CHECK* run faster.
  7107. -- http://blogs.msdn.com/b/psssql/archive/2012/02/23/a-faster-checkdb-part-ii.aspx
  7108. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER ' THEN N'[Parallelism - DBCC CHECK_]'
  7109. -- FGCB_ADD_REMOVE = FGCB stands for File Group Control Block. This latch is required whenever a file is added or dropped from the filegroup, whenever a file is grown (manually or automatically), when recalculating proportional-fill weightings, and when cycling through the files in the filegroup as part of round-robin allocation. If you're seeing this, the most common cause is that there's a lot of file auto-growth happening. It could also be from a filegroup with lots of file (e.g. the primary filegroup in tempdb) where there are thousands of concurrent connections doing allocations. The proportional-fill weightings are recalculated every 8192 allocations, so there's the possibility of a slowdown with frequent recalculations over many files.
  7110. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7111. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION ' THEN N'[Mirroring - Busy]'
  7112. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7113. ELSE N'Other' END AS 'latch_category'
  7114. FROM Latches AS W1
  7115. INNER JOIN Latches AS W2
  7116. ON W2.rn <= W1.rn
  7117. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7118. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7119. ;WITH Latches AS
  7120. (SELECT latch_class,
  7121. wait_time_ms / 1000.0 AS wait_time_s,
  7122. waiting_requests_count,
  7123. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  7124. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  7125. FROM sys.dm_os_latch_stats (NOLOCK)
  7126. WHERE latch_class NOT IN ('BUFFER')
  7127. AND wait_time_ms > 0
  7128. )
  7129. SELECT 'Performance_checks' AS [Category], 'Cumulative_Latches_wo_BUFFER' AS [Information], W1.latch_class,
  7130. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7131. W1.waiting_requests_count,
  7132. CAST(W1.pct AS DECIMAL(14, 2)) AS pct,
  7133. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7134. CAST((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7135. -- ACCESS_METHODS_HOBT_VIRTUAL_ROOT = This latch is used to access the metadata for an index that contains the page ID of the index's root page. Contention on this latch can occur when a B-tree root page split occurs (requiring the latch in EX mode) and threads wanting to navigate down the B-tree (requiring the latch in SH mode) have to wait. This could be from very fast population of a small index using many concurrent connections, with or without page splits from random key values causing cascading page splits (from leaf to root).
  7136. -- ACCESS_METHODS_HOBT_COUNT = This latch is used to flush out page and row count deltas for a HoBt (Heap-or-B-tree) to the Storage Engine metadata tables. Contention would indicate *lots* of small, concurrent DML operations on a single table.
  7137. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7138. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7139. -- ACCESS_METHODS_DATASET_PARENT and ACCESS_METHODS_SCAN_RANGE_GENERATOR = These two latches are used during parallel scans to give each thread a range of page IDs to scan. The LATCH_XX waits for these latches will typically appear with CXPACKET waits and PAGEIOLATCH_XX waits (if the data being scanned is not memory-resident). Use normal parallelism troubleshooting methods to investigate further (e.g. is the parallelism warranted? maybe increase 'cost threshold for parallelism', lower MAXDOP, use a MAXDOP hint, use Resource Governor to limit DOP using a workload group with a MAX_DOP limit. Did a plan change from index seeks to parallel table scans because a tipping point was reached or a plan recompiled with an atypical SP parameter or poor statistics? Do NOT knee-jerk and set server MAXDOP to 1 – that's some of the worst advice I see on the Internet.);
  7140. -- NESTING_TRANSACTION_FULL = This latch, along with NESTING_TRANSACTION_READONLY, is used to control access to transaction description structures (called an XDES) for parallel nested transactions. The _FULL is for a transaction that's 'active', i.e. it's changed the database (usually for an index build/rebuild), and that makes the _READONLY description obvious. A query that involves a parallel operator must start a sub-transaction for each parallel thread that is used – these transactions are sub-transactions of the parallel nested transaction. For contention on these, I'd investigate unwanted parallelism but I don't have a definite "it's usually this problem". Also check out the comments for some info about these also sometimes being a problem when RCSI is used.
  7141. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7142. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7143. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7144. -- LOG_MANAGER = you see this latch it is almost certainly because a transaction log is growing because it could not clear/truncate for some reason. Find the database where the log is growing and then figure out what's preventing log clearing using sys.databases.
  7145. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7146. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7147. -- DBCC_MULTIOBJECT_SCANNER = This latch appears on Enterprise Edition when DBCC CHECK_ commands are allowed to run in parallel. It is used by threads to request the next data file page to process. Late last year this was identified as a major contention point inside DBCC CHECK* and there was work done to reduce the contention and make DBCC CHECK* run faster.
  7148. -- http://blogs.msdn.com/b/psssql/archive/2012/02/23/a-faster-checkdb-part-ii.aspx
  7149. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER ' THEN N'[Parallelism - DBCC CHECK_]'
  7150. -- FGCB_ADD_REMOVE = FGCB stands for File Group Control Block. This latch is required whenever a file is added or dropped from the filegroup, whenever a file is grown (manually or automatically), when recalculating proportional-fill weightings, and when cycling through the files in the filegroup as part of round-robin allocation. If you're seeing this, the most common cause is that there's a lot of file auto-growth happening. It could also be from a filegroup with lots of file (e.g. the primary filegroup in tempdb) where there are thousands of concurrent connections doing allocations. The proportional-fill weightings are recalculated every 8192 allocations, so there's the possibility of a slowdown with frequent recalculations over many files.
  7151. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7152. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION ' THEN N'[Mirroring - Busy]'
  7153. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7154. ELSE N'Other' END AS 'latch_category'
  7155. FROM Latches AS W1
  7156. INNER JOIN Latches AS W2
  7157. ON W2.rn <= W1.rn
  7158. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7159. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7160. ;WITH cteSpinlocks1 AS (SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs FROM #tblSpinlocksBefore),
  7161. cteSpinlocks2 AS (SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs FROM #tblSpinlocksAfter)
  7162. INSERT INTO #tblFinalSpinlocks
  7163. SELECT DISTINCT t1.name,
  7164. (t2.collisions-t1.collisions) AS collisions,
  7165. (t2.spins-t1.spins) AS spins,
  7166. (t2.spins_per_collision-t1.spins_per_collision) AS spins_per_collision,
  7167. (t2.sleep_time-t1.sleep_time) AS sleep_time,
  7168. (t2.backoffs-t1.backoffs) AS backoffs,
  7169. 100.0 * (t2.spins-t1.spins) / SUM(t2.spins-t1.spins) OVER() AS spins_pct,
  7170. ROW_NUMBER() OVER(ORDER BY t2.spins DESC) AS rn
  7171. FROM cteSpinlocks1 t1 INNER JOIN cteSpinlocks2 t2 ON t1.name = t2.name
  7172. GROUP BY t1.name, t1.collisions, t2.collisions, t1.spins, t2.spins, t1.spins_per_collision, t2.spins_per_collision, t1.sleep_time, t2.sleep_time, t1.backoffs, t2.backoffs
  7173. HAVING (t2.spins-t1.spins) > 0
  7174. ORDER BY spins DESC;
  7175. SELECT 'Performance_checks' AS [Category], 'Spinlocks_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], S1.name,
  7176. S1.collisions, S1.spins, S1.spins_per_collision, S1.sleep_time, S1.backoffs,
  7177. CAST(S1.spins_pct AS DECIMAL(14, 2)) AS spins_pct,
  7178. CAST(SUM(S1.spins_pct) AS DECIMAL(12, 2)) AS overall_running_spins_pct
  7179. FROM #tblFinalSpinlocks AS S1 INNER JOIN #tblFinalSpinlocks AS S2 ON S2.rn <= S1.rn
  7180. GROUP BY S1.rn, S1.name, S1.collisions, S1.spins, S1.spins_per_collision, S1.sleep_time, S1.backoffs, S1.spins_pct
  7181. HAVING SUM(S2.spins_pct) - S1.spins_pct < 100 -- percentage threshold
  7182. ORDER BY spins DESC;
  7183. END;
  7184. --------------------------------------------------------------------------------------------------------------------------------
  7185. -- Worker thread exhaustion subsection
  7186. --------------------------------------------------------------------------------------------------------------------------------
  7187. IF @ptochecks = 1
  7188. BEGIN
  7189. RAISERROR (N' |-Starting Worker thread exhaustion', 10, 1) WITH NOWAIT
  7190. DECLARE @avgtskcnt int, @workqcnt int
  7191. SELECT @avgtskcnt = SUM(runnable_tasks_count)/COUNT(scheduler_id), @workqcnt = SUM(work_queue_count) FROM sys.dm_os_schedulers
  7192. WHERE parent_node_id < 64 AND scheduler_id < 255
  7193. IF @avgtskcnt <= 2 AND @workqcnt > 1
  7194. BEGIN
  7195. SELECT 'Performance_checks' AS [Category], 'Worker_thread_exhaustion' AS [Check], '[WARNING: Possible worker thread exhaustion (schedulers work queue count is ' + CONVERT(NVARCHAR(10), @workqcnt) + '). Because overall runnable tasks count is ' + CONVERT(NVARCHAR(10), @avgtskcnt) + ' (<= 2), indicating the server might not be CPU bound, there might be room to increase max_worker_threads]' AS [Deviation], '[Configured workers = ' + CONVERT(VARCHAR(10),@mwthreads_count) + ']' AS [Comment]
  7196. END
  7197. ELSE IF @avgtskcnt > 2 AND @workqcnt > 1
  7198. BEGIN
  7199. SELECT 'Performance_checks' AS [Category], 'Worker_thread_exhaustion' AS [Check], '[WARNING: Possible worker thread exhaustion (schedulers work queue count is ' + CONVERT(NVARCHAR(10), @workqcnt) + '). Overall runnable tasks count is ' + CONVERT(NVARCHAR(10), @avgtskcnt) + ' (> 2), also indicating the server might be CPU bound]' AS [Deviation], '[Configured workers = ' + CONVERT(VARCHAR(10),@mwthreads_count) + ']' AS [Comment]
  7200. END
  7201. ELSE
  7202. BEGIN
  7203. SELECT 'Performance_checks' AS [Category], 'Worker_thread_exhaustion' AS [Check], '[OK]' AS [Deviation], '' AS [Comment]
  7204. END
  7205. END;
  7206. --------------------------------------------------------------------------------------------------------------------------------
  7207. -- Blocking Chains subsection
  7208. -- Checks for blocking chains taking over 5s.
  7209. --------------------------------------------------------------------------------------------------------------------------------
  7210. IF @ptochecks = 1
  7211. BEGIN
  7212. RAISERROR (N' |-Starting Blocking Chains', 10, 1) WITH NOWAIT
  7213. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  7214. DROP TABLE #tblBlkChains;
  7215. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  7216. CREATE TABLE #tblBlkChains ([blocked_spid] [smallint], [blocked_spid_status] NVARCHAR(30), [blocked_task_status] NVARCHAR(60),
  7217. [blocked_spid_wait_type] NVARCHAR(60), [blocked_spid_wait_time_ms] [bigint], [blocked_spid_res_desc] NVARCHAR(1024),
  7218. [blocked_pageid] [int], [blocked_spid_res_type] VARCHAR(24), [blocked_batch] [xml], [blocked_statement] [xml],
  7219. [blocked_last_start] [datetime], [blocked_tran_isolation_level] VARCHAR(30), [blocker_spid] [smallint],
  7220. [is_head_blocker] [int], [blocker_batch] [xml], [blocker_statement] [xml], [blocker_last_start] [datetime],
  7221. [blocker_tran_isolation_level] VARCHAR(30), [blocked_database] NVARCHAR(128), [blocked_host] NVARCHAR(128),
  7222. [blocked_program] NVARCHAR(128), [blocked_login] NVARCHAR(128), [blocked_session_comment] VARCHAR(25),
  7223. [blocked_is_user_process] [bit], [blocker_database] NVARCHAR(128), [blocker_host] NVARCHAR(128),
  7224. [blocker_program] NVARCHAR(128), [blocker_login] NVARCHAR(128), [blocker_session_comment] VARCHAR(25), [blocker_is_user_process] [bit])
  7225. INSERT INTO #tblBlkChains
  7226. SELECT
  7227. -- blocked
  7228. es.session_id AS blocked_spid,
  7229. es.[status] AS [blocked_spid_status],
  7230. ot.task_state AS [blocked_task_status],
  7231. owt.wait_type AS blocked_spid_wait_type,
  7232. COALESCE(owt.wait_duration_ms, ABS(CONVERT(BIGINT,(DATEDIFF(mi, es.last_request_start_time, GETDATE())))*60)) AS blocked_spid_wait_time_ms,
  7233. --er.total_elapsed_time AS blocked_elapsed_time_ms,
  7234. /*
  7235. Check sys.dm_os_waiting_tasks for Exchange wait types in http://technet.microsoft.com/en-us/library/ms188743.aspx.
  7236. - Wait Resource e_waitPipeNewRow in CXPACKET waits – Producer waiting on consumer for a packet to fill.
  7237. - Wait Resource e_waitPipeGetRow in CXPACKET waits – Consumer waiting on producer to fill a packet.
  7238. */
  7239. owt.resource_description AS blocked_spid_res_desc,
  7240. owt.pageid AS blocked_pageid,
  7241. CASE WHEN owt.pageid = 1 OR owt.pageid % 8088 = 0 THEN 'Is_PFS_Page'
  7242. WHEN owt.pageid = 2 OR owt.pageid % 511232 = 0 THEN 'Is_GAM_Page'
  7243. WHEN owt.pageid = 3 OR (owt.pageid - 1) % 511232 = 0 THEN 'Is_SGAM_Page'
  7244. WHEN owt.pageid IS NULL THEN NULL
  7245. ELSE 'Is_not_PFS_GAM_SGAM_page' END AS blocked_spid_res_type,
  7246. (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7247. qt.[text],
  7248. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7249. AS [text()]
  7250. FROM sys.dm_exec_sql_text(COALESCE(er.sql_handle, ec.most_recent_sql_handle)) AS qt
  7251. FOR XML PATH(''), TYPE) AS [blocked_batch],
  7252. (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7253. SUBSTRING(qt2.text,
  7254. (CASE WHEN er.statement_start_offset = 0 THEN 0 ELSE er.statement_start_offset/2 END),
  7255. (CASE WHEN er.statement_end_offset = -1 THEN DATALENGTH(qt2.text) ELSE er.statement_end_offset/2 END - (CASE WHEN er.statement_start_offset = 0 THEN 0 ELSE er.statement_start_offset/2 END))),
  7256. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7257. AS [text()]
  7258. FROM sys.dm_exec_sql_text(COALESCE(er.sql_handle, ec.most_recent_sql_handle)) AS qt2
  7259. FOR XML PATH(''), TYPE) AS [blocked_statement],
  7260. es.last_request_start_time AS blocked_last_start,
  7261. LEFT (CASE COALESCE(es.transaction_isolation_level, er.transaction_isolation_level)
  7262. WHEN 0 THEN '0-Unspecified'
  7263. WHEN 1 THEN '1-ReadUncommitted(NOLOCK)'
  7264. WHEN 2 THEN '2-ReadCommitted'
  7265. WHEN 3 THEN '3-RepeatableRead'
  7266. WHEN 4 THEN '4-Serializable'
  7267. WHEN 5 THEN '5-Snapshot'
  7268. ELSE CONVERT (VARCHAR(30), COALESCE(es.transaction_isolation_level, er.transaction_isolation_level)) + '-UNKNOWN'
  7269. END, 30) AS blocked_tran_isolation_level,
  7270. -- blocker
  7271. er.blocking_session_id As blocker_spid,
  7272. CASE
  7273. -- session has an active request, is blocked, but is blocking others or session is idle but has an open tran and is blocking others
  7274. WHEN (er2.session_id IS NULL OR owt.blocking_session_id IS NULL) AND (er.blocking_session_id = 0 OR er.session_id IS NULL) THEN 1
  7275. -- session is either not blocking someone, or is blocking someone but is blocked by another party
  7276. ELSE 0
  7277. END AS is_head_blocker,
  7278. (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7279. qt2.[text],
  7280. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7281. AS [text()]
  7282. FROM sys.dm_exec_sql_text(COALESCE(er2.sql_handle, ec2.most_recent_sql_handle)) AS qt2
  7283. FOR XML PATH(''), TYPE) AS [blocker_batch],
  7284. (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7285. SUBSTRING(qt2.text,
  7286. (CASE WHEN er2.statement_start_offset = 0 THEN 0 ELSE er2.statement_start_offset/2 END),
  7287. (CASE WHEN er2.statement_end_offset = -1 THEN DATALENGTH(qt2.text) ELSE er2.statement_end_offset/2 END - (CASE WHEN er2.statement_start_offset = 0 THEN 0 ELSE er2.statement_start_offset/2 END))),
  7288. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7289. AS [text()]
  7290. FROM sys.dm_exec_sql_text(COALESCE(er2.sql_handle, ec2.most_recent_sql_handle)) AS qt2
  7291. FOR XML PATH(''), TYPE) AS [blocker_statement],
  7292. es2.last_request_start_time AS blocker_last_start,
  7293. LEFT (CASE COALESCE(er2.transaction_isolation_level, es.transaction_isolation_level)
  7294. WHEN 0 THEN '0-Unspecified'
  7295. WHEN 1 THEN '1-ReadUncommitted(NOLOCK)'
  7296. WHEN 2 THEN '2-ReadCommitted'
  7297. WHEN 3 THEN '3-RepeatableRead'
  7298. WHEN 4 THEN '4-Serializable'
  7299. WHEN 5 THEN '5-Snapshot'
  7300. ELSE CONVERT (VARCHAR(30), COALESCE(er2.transaction_isolation_level, es.transaction_isolation_level)) + '-UNKNOWN'
  7301. END, 30) AS blocker_tran_isolation_level,
  7302. -- blocked - other data
  7303. DB_NAME(er.database_id) AS blocked_database,
  7304. es.[host_name] AS blocked_host,
  7305. es.[program_name] AS blocked_program,
  7306. es.login_name AS blocked_login,
  7307. CASE WHEN es.session_id = -2 THEN 'Orphaned_distributed_tran'
  7308. WHEN es.session_id = -3 THEN 'Defered_recovery_tran'
  7309. WHEN es.session_id = -4 THEN 'Unknown_tran' ELSE NULL END AS blocked_session_comment,
  7310. es.is_user_process AS [blocked_is_user_process],
  7311. -- blocker - other data
  7312. DB_NAME(er2.database_id) AS blocker_database,
  7313. es2.[host_name] AS blocker_host,
  7314. es2.[program_name] AS blocker_program,
  7315. es2.login_name AS blocker_login,
  7316. CASE WHEN es2.session_id = -2 THEN 'Orphaned_distributed_tran'
  7317. WHEN es2.session_id = -3 THEN 'Defered_recovery_tran'
  7318. WHEN es2.session_id = -4 THEN 'Unknown_tran' ELSE NULL END AS blocker_session_comment,
  7319. es2.is_user_process AS [blocker_is_user_process]
  7320. FROM sys.dm_exec_sessions es
  7321. LEFT OUTER JOIN sys.dm_exec_requests er ON es.session_id = er.session_id
  7322. LEFT OUTER JOIN sys.dm_exec_connections ec ON es.session_id = ec.session_id
  7323. LEFT OUTER JOIN sys.dm_os_tasks ot ON er.session_id = ot.session_id AND er.request_id = ot.request_id
  7324. LEFT OUTER JOIN sys.dm_exec_sessions es2 ON er.blocking_session_id = es2.session_id
  7325. LEFT OUTER JOIN sys.dm_exec_requests er2 ON es2.session_id = er2.session_id
  7326. LEFT OUTER JOIN sys.dm_exec_connections ec2 ON es2.session_id = ec2.session_id
  7327. LEFT OUTER JOIN
  7328. (
  7329. -- In some cases (e.g. parallel queries, also waiting for a worker), one thread can be flagged as
  7330. -- waiting for several different threads. This will cause that thread to show up in multiple rows
  7331. -- in our grid, which we don't want. Use ROW_NUMBER to select the longest wait for each thread,
  7332. -- and use it as representative of the other wait relationships this thread is involved in.
  7333. SELECT waiting_task_address, session_id, exec_context_id, wait_duration_ms,
  7334. wait_type, resource_address, blocking_task_address, blocking_session_id,
  7335. blocking_exec_context_id, resource_description,
  7336. CASE WHEN [wait_type] LIKE 'PAGE%' AND [resource_description] LIKE '%:%' THEN CAST(RIGHT([resource_description], LEN([resource_description]) - CHARINDEX(':', [resource_description], LEN([resource_description])-CHARINDEX(':', REVERSE([resource_description])))) AS int)
  7337. ELSE NULL END AS pageid,
  7338. ROW_NUMBER() OVER (PARTITION BY waiting_task_address ORDER BY wait_duration_ms DESC) AS row_num
  7339. FROM sys.dm_os_waiting_tasks
  7340. WHERE wait_type <> 'SP_SERVER_DIAGNOSTICS_SLEEP'
  7341. ) owt ON ot.task_address = owt.waiting_task_address AND owt.row_num = 1
  7342. --OUTER APPLY sys.dm_exec_sql_text (er.sql_handle) est
  7343. --OUTER APPLY sys.dm_exec_query_plan (er.plan_handle) eqp
  7344. WHERE es.session_id <> @@SPID AND es.is_user_process = 1
  7345. AND ((owt.wait_duration_ms/1000) > 5 OR (er.total_elapsed_time/1000) > 5 OR er.total_elapsed_time IS NULL) --Only report blocks > 5 Seconds plus head blocker
  7346. AND (es.session_id IN (SELECT er3.blocking_session_id FROM sys.dm_exec_requests er3) OR er.blocking_session_id IS NOT NULL)
  7347. ORDER BY blocked_spid, is_head_blocker DESC, blocked_spid_wait_time_ms DESC, blocker_spid;
  7348. IF (SELECT COUNT(blocked_spid) FROM #tblBlkChains WHERE CONVERT(VARCHAR(max), blocked_batch) <> 'sp_server_diagnostics') > 0
  7349. BEGIN
  7350. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Check], '[WARNING: Blocking chains in excess of 5s were found.]' AS [Deviation]
  7351. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Information],[blocked_spid],[blocked_spid_status],[blocked_task_status],
  7352. [blocked_spid_wait_type],[blocked_spid_wait_time_ms],[blocked_spid_res_desc],[blocked_pageid],[blocked_spid_res_type],
  7353. [blocked_batch],[blocked_statement],[blocked_last_start],[blocked_tran_isolation_level],[blocker_spid],[is_head_blocker],
  7354. [blocker_batch],[blocker_statement],[blocker_last_start],[blocker_tran_isolation_level],[blocked_database],
  7355. [blocked_host],[blocked_program],[blocked_login],[blocked_session_comment],[blocked_is_user_process],[blocker_database],
  7356. [blocker_host],[blocker_program],[blocker_login],[blocker_session_comment],[blocker_is_user_process]
  7357. FROM #tblBlkChains
  7358. END
  7359. ELSE
  7360. BEGIN
  7361. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Check], '[OK]' AS [Deviation]
  7362. END;
  7363. END;
  7364. --------------------------------------------------------------------------------------------------------------------------------
  7365. -- Plan use ratio subsection
  7366. --------------------------------------------------------------------------------------------------------------------------------
  7367. IF @ptochecks = 1
  7368. BEGIN
  7369. RAISERROR (N' |-Starting Plan use ratio', 10, 1) WITH NOWAIT
  7370. IF (SELECT SUM(CAST(size_in_bytes AS bigint))/1024/1024 AS Size_MB
  7371. FROM sys.dm_exec_cached_plans (NOLOCK)
  7372. WHERE cacheobjtype LIKE '%Plan%' AND usecounts = 1)
  7373. >=
  7374. (SELECT SUM(CAST(size_in_bytes AS bigint))/1024/1024 AS Size_MB
  7375. FROM sys.dm_exec_cached_plans (NOLOCK)
  7376. WHERE cacheobjtype LIKE '%Plan%' AND usecounts > 1)
  7377. BEGIN
  7378. SELECT 'Performance_checks' AS [Category], 'Plan_use_ratio' AS [Check], '[WARNING: Amount of single use plans in cache is high]' AS [Deviation], CASE WHEN @sqlmajorver > 9 AND @adhoc = 0 THEN '[Consider enabling the Optimize for ad hoc workloads setting on heavy OLTP ad-hoc workloads to conserve resources]' ELSE '' END AS [Comment]
  7379. END
  7380. ELSE
  7381. BEGIN
  7382. SELECT 'Performance_checks' AS [Category], 'Plan_use_ratio' AS [Check], '[OK]' AS [Deviation], '' AS [Comment]
  7383. END;
  7384. --High number of cached plans with usecounts = 1.
  7385. SELECT 'Performance_checks' AS [Category], 'Plan_use_ratio' AS [Information], objtype, cacheobjtype, AVG(CAST(usecounts AS bigint)) AS Avg_UseCount_perPlan, SUM(refcounts) AS AllRefObjects, SUM(CAST(size_in_bytes AS bigint))/1024/1024 AS Size_MB
  7386. FROM sys.dm_exec_cached_plans (NOLOCK)
  7387. WHERE cacheobjtype LIKE '%Plan%' AND usecounts = 1
  7388. GROUP BY objtype, cacheobjtype
  7389. UNION ALL
  7390. --High number of cached plans with usecounts > 1.
  7391. SELECT 'Performance_checks' AS [Category], 'Plan_use_ratio' AS [Information], objtype, cacheobjtype, AVG(CAST(usecounts AS bigint)) AS Avg_UseCount_perPlan, SUM(refcounts) AS AllRefObjects, SUM(CAST(size_in_bytes AS bigint))/1024/1024 AS Size_MB
  7392. FROM sys.dm_exec_cached_plans (NOLOCK)
  7393. WHERE cacheobjtype LIKE '%Plan%' AND usecounts > 1
  7394. GROUP BY objtype, cacheobjtype
  7395. ORDER BY objtype, cacheobjtype;
  7396. END;
  7397. --------------------------------------------------------------------------------------------------------------------------------
  7398. -- Hints usage subsection
  7399. -- Refer to "Hints" BOL entry for more information (http://msdn.microsoft.com/en-us/library/ms187713.aspx)
  7400. --------------------------------------------------------------------------------------------------------------------------------
  7401. IF @ptochecks = 1
  7402. BEGIN
  7403. RAISERROR (N' |-Starting Hints usage', 10, 1) WITH NOWAIT
  7404. IF (SELECT COUNT([counter]) FROM sys.dm_exec_query_optimizer_info WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1) > 0
  7405. BEGIN
  7406. RAISERROR (N' |-Hints are being used - finding usage in SQL modules', 10, 1) WITH NOWAIT
  7407. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  7408. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  7409. DROP TABLE #tblHints;
  7410. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  7411. CREATE TABLE #tblHints ([DBName] sysname, [Schema] VARCHAR(100), [Object] VARCHAR(255), [Type] VARCHAR(100), Hint VARCHAR(30));
  7412. UPDATE #tmpdbs0
  7413. SET isdone = 0;
  7414. UPDATE #tmpdbs0
  7415. SET isdone = 1
  7416. WHERE [state] <> 0 OR [dbid] < 5;
  7417. UPDATE #tmpdbs0
  7418. SET isdone = 1
  7419. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  7420. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  7421. BEGIN
  7422. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  7423. BEGIN
  7424. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  7425. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  7426. SELECT ''' + @dbname + ''' AS [DBName], ss.name AS [Schema_Name], so.name AS [Object_Name], so.type_desc,
  7427. CASE WHEN sm.[definition] LIKE ''%FORCE ORDER%'' THEN ''[FORCE ORDER Hint]''
  7428. WHEN sm.[definition] LIKE ''%MERGE JOIN%''
  7429. OR sm.[definition] LIKE ''%LOOP JOIN%''
  7430. OR sm.[definition] LIKE ''%HASH JOIN%'' THEN ''[JOIN Hint]'' END AS Hint
  7431. FROM sys.sql_modules sm
  7432. INNER JOIN sys.objects so ON sm.[object_id] = so.[object_id]
  7433. INNER JOIN sys.schemas ss ON so.[schema_id] = ss.[schema_id]
  7434. WHERE sm.[definition] LIKE ''%FORCE ORDER%''
  7435. OR sm.[definition] LIKE ''%MERGE JOIN%''
  7436. OR sm.[definition] LIKE ''%LOOP JOIN%''
  7437. OR sm.[definition] LIKE ''%HASH JOIN%'';'
  7438. BEGIN TRY
  7439. INSERT INTO #tblHints
  7440. EXECUTE sp_executesql @sqlcmd
  7441. END TRY
  7442. BEGIN CATCH
  7443. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  7444. SELECT @ErrorMessage = 'Hints usage subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  7445. RAISERROR (@ErrorMessage, 16, 1);
  7446. END CATCH
  7447. UPDATE #tmpdbs0
  7448. SET isdone = 1
  7449. WHERE [dbid] = @dbid
  7450. END
  7451. END;
  7452. SELECT 'Performance_checks' AS [Category], 'Hints_usage' AS [Check], '[WARNING: Hints are being used. These can hinder the QO ability to optimize queries]' AS [Deviation]
  7453. SELECT 'Performance_checks' AS [Category], 'Hints_usage' AS [Information], CASE WHEN [counter] = 'order hint' THEN '[FORCE ORDER Hint]' WHEN [counter] = 'join hint' THEN '[JOIN Hint]' END AS [Hint], occurrence
  7454. FROM sys.dm_exec_query_optimizer_info (NOLOCK)
  7455. WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1;
  7456. IF (SELECT COUNT(*) FROM #tblHints WHERE [DBName] IS NOT NULL) > 0
  7457. BEGIN
  7458. SELECT 'Performance_checks' AS [Category], 'Hints_usage_in_Objects' AS [Information], [DBName], [Schema], [Object], [Type], Hint, '' AS Comment
  7459. FROM #tblHints (NOLOCK)
  7460. ORDER BY [DBName], Hint, [Type], [Object];
  7461. END
  7462. ELSE
  7463. BEGIN
  7464. SELECT 'Performance_checks' AS [Category], 'Hints_usage_in_Objects' AS [Information], NULL AS [DBName], NULL AS [Schema], NULL AS [Object], NULL AS [Type],
  7465. CASE WHEN [counter] = 'order hint' THEN '[FORCE ORDER Hint]' WHEN [counter] = 'join hint' THEN '[JOIN Hint]' END AS [Hint], '[INFORMATION: Hints may be in use with ad-hoc code]' AS Comment
  7466. FROM sys.dm_exec_query_optimizer_info (NOLOCK)
  7467. WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1;
  7468. END
  7469. END
  7470. ELSE
  7471. BEGIN
  7472. SELECT 'Performance_checks' AS [Category], 'Hints_usage' AS [Check], '[OK]' AS [Deviation]
  7473. END
  7474. END;
  7475. --------------------------------------------------------------------------------------------------------------------------------
  7476. -- Cached Query Plans issues subsection
  7477. --------------------------------------------------------------------------------------------------------------------------------
  7478. IF @ptochecks = 1
  7479. BEGIN
  7480. RAISERROR (N' |-Starting Cached Query Plans issues', 10, 1) WITH NOWAIT
  7481. --DECLARE @sqlcmd NVARCHAR(max), @params NVARCHAR(500), @sqlmajorver int, @sqlminorver int, @sqlbuild int
  7482. --SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  7483. --SELECT @sqlminorver = CONVERT(int, (@@microsoftversion / 0x10000) & 0xff);
  7484. --SELECT @sqlbuild = CONVERT(int, @@microsoftversion & 0xffff);
  7485. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  7486. DROP TABLE #tmp_dm_exec_query_stats;
  7487. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  7488. CREATE TABLE #tmp_dm_exec_query_stats ([plan_id] [int] NOT NULL IDENTITY(1, 1),
  7489. [sql_handle] [varbinary](64) NOT NULL,
  7490. [statement_start_offset] [int] NOT NULL,
  7491. [statement_end_offset] [int] NOT NULL,
  7492. [plan_generation_num] [bigint] NOT NULL,
  7493. [plan_handle] [varbinary](64) NOT NULL,
  7494. [creation_time] [datetime] NOT NULL,
  7495. [last_execution_time] [datetime] NOT NULL,
  7496. [execution_count] [bigint] NOT NULL,
  7497. [total_worker_time] [bigint] NOT NULL,
  7498. [last_worker_time] [bigint] NOT NULL,
  7499. [min_worker_time] [bigint] NOT NULL,
  7500. [max_worker_time] [bigint] NOT NULL,
  7501. [total_physical_reads] [bigint] NOT NULL,
  7502. [last_physical_reads] [bigint] NOT NULL,
  7503. [min_physical_reads] [bigint] NOT NULL,
  7504. [max_physical_reads] [bigint] NOT NULL,
  7505. [total_logical_writes] [bigint] NOT NULL,
  7506. [last_logical_writes] [bigint] NOT NULL,
  7507. [min_logical_writes] [bigint] NOT NULL,
  7508. [max_logical_writes] [bigint] NOT NULL,
  7509. [total_logical_reads] [bigint] NOT NULL,
  7510. [last_logical_reads] [bigint] NOT NULL,
  7511. [min_logical_reads] [bigint] NOT NULL,
  7512. [max_logical_reads] [bigint] NOT NULL,
  7513. [total_clr_time] [bigint] NOT NULL,
  7514. [last_clr_time] [bigint] NOT NULL,
  7515. [min_clr_time] [bigint] NOT NULL,
  7516. [max_clr_time] [bigint] NOT NULL,
  7517. [total_elapsed_time] [bigint] NOT NULL,
  7518. [last_elapsed_time] [bigint] NOT NULL,
  7519. [min_elapsed_time] [bigint] NOT NULL,
  7520. [max_elapsed_time] [bigint] NOT NULL,
  7521. --2008 only
  7522. [query_hash] [binary](8) NULL,
  7523. [query_plan_hash] [binary](8) NULL,
  7524. --2008R2 only
  7525. [total_rows] bigint NULL,
  7526. [last_rows] bigint NULL,
  7527. [min_rows] bigint NULL,
  7528. [max_rows] bigint NULL,
  7529. --post 2012 SP3, 2014 SP2 and 2016
  7530. [Last_grant_kb] bigint NULL,
  7531. [Min_grant_kb] bigint NULL,
  7532. [Max_grant_kb] bigint NULL,
  7533. [Total_grant_kb] bigint NULL,
  7534. [Last_used_grant_kb] bigint NULL,
  7535. [Min_used_grant_kb] bigint NULL,
  7536. [Max_used_grant_kb] bigint NULL,
  7537. [Total_used_grant_kb] bigint NULL,
  7538. [Last_ideal_grant_kb] bigint NULL,
  7539. [Min_ideal_grant_kb] bigint NULL,
  7540. [Max_ideal_grant_kb] bigint NULL,
  7541. [Total_ideal_grant_kb] bigint NULL,
  7542. [Last_dop] bigint NULL,
  7543. [Min_dop] bigint NULL,
  7544. [Max_dop] bigint NULL,
  7545. [Total_dop] bigint NULL,
  7546. [Last_reserved_threads] bigint NULL,
  7547. [Min_reserved_threads] bigint NULL,
  7548. [Max_reserved_threads] bigint NULL,
  7549. [Total_reserved_threads] bigint NULL,
  7550. [Last_used_threads] bigint NULL,
  7551. [Min_used_threads] bigint NULL,
  7552. [Max_used_threads] bigint NULL,
  7553. [Total_used_threads] bigint NULL,
  7554. [Grant2Used_Ratio] float NULL)
  7555. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  7556. DROP TABLE #dm_exec_query_stats;
  7557. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  7558. CREATE TABLE #dm_exec_query_stats ([plan_id] [int] NOT NULL IDENTITY(1, 1),
  7559. [sql_handle] [varbinary](64) NOT NULL,
  7560. [statement_start_offset] [int] NOT NULL,
  7561. [statement_end_offset] [int] NOT NULL,
  7562. [plan_generation_num] [bigint] NOT NULL,
  7563. [plan_handle] [varbinary](64) NOT NULL,
  7564. [creation_time] [datetime] NOT NULL,
  7565. [last_execution_time] [datetime] NOT NULL,
  7566. [execution_count] [bigint] NOT NULL,
  7567. [total_worker_time] [bigint] NOT NULL,
  7568. [last_worker_time] [bigint] NOT NULL,
  7569. [min_worker_time] [bigint] NOT NULL,
  7570. [max_worker_time] [bigint] NOT NULL,
  7571. [total_physical_reads] [bigint] NOT NULL,
  7572. [last_physical_reads] [bigint] NOT NULL,
  7573. [min_physical_reads] [bigint] NOT NULL,
  7574. [max_physical_reads] [bigint] NOT NULL,
  7575. [total_logical_writes] [bigint] NOT NULL,
  7576. [last_logical_writes] [bigint] NOT NULL,
  7577. [min_logical_writes] [bigint] NOT NULL,
  7578. [max_logical_writes] [bigint] NOT NULL,
  7579. [total_logical_reads] [bigint] NOT NULL,
  7580. [last_logical_reads] [bigint] NOT NULL,
  7581. [min_logical_reads] [bigint] NOT NULL,
  7582. [max_logical_reads] [bigint] NOT NULL,
  7583. [total_clr_time] [bigint] NOT NULL,
  7584. [last_clr_time] [bigint] NOT NULL,
  7585. [min_clr_time] [bigint] NOT NULL,
  7586. [max_clr_time] [bigint] NOT NULL,
  7587. [total_elapsed_time] [bigint] NOT NULL,
  7588. [last_elapsed_time] [bigint] NOT NULL,
  7589. [min_elapsed_time] [bigint] NOT NULL,
  7590. [max_elapsed_time] [bigint] NOT NULL,
  7591. --2008 only
  7592. [query_hash] [binary](8) NULL,
  7593. [query_plan_hash] [binary](8) NULL,
  7594. --2008R2 only
  7595. [total_rows] bigint NULL,
  7596. [last_rows] bigint NULL,
  7597. [min_rows] bigint NULL,
  7598. [max_rows] bigint NULL,
  7599. --post 2012 SP3, 2014 SP2 and 2016
  7600. [Last_grant_kb] bigint NULL,
  7601. [Min_grant_kb] bigint NULL,
  7602. [Max_grant_kb] bigint NULL,
  7603. [Total_grant_kb] bigint NULL,
  7604. [Last_used_grant_kb] bigint NULL,
  7605. [Min_used_grant_kb] bigint NULL,
  7606. [Max_used_grant_kb] bigint NULL,
  7607. [Total_used_grant_kb] bigint NULL,
  7608. [Last_ideal_grant_kb] bigint NULL,
  7609. [Min_ideal_grant_kb] bigint NULL,
  7610. [Max_ideal_grant_kb] bigint NULL,
  7611. [Total_ideal_grant_kb] bigint NULL,
  7612. [Last_dop] bigint NULL,
  7613. [Min_dop] bigint NULL,
  7614. [Max_dop] bigint NULL,
  7615. [Total_dop] bigint NULL,
  7616. [Last_reserved_threads] bigint NULL,
  7617. [Min_reserved_threads] bigint NULL,
  7618. [Max_reserved_threads] bigint NULL,
  7619. [Total_reserved_threads] bigint NULL,
  7620. [Last_used_threads] bigint NULL,
  7621. [Min_used_threads] bigint NULL,
  7622. [Max_used_threads] bigint NULL,
  7623. [Total_used_threads] bigint NULL,
  7624. [Grant2Used_Ratio] float NULL,
  7625. --end
  7626. [query_plan] [xml] NULL,
  7627. [text] [nvarchar](MAX) COLLATE database_default NULL,
  7628. [text_filtered] [nvarchar](MAX) COLLATE database_default NULL)
  7629. IF @sqlmajorver = 9
  7630. BEGIN
  7631. --CPU
  7632. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time])
  7633. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time]
  7634. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7635. --ORDER BY qs.total_worker_time DESC');
  7636. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7637. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time]
  7638. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7639. ORDER BY qs.total_worker_time DESC),
  7640. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],ix.query(''.'') AS StmtSimple
  7641. FROM TopSearch ts
  7642. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7643. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7644. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time]
  7645. FROM TopFineSearch tfs
  7646. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7647. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7648. ORDER BY tfs.total_worker_time DESC');
  7649. --IO
  7650. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time])
  7651. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time]
  7652. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7653. --ORDER BY qs.total_logical_reads DESC');
  7654. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7655. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time]
  7656. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7657. ORDER BY qs.total_logical_reads DESC),
  7658. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],ix.query(''.'') AS StmtSimple
  7659. FROM TopSearch ts
  7660. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7661. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7662. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time]
  7663. FROM TopFineSearch tfs
  7664. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7665. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7666. ORDER BY tfs.total_logical_reads DESC');
  7667. --Recompiles
  7668. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time])
  7669. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time]
  7670. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7671. --ORDER BY qs.plan_generation_num DESC');
  7672. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7673. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time]
  7674. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7675. ORDER BY qs.plan_generation_num DESC),
  7676. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],ix.query(''.'') AS StmtSimple
  7677. FROM TopSearch ts
  7678. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7679. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7680. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time]
  7681. FROM TopFineSearch tfs
  7682. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7683. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7684. ORDER BY tfs.plan_generation_num DESC');
  7685. END
  7686. ELSE IF @sqlmajorver = 10 AND (@sqlminorver = 0 OR (@sqlminorver = 50 AND @sqlbuild < 2500))
  7687. BEGIN
  7688. --CPU
  7689. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash])
  7690. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash]
  7691. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7692. --ORDER BY qs.total_worker_time DESC');
  7693. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7694. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash]
  7695. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7696. ORDER BY qs.total_worker_time DESC),
  7697. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],ix.query(''.'') AS StmtSimple
  7698. FROM TopSearch ts
  7699. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7700. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7701. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash]
  7702. FROM TopFineSearch tfs
  7703. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7704. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7705. ORDER BY tfs.total_worker_time DESC');
  7706. --IO
  7707. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash])
  7708. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash]
  7709. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7710. --ORDER BY qs.total_logical_reads DESC');
  7711. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7712. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash]
  7713. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7714. ORDER BY qs.total_logical_reads DESC),
  7715. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],ix.query(''.'') AS StmtSimple
  7716. FROM TopSearch ts
  7717. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7718. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7719. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash]
  7720. FROM TopFineSearch tfs
  7721. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7722. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7723. ORDER BY tfs.total_logical_reads DESC');
  7724. --Recompiles
  7725. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash])
  7726. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash]
  7727. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7728. --ORDER BY qs.plan_generation_num DESC');
  7729. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7730. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash]
  7731. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7732. ORDER BY qs.plan_generation_num DESC),
  7733. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],ix.query(''.'') AS StmtSimple
  7734. FROM TopSearch ts
  7735. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7736. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7737. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash]
  7738. FROM TopFineSearch tfs
  7739. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7740. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7741. ORDER BY tfs.plan_generation_num DESC');
  7742. END
  7743. ELSE IF (@sqlmajorver = 10 AND @sqlminorver = 50) OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  7744. BEGIN
  7745. --CPU
  7746. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows])
  7747. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7748. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7749. --ORDER BY qs.total_worker_time DESC');
  7750. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7751. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7752. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7753. ORDER BY qs.total_worker_time DESC),
  7754. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],ix.query(''.'') AS StmtSimple
  7755. FROM TopSearch ts
  7756. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7757. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7758. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7759. FROM TopFineSearch tfs
  7760. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7761. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7762. ORDER BY tfs.total_worker_time DESC');
  7763. --IO
  7764. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows])
  7765. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7766. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7767. --ORDER BY qs.total_logical_reads DESC');
  7768. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7769. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7770. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7771. ORDER BY qs.total_logical_reads DESC),
  7772. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],ix.query(''.'') AS StmtSimple
  7773. FROM TopSearch ts
  7774. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7775. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7776. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7777. FROM TopFineSearch tfs
  7778. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7779. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7780. ORDER BY tfs.total_logical_reads DESC');
  7781. --Recompiles
  7782. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows])
  7783. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7784. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7785. --ORDER BY qs.plan_generation_num DESC');
  7786. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7787. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7788. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7789. ORDER BY qs.plan_generation_num DESC),
  7790. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],ix.query(''.'') AS StmtSimple
  7791. FROM TopSearch ts
  7792. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7793. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7794. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7795. FROM TopFineSearch tfs
  7796. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7797. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7798. ORDER BY tfs.plan_generation_num DESC');
  7799. END
  7800. ELSE IF (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  7801. BEGIN
  7802. --CPU
  7803. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],[Grant2Used_Ratio])
  7804. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads]
  7805. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7806. --ORDER BY qs.total_worker_time DESC');
  7807. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7808. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],COALESCE((([Total_used_grant_kb] * 100.00) / NULLIF([Total_grant_kb],0)), 0) AS Grant2Used_Ratio
  7809. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7810. ORDER BY qs.total_worker_time DESC),
  7811. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],ix.query(''.'') AS StmtSimple, Grant2Used_Ratio
  7812. FROM TopSearch ts
  7813. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7814. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7815. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads], Grant2Used_Ratio
  7816. FROM TopFineSearch tfs
  7817. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7818. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7819. ORDER BY tfs.total_worker_time DESC');
  7820. --IO
  7821. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],[Grant2Used_Ratio])
  7822. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads]
  7823. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7824. --ORDER BY qs.total_logical_reads DESC');
  7825. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7826. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],COALESCE((([Total_used_grant_kb] * 100.00) / NULLIF([Total_grant_kb],0)), 0) AS Grant2Used_Ratio
  7827. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7828. ORDER BY qs.total_logical_reads DESC),
  7829. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],ix.query(''.'') AS StmtSimple, Grant2Used_Ratio
  7830. FROM TopSearch ts
  7831. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7832. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7833. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads], Grant2Used_Ratio
  7834. FROM TopFineSearch tfs
  7835. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7836. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7837. ORDER BY tfs.total_logical_reads DESC');
  7838. --Recompiles
  7839. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],[Grant2Used_Ratio])
  7840. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads]
  7841. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7842. --ORDER BY qs.plan_generation_num DESC');
  7843. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7844. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],COALESCE((([Total_used_grant_kb] * 100.00) / NULLIF([Total_grant_kb],0)), 0) AS Grant2Used_Ratio
  7845. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7846. ORDER BY qs.plan_generation_num DESC),
  7847. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],ix.query(''.'') AS StmtSimple, Grant2Used_Ratio
  7848. FROM TopSearch ts
  7849. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7850. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7851. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads], Grant2Used_Ratio
  7852. FROM TopFineSearch tfs
  7853. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7854. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7855. ORDER BY tfs.plan_generation_num DESC');
  7856. --Mem Grants
  7857. INSERT INTO #tmp_dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],[Grant2Used_Ratio])
  7858. --EXEC ('SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads]
  7859. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7860. --ORDER BY qs.Total_grant_kb DESC');
  7861. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7862. TopSearch AS (SELECT DISTINCT TOP 25 [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],COALESCE((([Total_used_grant_kb] * 100.00) / NULLIF([Total_grant_kb],0)), 0) AS Grant2Used_Ratio
  7863. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7864. WHERE [Total_used_grant_kb] > 0
  7865. ORDER BY Total_used_grant_kb DESC, COALESCE((([Total_used_grant_kb] * 100.00) / NULLIF([Total_grant_kb],0)), 0) ASC),
  7866. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],ix.query(''.'') AS StmtSimple, Grant2Used_Ratio
  7867. FROM TopSearch ts
  7868. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7869. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7870. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads], Grant2Used_Ratio
  7871. FROM TopFineSearch tfs
  7872. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7873. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7874. ORDER BY tfs.Grant2Used_Ratio ASC');
  7875. END;
  7876. -- Remove duplicates before inserting XML
  7877. IF @sqlmajorver = 9
  7878. BEGIN
  7879. INSERT INTO #dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time])
  7880. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time]
  7881. FROM #tmp_dm_exec_query_stats;
  7882. END
  7883. ELSE IF @sqlmajorver = 10 AND (@sqlminorver = 0 OR (@sqlminorver = 50 AND @sqlbuild < 2500))
  7884. BEGIN
  7885. INSERT INTO #dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash])
  7886. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash]
  7887. FROM #tmp_dm_exec_query_stats;
  7888. END
  7889. ELSE IF (@sqlmajorver = 10 AND @sqlminorver = 50) OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  7890. BEGIN
  7891. INSERT INTO #dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows])
  7892. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7893. FROM #tmp_dm_exec_query_stats;
  7894. END
  7895. ELSE IF (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  7896. BEGIN
  7897. INSERT INTO #dm_exec_query_stats ([sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],[Grant2Used_Ratio])
  7898. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],[Grant2Used_Ratio]
  7899. FROM #tmp_dm_exec_query_stats;
  7900. END;
  7901. UPDATE #dm_exec_query_stats
  7902. SET query_plan = qp.query_plan,
  7903. [text] = st.[text],
  7904. text_filtered = SUBSTRING(st.[text],
  7905. (CASE WHEN qs.statement_start_offset = 0 THEN 0 ELSE qs.statement_start_offset/2 END),
  7906. (CASE WHEN qs.statement_end_offset = -1 THEN DATALENGTH(st.[text]) ELSE qs.statement_end_offset/2 END - (CASE WHEN qs.statement_start_offset = 0 THEN 0 ELSE qs.statement_start_offset/2 END)))
  7907. FROM #dm_exec_query_stats qs
  7908. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
  7909. CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
  7910. -- Delete own queries
  7911. DELETE FROM #dm_exec_query_stats
  7912. WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE '%Query_Plan_Warnings%';
  7913. -- Aggregate results
  7914. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  7915. DROP TABLE #qpwarnings;
  7916. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  7917. CREATE TABLE #qpwarnings ([Deviation] VARCHAR(50), [Comment] VARCHAR(255), query_plan XML, [statement] XML)
  7918. -- Find issues
  7919. INSERT INTO #qpwarnings
  7920. SELECT 'Scalar_UDFs'AS [Deviation],
  7921. ('[WARNING: Scalar UDF found in a top resource-intensive query, which that may inhibit parallelism]') AS [Comment],
  7922. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7923. qs.text_filtered,
  7924. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7925. FOR XML PATH(''), TYPE) AS [statement]
  7926. FROM #dm_exec_query_stats qs
  7927. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%UserDefinedFunction%'
  7928. UNION ALL
  7929. SELECT 'Implicit_Conversion_with_IX_Scan'AS [Deviation],
  7930. ('[WARNING: Implicit type conversions found where an Index Scan is present]') AS Details ,
  7931. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7932. qs.text_filtered,
  7933. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7934. FOR XML PATH(''), TYPE) AS [statement]
  7935. FROM #dm_exec_query_stats qs
  7936. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%CONVERT_IMPLICIT%'
  7937. AND CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%PhysicalOp="Index Scan"%'
  7938. UNION ALL
  7939. SELECT 'Missing_Index'AS [Deviation],
  7940. ('[WARNING: One of the top resource-intensive queries may be improved by adding an index]') AS [Comment],
  7941. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7942. qs.text_filtered,
  7943. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7944. FOR XML PATH(''), TYPE) AS [statement]
  7945. FROM #dm_exec_query_stats qs
  7946. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%MissingIndexGroup%'
  7947. UNION ALL
  7948. SELECT 'Cursor'AS [Deviation],
  7949. ('[WARNING: Cursor usage found in a top resource-intensive query. Check if it can be rewritten as a WHILE cycle]') AS [Comment],
  7950. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7951. qs.text_filtered,
  7952. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7953. FOR XML PATH(''), TYPE) AS [statement]
  7954. FROM #dm_exec_query_stats qs
  7955. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<CursorType%'
  7956. UNION ALL
  7957. SELECT 'Missing_Join_Predicate'AS [Deviation],
  7958. ('[WARNING: NO JOIN predicate event fired for a top resource-intensive query]') AS [Comment],
  7959. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7960. qs.text_filtered,
  7961. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7962. FOR XML PATH(''), TYPE) AS [statement]
  7963. FROM #dm_exec_query_stats qs
  7964. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings NoJoinPredicate="true"%'
  7965. UNION ALL
  7966. SELECT 'Columns_with_no_Statistics'AS [Deviation],
  7967. ('[WARNING: Missing Column Statistics event fired for a top resource-intensive query]') AS [Comment],
  7968. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7969. qs.text_filtered,
  7970. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7971. FOR XML PATH(''), TYPE) AS [statement]
  7972. FROM #dm_exec_query_stats qs
  7973. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings ColumnsWithNoStatistics%';
  7974. IF @sqlmajorver > 10
  7975. BEGIN
  7976. INSERT INTO #qpwarnings
  7977. -- Note that currently SpillToTempDb warnings are only found in actual execution plans
  7978. SELECT 'Spill_to_TempDb'AS [Deviation],
  7979. ('[WARNING: Spill to TempDB found during a HASH or SORT operation]') AS [Comment],
  7980. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7981. qs.text_filtered,
  7982. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7983. FOR XML PATH(''), TYPE) AS [statement]
  7984. FROM #dm_exec_query_stats qs
  7985. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<SpillToTempDb SpillLevel%'
  7986. UNION ALL
  7987. SELECT 'Implicit_Convert_affecting_Seek_Plan'AS [Deviation],
  7988. ('[WARNING: Implicit type conversions found, which can be affecting the choice of seek plans]') AS [Comment],
  7989. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7990. qs.text_filtered,
  7991. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7992. FOR XML PATH(''), TYPE) AS [statement]
  7993. FROM #dm_exec_query_stats qs
  7994. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Seek Plan" Expression="CONVERT_IMPLICIT%'
  7995. UNION ALL
  7996. SELECT 'Explicit_Conversion_affecting_Cardinality'AS [Deviation],
  7997. ('[WARNING: Explicit type conversions found, which can be affecting cardinality estimates]') AS [Comment],
  7998. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7999. qs.text_filtered,
  8000. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  8001. FOR XML PATH(''), TYPE) AS [statement]
  8002. FROM #dm_exec_query_stats qs
  8003. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Cardinality Estimate" Expression="CONVERT%'
  8004. UNION ALL
  8005. SELECT 'Implicit_Conversion_affecting_Cardinality'AS [Deviation],
  8006. ('[WARNING: Implicit type conversions found, which can be affecting cardinality estimates]') AS [Comment],
  8007. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  8008. qs.text_filtered,
  8009. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  8010. FOR XML PATH(''), TYPE) AS [statement]
  8011. FROM #dm_exec_query_stats qs
  8012. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Cardinality Estimate" Expression="CONVERT_IMPLICIT%'
  8013. UNION ALL
  8014. SELECT 'Unmatched_Indexes'AS [Deviation],
  8015. ('[WARNING: An unmatched indexes warning fired, where an index could not be used due to parameterization]') AS [Comment],
  8016. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  8017. qs.text_filtered,
  8018. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  8019. FOR XML PATH(''), TYPE) AS [statement]
  8020. FROM #dm_exec_query_stats qs
  8021. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings UnmatchedIndexes="true"%';
  8022. END;
  8023. IF (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  8024. BEGIN
  8025. INSERT INTO #qpwarnings
  8026. -- Note that currently MemoryGrant warnings are only found in actual execution plans
  8027. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8028. ('[WARNING: Granted memory was much larger than maximum used memory]') AS [Comment],
  8029. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  8030. qs.text_filtered,
  8031. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  8032. FOR XML PATH(''), TYPE) AS [statement]
  8033. FROM #dm_exec_query_stats qs
  8034. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Excessive Grant"%'
  8035. UNION ALL
  8036. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8037. ('[WARNING: Maximum used memory exceeds granted memory]') AS [Comment],
  8038. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  8039. qs.text_filtered,
  8040. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  8041. FOR XML PATH(''), TYPE) AS [statement]
  8042. FROM #dm_exec_query_stats qs
  8043. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Used More Than Granted"%'
  8044. UNION ALL
  8045. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8046. ('[WARNING: Dynamic grant increased too much when compared to initial grant request]') AS [Comment],
  8047. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  8048. qs.text_filtered,
  8049. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  8050. FOR XML PATH(''), TYPE) AS [statement]
  8051. FROM #dm_exec_query_stats qs
  8052. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Grant Increase"%'
  8053. END;
  8054. IF (SELECT COUNT(*) FROM #qpwarnings) > 0
  8055. BEGIN
  8056. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], '[WARNING: Top resource-intensive queries issued plan level warnings]' AS [Deviation]
  8057. END
  8058. ELSE
  8059. BEGIN
  8060. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], '[OK]' AS [Deviation]
  8061. END;
  8062. IF (SELECT COUNT(*) FROM #qpwarnings) > 0
  8063. BEGIN
  8064. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], [Comment], query_plan, [statement]
  8065. FROM #qpwarnings;
  8066. END;
  8067. IF (SELECT COUNT(*) FROM #dm_exec_query_stats) > 0
  8068. BEGIN
  8069. SELECT 'Performance_checks' AS [Category], 'Inefficient_Plans_Reads' AS [Check], query_plan,
  8070. (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  8071. text_filtered,
  8072. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  8073. FOR XML PATH(''), TYPE) AS [statement],
  8074. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8075. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8076. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8077. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8078. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8079. [Grant2Used_Ratio],
  8080. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8081. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8082. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8083. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8084. FROM #dm_exec_query_stats
  8085. ORDER BY [Avg_Logical_Reads] DESC;
  8086. SELECT 'Performance_checks' AS [Category], 'Inefficient_Plans_CPU' AS [Check], query_plan,
  8087. (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  8088. text_filtered,
  8089. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  8090. FOR XML PATH(''), TYPE) AS [statement],
  8091. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8092. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8093. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8094. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8095. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8096. [Grant2Used_Ratio],
  8097. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8098. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8099. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8100. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8101. FROM #dm_exec_query_stats
  8102. ORDER BY [Avg_Worker_Time] DESC;
  8103. SELECT 'Performance_checks' AS [Category], 'Inefficient_Memory_Use' AS [Check], query_plan,
  8104. (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  8105. text_filtered,
  8106. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  8107. FOR XML PATH(''), TYPE) AS [statement],
  8108. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8109. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8110. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8111. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8112. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8113. [Grant2Used_Ratio],
  8114. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8115. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8116. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8117. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8118. FROM #dm_exec_query_stats
  8119. ORDER BY Grant2Used_Ratio ASC;
  8120. END;
  8121. END;
  8122. --------------------------------------------------------------------------------------------------------------------------------
  8123. -- Declarative Referential Integrity - Untrusted Constraints subsection
  8124. --------------------------------------------------------------------------------------------------------------------------------
  8125. IF @ptochecks = 1
  8126. BEGIN
  8127. RAISERROR (N' |-Starting Declarative Referential Integrity - Untrusted Constraints', 10, 1) WITH NOWAIT
  8128. /*
  8129. Declarative Referential Integrity (DRI), meaning “trusting” constraints will allow SQL Server to introduce optimizations that would otherwise not be possible,
  8130. such as eliminating JOINs or even not reading any table for particular queries.
  8131. For example, if a search argument is looking for when a column IS NULL, but there is a NOT NULL constraint in place, the table might not even be accessed from a data read standpoint.
  8132. */
  8133. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  8134. DROP TABLE #tblDRI;
  8135. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  8136. CREATE TABLE #tblDRI ([databaseID] int, [database_name] sysname, [schema_id] int, [schema_name] VARCHAR(100), [object_id] int, [table_name] VARCHAR(200), [constraint_name] VARCHAR(200), [constraint_type] VARCHAR(10)
  8137. CONSTRAINT PK_DRI PRIMARY KEY CLUSTERED(databaseID, [schema_id], [object_id], [constraint_name]))
  8138. UPDATE #tmpdbs1
  8139. SET isdone = 0
  8140. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  8141. BEGIN
  8142. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  8143. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8144. USE ' + QUOTENAME(@dbname) + '
  8145. SELECT ''' + CONVERT(VARCHAR(12),@dbid) + ''' AS [databaseID], ''' + @dbname + ''' AS [database_name], o.[schema_id], t.name AS [schema_name], mst.[object_id], mst.name AS [table_name], FKC.name AS [constraint_name], ''ForeignKey'' As [constraint_type]
  8146. FROM sys.foreign_keys FKC (NOLOCK)
  8147. INNER JOIN sys.objects o (NOLOCK) ON FKC.parent_object_id = o.[object_id]
  8148. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8149. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8150. WHERE o.type = ''U'' AND FKC.is_not_trusted = 1 AND FKC.is_not_for_replication = 0
  8151. GROUP BY o.[schema_id], mst.[object_id], FKC.name, t.name, mst.name
  8152. UNION ALL
  8153. SELECT ''' + CONVERT(VARCHAR(12),@dbid) + ''' AS [databaseID], ''' + @dbname + ''' AS [database_name], t.[schema_id], t.name AS [schema_name], mst.[object_id], mst.name AS [table_name], CC.name AS [constraint_name], ''Check'' As [constraint_type]
  8154. FROM sys.check_constraints CC (NOLOCK)
  8155. INNER JOIN sys.objects o (NOLOCK) ON CC.parent_object_id = o.[object_id]
  8156. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8157. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8158. WHERE o.type = ''U'' AND CC.is_not_trusted = 1 AND CC.is_not_for_replication = 0 AND CC.is_disabled = 0
  8159. GROUP BY t.[schema_id], mst.[object_id], CC.name, t.name, mst.name
  8160. ORDER BY mst.name, [constraint_name];'
  8161. BEGIN TRY
  8162. INSERT INTO #tblDRI
  8163. EXECUTE sp_executesql @sqlcmd
  8164. END TRY
  8165. BEGIN CATCH
  8166. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8167. SELECT @ErrorMessage = 'Declarative Referential Integrity subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8168. RAISERROR (@ErrorMessage, 16, 1);
  8169. END CATCH
  8170. UPDATE #tmpdbs1
  8171. SET isdone = 1
  8172. WHERE [dbid] = @dbid
  8173. END;
  8174. IF (SELECT COUNT(*) FROM #tblDRI) > 0
  8175. BEGIN
  8176. SELECT 'Performance_checks' AS [Category], 'DRI_UntrustedConstraints' AS [Check], '[WARNING: Some constraints are not trusted for referential integrity. It is recommended to revise these due to possible performance issues]' AS [Deviation]
  8177. SELECT 'Performance_checks' AS [Category], 'DRI_UntrustedConstraints' AS [Information], [database_name] AS [Database_Name], constraint_name AS [Constraint_Name],
  8178. [schema_name] AS [Schema_Name], table_name AS [Table_Name], [constraint_type] AS [Constraint_Type]
  8179. FROM #tblDRI
  8180. ORDER BY [database_name], [schema_name], table_name, [constraint_type];
  8181. IF @gen_scripts = 1
  8182. BEGIN
  8183. DECLARE @strSQL1 NVARCHAR(4000)
  8184. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8185. PRINT CHAR(10) + '--############# Trust untrusted Contraints statements #############' + CHAR(10)
  8186. DECLARE cDRI CURSOR FAST_FORWARD FOR SELECT 'USE ' + [database_name] + CHAR(10) + 'GO' + CHAR(10) +
  8187. 'ALTER TABLE ' + QUOTENAME([schema_name]) + '.' + QUOTENAME(table_name) + CHAR(10) +
  8188. 'WITH CHECK CHECK CONSTRAINT ' + QUOTENAME(constraint_name) + CHAR(10) + 'GO'
  8189. FROM #tblDRI
  8190. ORDER BY [database_name], [schema_name], table_name, [constraint_type]
  8191. OPEN cDRI
  8192. FETCH NEXT FROM cDRI INTO @strSQL1
  8193. WHILE (@@FETCH_STATUS = 0)
  8194. BEGIN
  8195. PRINT @strSQL1
  8196. FETCH NEXT FROM cDRI INTO @strSQL1
  8197. END
  8198. CLOSE cDRI
  8199. DEALLOCATE cDRI
  8200. PRINT CHAR(10) + '--############# Ended Trust untrusted Contraints statements #############' + CHAR(10)
  8201. END;
  8202. END
  8203. ELSE
  8204. BEGIN
  8205. SELECT 'Performance_checks' AS [Category], 'DRI_UntrustedConstraints' AS [Check], '[OK]' AS [Deviation]
  8206. END;
  8207. END;
  8208. IF @ptochecks = 1
  8209. RAISERROR (N'|-Starting Indexes and Statistics Checks', 10, 1) WITH NOWAIT
  8210. --------------------------------------------------------------------------------------------------------------------------------
  8211. -- Statistics update subsection
  8212. --------------------------------------------------------------------------------------------------------------------------------
  8213. IF @ptochecks = 1
  8214. BEGIN
  8215. RAISERROR (N' |-Starting Statistics update', 10, 1) WITH NOWAIT
  8216. UPDATE #tmpdbs0
  8217. SET isdone = 0;
  8218. UPDATE #tmpdbs0
  8219. SET isdone = 1
  8220. WHERE [state] <> 0 OR [dbid] < 5;
  8221. UPDATE #tmpdbs0
  8222. SET isdone = 1
  8223. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8224. DECLARE @dbcmptlevel int
  8225. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  8226. DROP TABLE #tblStatsUpd;
  8227. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  8228. CREATE TABLE #tblStatsUpd ([DatabaseName] sysname, [databaseID] int, objectID int, schemaName VARCHAR(100), [tableName] VARCHAR(250), last_updated DATETIME, [rows] bigint, modification_counter bigint, [stats_id] int, [stat_name] VARCHAR(255), auto_created bit, user_created bit, has_filter bit NULL, filter_definition NVARCHAR(MAX) NULL, unfiltered_rows bigint, steps int)
  8229. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8230. BEGIN
  8231. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8232. BEGIN
  8233. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid], @dbcmptlevel = [compatibility_level] FROM #tmpdbs0 WHERE isdone = 0
  8234. IF ((@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4000) OR (@sqlmajorver = 11 AND @sqlbuild >= 3000) OR @sqlmajorver > 11) AND @dbcmptlevel > 80
  8235. BEGIN
  8236. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8237. SELECT DISTINCT ''' + @dbname + ''' AS [DatabaseName], ''' + CONVERT(VARCHAR(12),@dbid) + ''' AS [databaseID], mst.[object_id] AS objectID, t.name AS schemaName, OBJECT_NAME(mst.[object_id]) AS tableName,
  8238. sp.last_updated, sp.[rows], sp.modification_counter, ss.[stats_id], ss.name AS [stat_name], ss.auto_created, ss.user_created, ss.has_filter, ss.filter_definition, sp.unfiltered_rows, sp.steps
  8239. FROM sys.objects AS o
  8240. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8241. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8242. INNER JOIN sys.stats AS ss ON ss.[object_id] = mst.[object_id]
  8243. CROSS APPLY sys.dm_db_stats_properties(ss.[object_id], ss.[stats_id]) AS sp
  8244. WHERE sp.[rows] > 0
  8245. AND ((sp.[rows] <= 500 AND sp.modification_counter >= 500)
  8246. OR (sp.[rows] > 500 AND sp.modification_counter >= (500 + sp.[rows] * 0.20)))'
  8247. END
  8248. ELSE
  8249. BEGIN
  8250. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8251. SELECT DISTINCT ''' + @dbname + ''' AS [DatabaseName], ''' + CONVERT(VARCHAR(12),@dbid) + ''' AS [databaseID], mst.[object_id] AS objectID, t.name AS schemaName, OBJECT_NAME(mst.[object_id]) AS tableName,
  8252. STATS_DATE(mst.[object_id], ss.stats_id) AS last_updated, SUM(p.[rows]) AS [rows], si.rowmodctr AS modification_counter, ss.stats_id, ss.name AS [stat_name], ss.auto_created, ss.user_created, NULL, NULL, NULL, NULL
  8253. FROM sys.sysindexes AS si
  8254. INNER JOIN sys.objects AS o ON si.id = o.[object_id]
  8255. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8256. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8257. INNER JOIN sys.stats AS ss ON ss.[object_id] = o.[object_id]
  8258. INNER JOIN sys.partitions AS p ON p.[object_id] = ss.[object_id]
  8259. LEFT JOIN sys.indexes i ON si.id = i.[object_id] AND si.indid = i.index_id
  8260. WHERE o.type <> ''S'' AND i.name IS NOT NULL
  8261. GROUP BY mst.[object_id], t.name, rowmodctr, ss.stats_id, ss.name, ss.auto_created, ss.user_created
  8262. HAVING SUM(p.[rows]) > 0
  8263. AND ((SUM(p.[rows]) <= 500 AND rowmodctr >= 500)
  8264. OR (SUM(p.[rows]) > 500 AND rowmodctr >= (500 + SUM(p.[rows]) * 0.20)))'
  8265. END
  8266. BEGIN TRY
  8267. INSERT INTO #tblStatsUpd
  8268. EXECUTE sp_executesql @sqlcmd
  8269. END TRY
  8270. BEGIN CATCH
  8271. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8272. SELECT @ErrorMessage = 'Statistics update subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8273. RAISERROR (@ErrorMessage, 16, 1);
  8274. END CATCH
  8275. UPDATE #tmpdbs0
  8276. SET isdone = 1
  8277. WHERE [dbid] = @dbid
  8278. END
  8279. END;
  8280. CREATE INDEX IX_Stats ON #tblStatsUpd([databaseID]);
  8281. IF (SELECT COUNT(*) FROM #tblStatsUpd) > 0
  8282. BEGIN
  8283. IF (SELECT COUNT(*) FROM master.sys.databases (NOLOCK) WHERE is_auto_update_stats_on = 0) > 0 AND (SELECT COUNT(*) FROM #tblStatsUpd AS su INNER JOIN master.sys.databases AS sd (NOLOCK) ON su.[databaseID] = sd.[database_id] WHERE sd.is_auto_update_stats_on = 0) > 0
  8284. BEGIN
  8285. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_to_update' AS [Check], '[WARNING: Some databases have Auto_Update_Statistics DISABLED and statistics that might need to be updated]' AS [Deviation]
  8286. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_to_update' AS [Information], [DatabaseName] AS [Database_Name], schemaName AS [Schema_Name], [tableName] AS [Table_Name], [stats_id] AS [statsID], [stat_name] AS [Statistic_Name],
  8287. last_updated, [rows], modification_counter, CAST((su.modification_counter*1.00/(su.[rows]*1.00))*100.0 AS DECIMAL(18,2)) AS [RowMod_Pct],
  8288. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8289. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8290. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8291. ELSE NULL
  8292. END AS [Statistic_Type],
  8293. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition], su.unfiltered_rows AS [Unfiltered_Rows]
  8294. FROM #tblStatsUpd AS su INNER JOIN master.sys.databases AS sd (NOLOCK) ON su.[databaseID] = sd.[database_id]
  8295. WHERE sd.is_auto_update_stats_on = 0
  8296. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8297. END;
  8298. IF (SELECT COUNT(*) FROM #tblStatsUpd AS su INNER JOIN master.sys.databases AS sd (NOLOCK) ON su.[databaseID] = sd.[database_id] WHERE sd.is_auto_update_stats_on = 1) > 0
  8299. BEGIN
  8300. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_to_update' AS [Check], '[WARNING: Some databases have Auto_Update_Statistics ENABLED and statistics that might need to be updated]' AS [Deviation]
  8301. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_to_update' AS [Information], [DatabaseName] AS [Database_Name], schemaName AS [Schema_Name], [tableName] AS [Table_Name], [stats_id] AS [statsID], [stat_name] AS [Statistic_Name],
  8302. last_updated, [rows], modification_counter, CAST((su.modification_counter*1.00/(su.[rows]*1.00))*100.0 AS DECIMAL(18,2)) AS [RowMod_Pct],
  8303. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8304. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8305. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8306. ELSE NULL
  8307. END AS [Statistic_Type],
  8308. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition]
  8309. FROM #tblStatsUpd AS su INNER JOIN master.sys.databases AS sd (NOLOCK) ON su.[databaseID] = sd.[database_id]
  8310. WHERE sd.is_auto_update_stats_on = 1
  8311. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8312. END;
  8313. END
  8314. ELSE
  8315. BEGIN
  8316. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_to_update' AS [Check], '[OK]' AS [Deviation]
  8317. END;
  8318. END;
  8319. --------------------------------------------------------------------------------------------------------------------------------
  8320. -- Statistics sampling subsection
  8321. --------------------------------------------------------------------------------------------------------------------------------
  8322. IF @ptochecks = 1
  8323. BEGIN
  8324. IF (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4000) OR (@sqlmajorver = 11 AND @sqlbuild >= 3000) OR @sqlmajorver > 11
  8325. BEGIN
  8326. RAISERROR (N' |-Starting Statistics sampling', 10, 1) WITH NOWAIT
  8327. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  8328. DROP TABLE #tblStatsSamp;
  8329. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  8330. CREATE TABLE #tblStatsSamp ([DatabaseName] sysname, [databaseID] int, objectID int, schemaName VARCHAR(100), [tableName] VARCHAR(250), last_updated DATETIME, [rows] bigint, modification_counter bigint, [stats_id] int, [stat_name] VARCHAR(255), rows_sampled bigint, auto_created bit, user_created bit, has_filter bit NULL, filter_definition NVARCHAR(MAX) NULL, unfiltered_rows bigint, steps int)
  8331. UPDATE #tmpdbs0
  8332. SET isdone = 0;
  8333. UPDATE #tmpdbs0
  8334. SET isdone = 1
  8335. WHERE [state] <> 0 OR [dbid] < 5;
  8336. UPDATE #tmpdbs0
  8337. SET isdone = 1
  8338. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8339. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8340. BEGIN
  8341. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8342. BEGIN
  8343. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid], @dbcmptlevel = [compatibility_level] FROM #tmpdbs0 WHERE isdone = 0
  8344. IF @dbcmptlevel > 80
  8345. BEGIN
  8346. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8347. SELECT DISTINCT ''' + @dbname + ''' AS [DatabaseName], ''' + CONVERT(VARCHAR(12),@dbid) + ''' AS [databaseID], mst.[object_id] AS objectID, t.name AS schemaName, OBJECT_NAME(mst.[object_id]) AS tableName,
  8348. sp.last_updated, sp.[rows], sp.modification_counter, ss.[stats_id], ss.name AS [stat_name], sp.rows_sampled, ss.auto_created, ss.user_created, ss.has_filter, ss.filter_definition, sp.unfiltered_rows, sp.steps
  8349. FROM sys.objects AS o
  8350. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8351. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8352. INNER JOIN sys.stats AS ss ON ss.[object_id] = mst.[object_id]
  8353. CROSS APPLY sys.dm_db_stats_properties(ss.[object_id], ss.[stats_id]) AS sp
  8354. WHERE sp.[rows] > 0
  8355. AND CAST((sp.rows_sampled/(sp.[rows]*1.00))*100.0 AS DECIMAL(5,2)) < 25'
  8356. BEGIN TRY
  8357. INSERT INTO #tblStatsSamp
  8358. EXECUTE sp_executesql @sqlcmd
  8359. END TRY
  8360. BEGIN CATCH
  8361. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8362. SELECT @ErrorMessage = 'Statistics sampling subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8363. RAISERROR (@ErrorMessage, 16, 1);
  8364. END CATCH
  8365. END
  8366. UPDATE #tmpdbs0
  8367. SET isdone = 1
  8368. WHERE [dbid] = @dbid
  8369. END
  8370. END;
  8371. CREATE INDEX IX_Stats ON #tblStatsSamp([databaseID]);
  8372. IF (SELECT COUNT(*) FROM #tblStatsSamp) > 0
  8373. BEGIN
  8374. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_sampling_lt_25pct' AS [Check], '[WARNING: Some statistics have sampling rates less than 25 pct, consider updating with a larger sample or fullscan]' AS [Deviation]
  8375. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_sampling_lt_25pct' AS [Information], [DatabaseName] AS [Database_Name], schemaName AS [Schema_Name], [tableName] AS [Table_Name], [stats_id] AS [statsID], [stat_name] AS [Statistic_Name],
  8376. last_updated, [rows], rows_sampled, CAST((rows_sampled/([rows]*1.00))*100.0 AS DECIMAL(5,2)) AS [Sample_Pct],
  8377. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8378. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8379. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8380. ELSE NULL
  8381. END AS [Statistic_Type],
  8382. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition]
  8383. FROM #tblStatsSamp AS su
  8384. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8385. END
  8386. ELSE
  8387. BEGIN
  8388. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_sampling_lt_25pct' AS [Check], '[OK]' AS [Deviation]
  8389. END;
  8390. END;
  8391. END;
  8392. --------------------------------------------------------------------------------------------------------------------------------
  8393. -- Hypothetical objects subsection
  8394. --------------------------------------------------------------------------------------------------------------------------------
  8395. IF @ptochecks = 1
  8396. BEGIN
  8397. RAISERROR (N' |-Starting Hypothetical objects', 10, 1) WITH NOWAIT
  8398. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  8399. DROP TABLE #tblHypObj;
  8400. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  8401. CREATE TABLE #tblHypObj ([DBName] sysname, [Schema] VARCHAR(100), [Table] VARCHAR(255), [Object] VARCHAR(255), [Type] VARCHAR(10));
  8402. UPDATE #tmpdbs0
  8403. SET isdone = 0;
  8404. UPDATE #tmpdbs0
  8405. SET isdone = 1
  8406. WHERE [state] <> 0 OR [dbid] = 2;
  8407. UPDATE #tmpdbs0
  8408. SET isdone = 1
  8409. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8410. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8411. BEGIN
  8412. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8413. BEGIN
  8414. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  8415. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8416. SELECT ''' + @dbname + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), i.name, ''INDEX''
  8417. FROM sys.indexes i
  8418. INNER JOIN sys.objects o ON o.[object_id] = i.[object_id]
  8419. INNER JOIN sys.tables AS mst ON mst.[object_id] = i.[object_id]
  8420. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8421. WHERE i.is_hypothetical = 1
  8422. UNION ALL
  8423. SELECT ''' + @dbname + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), s.name, ''STATISTICS''
  8424. FROM sys.stats s
  8425. INNER JOIN sys.objects o (NOLOCK) ON o.[object_id] = s.[object_id]
  8426. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = s.[object_id]
  8427. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8428. WHERE (s.name LIKE ''hind_%'' OR s.name LIKE ''_dta_stat%'') AND auto_created = 0
  8429. AND s.name NOT IN (SELECT name FROM ' + QUOTENAME(@dbname) + '.sys.indexes)'
  8430. BEGIN TRY
  8431. INSERT INTO #tblHypObj
  8432. EXECUTE sp_executesql @sqlcmd
  8433. END TRY
  8434. BEGIN CATCH
  8435. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8436. SELECT @ErrorMessage = 'Hypothetical objects subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8437. RAISERROR (@ErrorMessage, 16, 1);
  8438. END CATCH
  8439. UPDATE #tmpdbs0
  8440. SET isdone = 1
  8441. WHERE [dbid] = @dbid
  8442. END
  8443. END;
  8444. UPDATE #tmpdbs0
  8445. SET isdone = 0;
  8446. IF (SELECT COUNT([Object]) FROM #tblHypObj) > 0
  8447. BEGIN
  8448. SELECT 'Index_and_Stats_checks' AS [Category], 'Hypothetical_objects' AS [Check], '[WARNING: Some databases have indexes or statistics that are marked as hypothetical. It is recommended to drop these objects as soon as possible]' AS [Deviation]
  8449. SELECT 'Index_and_Stats_checks' AS [Category], 'Hypothetical_objects' AS [Information], DBName AS [Database_Name], [Table] AS [Table_Name], [Object] AS [Object_Name], [Type] AS [Object_Type]
  8450. FROM #tblHypObj
  8451. ORDER BY 2, 3, 5
  8452. IF @gen_scripts = 1
  8453. BEGIN
  8454. DECLARE @strSQL NVARCHAR(4000)
  8455. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8456. PRINT CHAR(10) + '--############# Existing Hypothetical objects drop statements #############' + CHAR(10)
  8457. DECLARE ITW_Stats CURSOR FAST_FORWARD FOR SELECT 'USE ' + [DBName] + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM ' + CASE WHEN [Type] = 'STATISTICS' THEN 'sys.stats' ELSE 'sys.indexes' END + ' WHERE name = N'''+ [Object] + ''')' + CHAR(10) +
  8458. CASE WHEN [Type] = 'STATISTICS' THEN 'DROP STATISTICS ' + [Schema] + '.' + [Table] + '.' + QUOTENAME([Object]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  8459. ELSE 'DROP INDEX ' + QUOTENAME([Object]) + ' ON ' + [Schema] + '.' + [Table] + ';' + CHAR(10) + 'GO' + CHAR(10)
  8460. END
  8461. FROM #tblHypObj
  8462. ORDER BY DBName, [Table]
  8463. OPEN ITW_Stats
  8464. FETCH NEXT FROM ITW_Stats INTO @strSQL
  8465. WHILE (@@FETCH_STATUS = 0)
  8466. BEGIN
  8467. PRINT @strSQL
  8468. FETCH NEXT FROM ITW_Stats INTO @strSQL
  8469. END
  8470. CLOSE ITW_Stats
  8471. DEALLOCATE ITW_Stats
  8472. PRINT CHAR(10) + '--############# Ended Hypothetical objects drop statements #############' + CHAR(10)
  8473. END;
  8474. END
  8475. ELSE
  8476. BEGIN
  8477. SELECT 'Index_and_Stats_checks' AS [Category], 'Hypothetical_objects' AS [Check], '[OK]' AS [Deviation]
  8478. END;
  8479. END;
  8480. --------------------------------------------------------------------------------------------------------------------------------
  8481. -- Index Health Analysis subsection
  8482. --------------------------------------------------------------------------------------------------------------------------------
  8483. IF @ixfrag = 1 AND @ptochecks = 1
  8484. BEGIN
  8485. RAISERROR (N' |-Starting Index Health Analysis check', 10, 1) WITH NOWAIT
  8486. DECLARE /*@dbid int, */@objectid int, @indexid int, @partition_nr int, @type_desc NVARCHAR(60)
  8487. DECLARE @ColumnStoreGetIXSQL NVARCHAR(2000), @ColumnStoreGetIXSQL_Param NVARCHAR(1000), @HasInMem bit
  8488. DECLARE /*@sqlcmd NVARCHAR(4000), @params NVARCHAR(500),*/ @schema_name VARCHAR(100), @table_name VARCHAR(300), @KeyCols VARCHAR(4000), @distinctCnt bigint, @OptimBucketCnt bigint
  8489. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  8490. DROP TABLE #tmpIPS;
  8491. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  8492. CREATE TABLE #tmpIPS ([database_id] int, [object_id] int, [index_id] int, [partition_number] int, fragmentation DECIMAL(18,3), [page_count] bigint, [size_MB] DECIMAL(26,3), record_count bigint, forwarded_record_count int NULL,
  8493. CONSTRAINT PK_IPS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id], [partition_number]));
  8494. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  8495. DROP TABLE #tmpIPS_CI;
  8496. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  8497. CREATE TABLE #tmpIPS_CI ([database_id] int, [object_id] int, [index_id] int, [partition_number] int, fragmentation DECIMAL(18,3), [page_count] bigint, [size_MB] DECIMAL(26,3), record_count bigint, delta_store_hobt_id bigint, row_group_id int , [state] tinyint, state_description VARCHAR(60),
  8498. CONSTRAINT PK_IPS_CI PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id], [partition_number], row_group_id));
  8499. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  8500. DROP TABLE #tmpXIS;
  8501. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  8502. CREATE TABLE #tmpXIS ([database_id] int, [object_id] int, [schema_name] VARCHAR(100) COLLATE database_default, [table_name] VARCHAR(300) COLLATE database_default, [index_id] int, [index_name] VARCHAR(300) COLLATE database_default, type_desc NVARCHAR(60), total_bucket_count bigint, empty_bucket_count bigint, avg_chain_length bigint, max_chain_length bigint, KeyCols VARCHAR(4000) COLLATE database_default, DistinctCnt bigint NULL, OptimBucketCnt bigint NULL, isdone bit,
  8503. CONSTRAINT PK_tmpXIS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id]));
  8504. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  8505. DROP TABLE #tmpXNCIS;
  8506. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  8507. CREATE TABLE #tmpXNCIS ([database_id] int, [object_id] int, [schema_name] VARCHAR(100) COLLATE database_default, [table_name] VARCHAR(300) COLLATE database_default, [index_id] int, [index_name] VARCHAR(300) COLLATE database_default, type_desc NVARCHAR(60), delta_pages bigint, internal_pages bigint, leaf_pages bigint, page_update_count bigint, page_update_retry_count bigint, page_consolidation_count bigint, page_consolidation_retry_count bigint, page_split_count bigint, page_split_retry_count bigint, key_split_count bigint, key_split_retry_count bigint, page_merge_count bigint, page_merge_retry_count bigint, key_merge_count bigint, key_merge_retry_count bigint, scans_started bigint, scans_retries bigint,
  8508. CONSTRAINT PK_tmpXNCIS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id]));
  8509. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  8510. DROP TABLE #tblWorking;
  8511. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  8512. CREATE TABLE #tblWorking (database_id int, [database_name] NVARCHAR(255), [object_id] int, [object_name] NVARCHAR(255), index_id int, index_name NVARCHAR(255), [schema_name] NVARCHAR(255), partition_number int, [type] tinyint, type_desc NVARCHAR(60), is_done bit)
  8513. -- type 0 = Heap; 1 = Clustered; 2 = Nonclustered; 3 = XML; 4 = Spatial; 5 = Clustered columnstore; 6 = Nonclustered columnstore; 7 = Nonclustered hash
  8514. RAISERROR (N' |-Populating support table...', 10, 1) WITH NOWAIT
  8515. UPDATE #tmpdbs0
  8516. SET isdone = 0;
  8517. UPDATE #tmpdbs0
  8518. SET isdone = 1
  8519. WHERE [state] <> 0 OR [dbid] < 5;
  8520. UPDATE #tmpdbs0
  8521. SET isdone = 1
  8522. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8523. IF EXISTS (SELECT TOP 1 id FROM #tmpdbs0 WHERE isdone = 0)
  8524. BEGIN
  8525. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8526. BEGIN
  8527. SELECT TOP 1 @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  8528. SELECT @sqlcmd = 'SELECT ' + CONVERT(VARCHAR(10), @dbid) + ', ''' + DB_NAME(@dbid) + ''', si.[object_id], mst.[name], si.index_id, si.name, t.name, sp.partition_number, si.[type], si.type_desc, 0
  8529. FROM [' + DB_NAME(@dbid) + '].sys.indexes si
  8530. INNER JOIN [' + DB_NAME(@dbid) + '].sys.partitions sp ON si.[object_id] = sp.[object_id] AND si.index_id = sp.index_id
  8531. INNER JOIN [' + DB_NAME(@dbid) + '].sys.tables AS mst ON mst.[object_id] = si.[object_id]
  8532. INNER JOIN [' + DB_NAME(@dbid) + '].sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8533. WHERE mst.is_ms_shipped = 0 AND ' + CASE WHEN @sqlmajorver <= 11 THEN ' si.[type] <= 2;' ELSE ' si.[type] IN (0,1,2,5,6,7);' END
  8534. INSERT INTO #tblWorking
  8535. EXEC sp_executesql @sqlcmd;
  8536. IF @sqlmajorver >= 12
  8537. BEGIN
  8538. SELECT @sqlcmd = 'SELECT @HasInMemOUT = ISNULL((SELECT TOP 1 1 FROM [' + DB_NAME(@dbid) + '].sys.filegroups FG where FG.[type] = ''FX''), 0)'
  8539. SET @params = N'@HasInMemOUT bit OUTPUT';
  8540. EXECUTE sp_executesql @sqlcmd, @params, @HasInMemOUT=@HasInMem OUTPUT
  8541. IF @HasInMem = 1
  8542. BEGIN
  8543. INSERT INTO #tmpIPS_CI ([database_id], [object_id], [index_id], [partition_number], fragmentation, [page_count], [size_MB], record_count, delta_store_hobt_id, row_group_id, [state], state_description)
  8544. EXECUTE sp_executesql @ColumnStoreGetIXSQL, @ColumnStoreGetIXSQL_Param, @dbid_In = @dbid, @objectid_In = @objectid, @indexid_In = @indexid, @partition_nr_In = @partition_nr;
  8545. SELECT @ErrorMessage = ' |-Gathering sys.dm_db_xtp_hash_index_stats and sys.dm_db_xtp_nonclustered_index_stats data in ' + DB_NAME(@dbid) + '...'
  8546. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT;
  8547. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8548. USE [' + DB_NAME(@dbid) + '];
  8549. SELECT ' + CONVERT(NVARCHAR(20), @dbid) + ' AS [database_id], xis.[object_id], t.name, o.name, xis.index_id, si.name, si.type_desc, xhis.total_bucket_count, xhis.empty_bucket_count, xhis.avg_chain_length, xhis.max_chain_length,
  8550. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8551. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8552. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8553. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8554. WHERE si.[object_id] = i.[object_id] AND si.index_id = i.index_id AND ic.is_included_column = 0
  8555. ORDER BY ic.key_ordinal
  8556. FOR XML PATH('''')), 2, 8000) AS KeyCols, NULL, NULL, 0
  8557. FROM sys.dm_db_xtp_hash_index_stats AS xhis
  8558. INNER JOIN sys.dm_db_xtp_index_stats AS xis ON xis.[object_id] = xhis.[object_id] AND xis.[index_id] = xhis.[index_id]
  8559. INNER JOIN sys.indexes AS si (NOLOCK) ON xis.[object_id] = si.[object_id] AND xis.[index_id] = si.[index_id]
  8560. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  8561. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8562. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8563. WHERE o.[type] = ''U'''
  8564. BEGIN TRY
  8565. INSERT INTO #tmpXIS
  8566. EXECUTE sp_executesql @sqlcmd
  8567. END TRY
  8568. BEGIN CATCH
  8569. SET @ErrorMessage = ' |-Error ' + CONVERT(VARCHAR(20),ERROR_NUMBER()) + ' has occurred while analyzing hash indexes. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS VARCHAR(10)) + ')'
  8570. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8571. END CATCH
  8572. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8573. USE [' + DB_NAME(@dbid) + '];
  8574. SELECT ' + CONVERT(NVARCHAR(20), @dbid) + ' AS [database_id],
  8575. xis.[object_id], t.name, o.name, xis.index_id, si.name, si.type_desc,
  8576. xnis.delta_pages, xnis.internal_pages, xnis.leaf_pages, xnis.page_update_count,
  8577. xnis.page_update_retry_count, xnis.page_consolidation_count,
  8578. xnis.page_consolidation_retry_count, xnis.page_split_count, xnis.page_split_retry_count,
  8579. xnis.key_split_count, xnis.key_split_retry_count, xnis.page_merge_count, xnis.page_merge_retry_count,
  8580. xnis.key_merge_count, xnis.key_merge_retry_count,
  8581. xis.scans_started, xis.scans_retries
  8582. FROM sys.dm_db_xtp_nonclustered_index_stats AS xnis (NOLOCK)
  8583. INNER JOIN sys.dm_db_xtp_index_stats AS xis (NOLOCK) ON xis.[object_id] = xnis.[object_id] AND xis.[index_id] = xnis.[index_id]
  8584. INNER JOIN sys.indexes AS si (NOLOCK) ON xis.[object_id] = si.[object_id] AND xis.[index_id] = si.[index_id]
  8585. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  8586. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8587. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8588. WHERE o.[type] = ''U'''
  8589. BEGIN TRY
  8590. INSERT INTO #tmpXNCIS
  8591. EXECUTE sp_executesql @sqlcmd
  8592. END TRY
  8593. BEGIN CATCH
  8594. SET @ErrorMessage = ' |-Error ' + CONVERT(VARCHAR(20),ERROR_NUMBER()) + ' has occurred while analyzing nonclustered hash indexes. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS VARCHAR(10)) + ')'
  8595. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8596. END CATCH
  8597. END;
  8598. /*ELSE
  8599. BEGIN
  8600. SELECT @ErrorMessage = ' |-Skipping ' + DB_NAME(@dbid) + '. No memory optimized filegroup was found...'
  8601. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT;
  8602. END;*/
  8603. END;
  8604. UPDATE #tmpdbs0
  8605. SET isdone = 1
  8606. WHERE [dbid] = @dbid;
  8607. END
  8608. END;
  8609. IF EXISTS (SELECT TOP 1 database_id FROM #tmpXIS WHERE isdone = 0)
  8610. BEGIN
  8611. RAISERROR (' |-Gathering additional data on xtp hash indexes...', 10, 1) WITH NOWAIT;
  8612. WHILE (SELECT COUNT(database_id) FROM #tmpXIS WHERE isdone = 0) > 0
  8613. BEGIN
  8614. SELECT TOP 1 @dbid = database_id, @objectid = [object_id], @indexid = [index_id], @schema_name = [schema_name], @table_name = [table_name], @KeyCols = KeyCols FROM #tmpXIS WHERE isdone = 0
  8615. SELECT @sqlcmd = 'USE ' + QUOTENAME(DB_NAME(@dbid)) + '; SELECT @distinctCntOUT = COUNT(*), @OptimBucketCntOUT = POWER(2,CEILING(LOG(CASE WHEN COUNT(*) = 0 THEN 1 ELSE COUNT(*) END)/LOG(2))) FROM (SELECT DISTINCT ' + @KeyCols + ' FROM ' + @schema_name + '.' + @table_name + ') t1;'
  8616. SET @params = N'@distinctCntOUT bigint OUTPUT, @OptimBucketCntOUT bigint OUTPUT';
  8617. EXECUTE sp_executesql @sqlcmd, @params, @distinctCntOUT=@distinctCnt OUTPUT, @OptimBucketCntOUT=@OptimBucketCnt OUTPUT;
  8618. UPDATE #tmpXIS
  8619. SET distinctCnt = @distinctCnt, OptimBucketCnt = @OptimBucketCnt, isdone = 1
  8620. WHERE database_id = @dbid AND [object_id] = @objectid AND [index_id] = @indexid;
  8621. END;
  8622. END;
  8623. IF (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND [type] <= 2) > 0
  8624. BEGIN
  8625. RAISERROR (' |-Gathering sys.dm_db_index_physical_stats data...', 10, 1) WITH NOWAIT;
  8626. WHILE (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND [type] <= 2) > 0
  8627. BEGIN
  8628. SELECT TOP 1 @dbid = database_id, @objectid = [object_id], @indexid = index_id, @partition_nr = partition_number
  8629. FROM #tblWorking WHERE is_done = 0 AND [type] <= 2
  8630. INSERT INTO #tmpIPS
  8631. SELECT ps.database_id, ps.[object_id], ps.index_id, ps.partition_number, SUM(ps.avg_fragmentation_in_percent), SUM(ps.page_count),
  8632. CAST((SUM(ps.page_count)*8)/1024 AS DECIMAL(26,3)) AS [size_MB], ps.record_count, ps.forwarded_record_count -- for heaps
  8633. FROM sys.dm_db_index_physical_stats(@dbid, @objectid, @indexid , @partition_nr, @ixfragscanmode) AS ps
  8634. WHERE /*ps.index_id > 0 -- ignore heaps
  8635. AND */ps.index_level = 0 -- leaf-level nodes only
  8636. AND ps.alloc_unit_type_desc = 'IN_ROW_DATA'
  8637. GROUP BY ps.database_id, ps.[object_id], ps.index_id, ps.partition_number, ps.record_count, ps.forwarded_record_count
  8638. OPTION (MAXDOP 2);
  8639. UPDATE #tblWorking
  8640. SET is_done = 1
  8641. WHERE database_id = @dbid AND [object_id] = @objectid AND index_id = @indexid AND partition_number = @partition_nr
  8642. END
  8643. END;
  8644. IF (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND type = 5) > 0
  8645. BEGIN
  8646. RAISERROR (' |-Gathering sys.column_store_row_groups data...', 10, 1) WITH NOWAIT;
  8647. WHILE (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND type IN (5,6)) > 0
  8648. BEGIN
  8649. SELECT TOP 1 @dbid = database_id, @objectid = [object_id], @indexid = index_id, @partition_nr = partition_number
  8650. FROM #tblWorking WHERE is_done = 0 AND type IN (5,6)
  8651. BEGIN TRY
  8652. SELECT @ColumnStoreGetIXSQL = 'SELECT @dbid_In, rg.object_id, rg.index_id, rg.partition_number, SUM((ISNULL(rg.deleted_rows,1)*100)/CASE WHEN rg.total_rows = 0 THEN 1 ELSE rg.total_rows END) AS [fragmentation], SUM(ISNULL(rg.size_in_bytes,1)/1024/8) AS [simulated_page_count], CAST(SUM(rg.size_in_bytes)/1024/1024 AS DECIMAL(26,3)) AS [size_MB], rg.total_rows, rg.delta_store_hobt_id, rg.row_group_id, rg.state, rg.state_description
  8653. FROM [' + DB_NAME(@dbid) + '].sys.column_store_row_groups rg
  8654. WHERE rg.object_id = @objectid_In
  8655. AND rg.index_id = @indexid_In
  8656. AND rg.partition_number = @partition_nr_In
  8657. --AND rg.state = 3 -- Only COMPRESSED row groups
  8658. GROUP BY rg.object_id, rg.index_id, rg.partition_number, rg.total_rows, rg.delta_store_hobt_id, rg.row_group_id, rg.state, rg.state_description
  8659. OPTION (MAXDOP 2)'
  8660. SET @ColumnStoreGetIXSQL_Param = N'@dbid_In int, @objectid_In int, @indexid_In int, @partition_nr_In int';
  8661. INSERT INTO #tmpIPS_CI ([database_id], [object_id], [index_id], [partition_number], fragmentation, [page_count], [size_MB], record_count, delta_store_hobt_id, row_group_id, [state], state_description)
  8662. EXECUTE sp_executesql @ColumnStoreGetIXSQL, @ColumnStoreGetIXSQL_Param, @dbid_In = @dbid, @objectid_In = @objectid, @indexid_In = @indexid, @partition_nr_In = @partition_nr;
  8663. END TRY
  8664. BEGIN CATCH
  8665. SET @ErrorMessage = ' |-Error ' + CONVERT(VARCHAR(20),ERROR_NUMBER()) + ' has occurred while analyzing columnstore indexes. Message: ' + ERROR_MESSAGE() + ' (Line Number: ' + CAST(ERROR_LINE() AS VARCHAR(10)) + ')'
  8666. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8667. END CATCH
  8668. UPDATE #tblWorking
  8669. SET is_done = 1
  8670. WHERE database_id = @dbid AND [object_id] = @objectid AND index_id = @indexid AND partition_number = @partition_nr
  8671. END
  8672. END;
  8673. -- Check for index fragmentation over 5 pct when index has more than 1 extent allocated, or in CCI, all compressed row groups
  8674. IF (SELECT COUNT(*) FROM #tmpIPS WHERE fragmentation > 5 AND [page_count] > 8) > 0
  8675. OR (SELECT COUNT(*) FROM #tmpIPS_CI WHERE fragmentation > 5 AND [state] = 3) > 0
  8676. BEGIN
  8677. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Fragmentation' AS [Check], '[WARNING: Some databases have fragmented indexes. It is recommended to remove fragmentation on a regular basis to maintain performance]' AS [Deviation]
  8678. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Fragmentation' AS [Check], wk.database_name, wk.[schema_name], wk.[object_name], wk.index_name, wk.type_desc AS index_type, ips.partition_number, ips.fragmentation,
  8679. ips.page_count, ips.[size_MB], ips.record_count, ips.forwarded_record_count, -- for heaps
  8680. NULL AS row_group_id, NULL AS [Comment]
  8681. FROM #tmpIPS ips
  8682. INNER JOIN #tblWorking wk ON ips.database_id = wk.database_id AND ips.[object_id] = wk.[object_id] AND ips.index_id = wk.index_id AND ips.partition_number = wk.partition_number
  8683. WHERE ips.fragmentation > 5 AND ips.[page_count] > 8
  8684. UNION ALL
  8685. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Fragmentation' AS [Check], wk.database_name, wk.[schema_name], wk.[object_name], wk.index_name, wk.type_desc AS index_type, ipsci.partition_number, ipsci.fragmentation,
  8686. ipsci.page_count, ipsci.[size_MB], ipsci.record_count, NULL AS forwarded_record_count, ipsci.row_group_id,
  8687. 'Fragmentation for CCI is the ratio of deleted_rows to total_rows; Page count is a simulated value coming from the size in bytes taken by the index]' AS [Comment]
  8688. FROM #tmpIPS_CI ipsci
  8689. INNER JOIN #tblWorking wk ON ipsci.database_id = wk.database_id AND ipsci.[object_id] = wk.[object_id] AND ipsci.index_id = wk.index_id AND ipsci.partition_number = wk.partition_number
  8690. WHERE ipsci.fragmentation > 5 AND ipsci.[state] = 3
  8691. ORDER BY fragmentation DESC, [page_count] ASC
  8692. END
  8693. ELSE
  8694. BEGIN
  8695. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Fragmentation' AS [Check], '[OK]' AS [Deviation]
  8696. END;
  8697. IF @sqlmajorver >= 12
  8698. BEGIN
  8699. -- For the below values, your mileage may vary. Assuming more than 50 percent empty buckets and an average chain length over 5 requires investigation
  8700. -- http://blogs.technet.com/b/dataplatforminsider/archive/2014/01/30/in-memory-oltp-index-troubleshooting-part-ii.aspx
  8701. IF (SELECT COUNT(*) FROM #tmpXIS WHERE FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) > 50 AND [avg_chain_length] > 5) > 0
  8702. BEGIN
  8703. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_AvgChain_EmptyBuckets' AS [Check], '[WARNING: Some databases have high avg chain lenght (>5) and high empty buckets count (>50 pct). Verify if there are many rows with duplicate index key values or there is a skew in the key values]' AS [Deviation]
  8704. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_AvgChain_EmptyBuckets' AS [Check], DB_NAME([database_id]) AS [database_name], [schema_name], [table_name], [index_name], [type_desc] AS index_type,
  8705. distinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8706. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8707. FROM #tmpXIS
  8708. WHERE FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) > 50 AND [avg_chain_length] > 5
  8709. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8710. END
  8711. ELSE
  8712. BEGIN
  8713. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_AvgChain_EmptyBuckets' AS [Check], '[OK]' AS [Deviation]
  8714. END;
  8715. IF (SELECT COUNT(*) FROM #tmpXIS WHERE total_bucket_count > distinctCnt) > 0
  8716. BEGIN
  8717. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooManyBuckets' AS [Check], '[WARNING: Some databases have a total bucket count larger than the number of distinct rows in the table, which is wasting memory and marginally slowing down full table scans]' AS [Deviation]
  8718. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooManyBuckets' AS [Check], DB_NAME([database_id]) AS [database_name], [schema_name], [table_name], [index_name], [type_desc] AS index_type,
  8719. distinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8720. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8721. FROM #tmpXIS
  8722. WHERE total_bucket_count > distinctCnt
  8723. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8724. END
  8725. ELSE
  8726. BEGIN
  8727. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooManyBuckets' AS [Check], '[OK]' AS [Deviation]
  8728. END;
  8729. IF (SELECT COUNT(*) FROM #tmpXIS WHERE total_bucket_count < distinctCnt) > 0
  8730. BEGIN
  8731. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooFewBuckets' AS [Check], '[WARNING: Some databases have a total bucket count smaller than the number of distinct rows in the table, which leads to chaining records]' AS [Deviation]
  8732. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooFewBuckets' AS [Check], DB_NAME([database_id]) AS [database_name], [schema_name], [table_name], [index_name], [type_desc] AS index_type,
  8733. distinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8734. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8735. FROM #tmpXIS
  8736. WHERE total_bucket_count < distinctCnt
  8737. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8738. END
  8739. ELSE
  8740. BEGIN
  8741. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooFewBuckets' AS [Check], '[OK]' AS [Deviation]
  8742. END;
  8743. -- For the below values, your mileage may vary. Assuming more than 5 percent retries requires investigation .
  8744. -- https://msdn.microsoft.com/en-us/library/dn645468.aspx
  8745. IF (SELECT COUNT(*) FROM #tmpXNCIS WHERE FLOOR((CAST(page_update_retry_count AS FLOAT)/CASE WHEN page_update_count = 0 THEN 1 ELSE page_update_count END) * 100) > 5
  8746. OR FLOOR((CAST(page_consolidation_retry_count AS FLOAT)/CASE WHEN page_consolidation_count = 0 THEN 1 ELSE page_consolidation_count END) * 100) > 5
  8747. OR FLOOR((CAST(page_split_retry_count AS FLOAT)/CASE WHEN page_split_count = 0 THEN 1 ELSE page_split_count END) * 100) > 5
  8748. OR FLOOR((CAST(key_split_retry_count AS FLOAT)/CASE WHEN key_split_count = 0 THEN 1 ELSE key_split_count END) * 100) > 5
  8749. OR FLOOR((CAST(page_merge_retry_count AS FLOAT)/CASE WHEN page_merge_count = 0 THEN 1 ELSE page_merge_count END) * 100) > 5
  8750. OR FLOOR((CAST(key_merge_retry_count AS FLOAT)/CASE WHEN key_merge_count = 0 THEN 1 ELSE key_merge_count END) * 100) > 5
  8751. ) > 0
  8752. BEGIN
  8753. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_RangeIX_Health' AS [Check], '[WARNING: Some databases have retry count over 5 percent of total, indicating possible concurrency issues]' AS [Deviation]
  8754. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_RangeIX_Health' AS [Category], DB_NAME([database_id]) AS [database_name], [schema_name], [table_name], [index_name], [type_desc] AS index_type,
  8755. delta_pages, internal_pages, leaf_pages,
  8756. page_update_count, page_update_retry_count, FLOOR((CAST(page_update_retry_count AS FLOAT)/CASE WHEN page_update_count = 0 THEN 1 ELSE page_update_count END) * 100) AS [page_update_retry_pct_of_total],
  8757. page_consolidation_count, page_consolidation_retry_count, FLOOR((CAST(page_consolidation_retry_count AS FLOAT)/CASE WHEN page_consolidation_count = 0 THEN 1 ELSE page_consolidation_count END) * 100) AS [page_consolidation_retry_pct_of_total],
  8758. page_split_count, page_split_retry_count, FLOOR((CAST(page_split_retry_count AS FLOAT)/CASE WHEN page_split_count = 0 THEN 1 ELSE page_split_count END) * 100) AS [page_split_retry_pct_of_total],
  8759. key_split_count, key_split_retry_count, FLOOR((CAST(key_split_retry_count AS FLOAT)/CASE WHEN key_split_count = 0 THEN 1 ELSE key_split_count END) * 100) AS [key_split_retry_pct_of_total],
  8760. page_merge_count, page_merge_retry_count, FLOOR((CAST(page_merge_retry_count AS FLOAT)/CASE WHEN page_merge_count = 0 THEN 1 ELSE page_merge_count END) * 100) AS [page_merge_retry_pct_of_total],
  8761. key_merge_count, key_merge_retry_count, FLOOR((CAST(key_merge_retry_count AS FLOAT)/CASE WHEN key_merge_count = 0 THEN 1 ELSE key_merge_count END) * 100) AS [key_merge_retry_pct_of_total]
  8762. FROM #tmpXNCIS
  8763. WHERE FLOOR((CAST(page_update_retry_count AS FLOAT)/CASE WHEN page_update_count = 0 THEN 1 ELSE page_update_count END) * 100) > 5
  8764. OR FLOOR((CAST(page_consolidation_retry_count AS FLOAT)/CASE WHEN page_consolidation_count = 0 THEN 1 ELSE page_consolidation_count END) * 100) > 5
  8765. OR FLOOR((CAST(page_split_retry_count AS FLOAT)/CASE WHEN page_split_count = 0 THEN 1 ELSE page_split_count END) * 100) > 5
  8766. OR FLOOR((CAST(key_split_retry_count AS FLOAT)/CASE WHEN key_split_count = 0 THEN 1 ELSE key_split_count END) * 100) > 5
  8767. OR FLOOR((CAST(page_merge_retry_count AS FLOAT)/CASE WHEN page_merge_count = 0 THEN 1 ELSE page_merge_count END) * 100) > 5
  8768. OR FLOOR((CAST(key_merge_retry_count AS FLOAT)/CASE WHEN key_merge_count = 0 THEN 1 ELSE key_merge_count END) * 100) > 5
  8769. ORDER BY [database_name], [schema_name], table_name, [leaf_pages] DESC;
  8770. END;
  8771. END;
  8772. END
  8773. ELSE
  8774. BEGIN
  8775. RAISERROR(' |- [INFORMATION: "Index Health Analysis" check is disabled]', 10, 1, N'disallow_ixfrag')
  8776. --RETURN
  8777. END;
  8778. --------------------------------------------------------------------------------------------------------------------------------
  8779. -- Duplicate or Redundant indexes subsection (clustered, non-clustered, clustered and non-clustered columnstore indexes only)
  8780. --------------------------------------------------------------------------------------------------------------------------------
  8781. IF @ptochecks = 1
  8782. BEGIN
  8783. RAISERROR (N' |-Starting Duplicate or Redundant indexes', 10, 1) WITH NOWAIT
  8784. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  8785. DROP TABLE #tblIxs1;
  8786. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  8787. CREATE TABLE #tblIxs1 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  8788. [indexID] int, [indexName] VARCHAR(200), [indexType] tinyint, is_primary_key bit, [is_unique_constraint] bit, is_unique bit, is_disabled bit, fill_factor tinyint, is_padded bit, has_filter bit, filter_definition NVARCHAR(max),
  8789. KeyCols VARCHAR(4000), KeyColsOrdered VARCHAR(4000), IncludedCols VARCHAR(4000) NULL, IncludedColsOrdered VARCHAR(4000) NULL, AllColsOrdered VARCHAR(4000) NULL, [KeyCols_data_length_bytes] int,
  8790. CONSTRAINT PK_Ixs PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]));
  8791. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  8792. DROP TABLE #tblCode;
  8793. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  8794. CREATE TABLE #tblCode ([DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [indexName] VARCHAR(200), type_desc NVARCHAR(60));
  8795. UPDATE #tmpdbs1
  8796. SET isdone = 0;
  8797. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  8798. BEGIN
  8799. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  8800. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8801. USE ' + QUOTENAME(@dbname) + ';
  8802. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  8803. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, mi.index_id AS indexID,
  8804. mi.[name] AS Index_Name, mi.[type] AS [indexType], mi.is_primary_key, mi.[is_unique_constraint], mi.is_unique, mi.is_disabled,
  8805. mi.fill_factor, mi.is_padded, ' + CASE WHEN @sqlmajorver > 9 THEN 'mi.has_filter, mi.filter_definition,' ELSE 'NULL, NULL,' END + '
  8806. SUBSTRING(( SELECT '','' + ac.name FROM sys.tables AS st
  8807. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8808. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8809. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8810. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  8811. ORDER BY ic.key_ordinal
  8812. FOR XML PATH('''')), 2, 8000) AS KeyCols,
  8813. SUBSTRING(( SELECT '','' + ac.name FROM sys.tables AS st
  8814. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8815. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8816. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8817. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  8818. ORDER BY ac.name
  8819. FOR XML PATH('''')), 2, 8000) AS KeyColsOrdered,
  8820. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8821. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8822. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8823. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8824. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 1
  8825. ORDER BY ic.key_ordinal
  8826. FOR XML PATH('''')), 2, 8000) AS IncludedCols,
  8827. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8828. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8829. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8830. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8831. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 1
  8832. ORDER BY ac.name
  8833. FOR XML PATH('''')), 2, 8000) AS IncludedColsOrdered,
  8834. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8835. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8836. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8837. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8838. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id
  8839. ORDER BY ac.name
  8840. FOR XML PATH('''')), 2, 8000) AS AllColsOrdered,
  8841. (SELECT SUM(CASE sty.name WHEN ''nvarchar'' THEN sc.max_length/2 ELSE sc.max_length END) FROM sys.indexes AS i
  8842. INNER JOIN sys.tables AS t ON t.[object_id] = i.[object_id]
  8843. INNER JOIN sys.schemas ss ON ss.[schema_id] = t.[schema_id]
  8844. INNER JOIN sys.index_columns AS sic ON sic.object_id = mst.object_id AND sic.index_id = mi.index_id
  8845. INNER JOIN sys.columns AS sc ON sc.object_id = t.object_id AND sc.column_id = sic.column_id
  8846. INNER JOIN sys.types AS sty ON sc.user_type_id = sty.user_type_id
  8847. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND sic.key_ordinal > 0) AS [KeyCols_data_length_bytes]
  8848. FROM sys.indexes AS mi
  8849. INNER JOIN sys.tables AS mst ON mst.[object_id] = mi.[object_id]
  8850. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8851. WHERE mi.type IN (1,2,5,6) AND mst.is_ms_shipped = 0
  8852. ORDER BY objectName
  8853. OPTION (MAXDOP 2);'
  8854. BEGIN TRY
  8855. INSERT INTO #tblIxs1
  8856. EXECUTE sp_executesql @sqlcmd
  8857. END TRY
  8858. BEGIN CATCH
  8859. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8860. SELECT @ErrorMessage = 'Duplicate or Redundant indexes subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8861. RAISERROR (@ErrorMessage, 16, 1);
  8862. END CATCH
  8863. UPDATE #tmpdbs1
  8864. SET isdone = 1
  8865. WHERE [dbid] = @dbid;
  8866. END
  8867. IF (SELECT COUNT(*) FROM #tblIxs1 I INNER JOIN #tblIxs1 I2 ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8868. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8869. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))) > 0
  8870. BEGIN
  8871. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes' AS [Check], '[WARNING: Some databases have duplicate indexes. It is recommended to revise the need to maintain all these objects as soon as possible]' AS [Deviation]
  8872. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes' AS [Information], I.[DatabaseName] AS [Database_Name], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name],
  8873. I.[indexID], I.[indexName] AS [Index_Name], I.is_primary_key, I.is_unique_constraint, I.is_unique, I.fill_factor, I.is_padded, I.has_filter, I.filter_definition,
  8874. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  8875. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8876. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8877. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8878. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8879. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8880. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8881. GROUP BY I.[databaseID], I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered, I.is_primary_key, I.is_unique_constraint, I.is_unique, I.fill_factor, I.is_padded, I.has_filter, I.filter_definition
  8882. ORDER BY I.DatabaseName, I.[objectName], I.[indexID]
  8883. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes_toDrop' AS [Check], I.[DatabaseName], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name],
  8884. I.[indexID], I.[indexName] AS [Index_Name], I.is_primary_key, I.is_unique_constraint, I.is_unique, I.fill_factor, I.is_padded, I.has_filter, I.filter_definition,
  8885. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  8886. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8887. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8888. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8889. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8890. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8891. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8892. AND I.[indexID] NOT IN (
  8893. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8894. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8895. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8896. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8897. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8898. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8899. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8900. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8901. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8902. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8903. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8904. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8905. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8906. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8907. ))
  8908. GROUP BY I.[databaseID], I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered, I.is_primary_key, I.is_unique_constraint, I.is_unique, I.fill_factor, I.is_padded, I.has_filter, I.filter_definition
  8909. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8910. DECLARE @strSQL2 NVARCHAR(4000), @DatabaseName sysname, @indexName sysname
  8911. IF @gen_scripts = 1
  8912. BEGIN
  8913. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8914. PRINT CHAR(10) + '/*
  8915. NOTE: It is possible that a clustered index (unique or not) is among the duplicate indexes to be dropped, namely if a non-clustered primary key exists on the table.
  8916. In this case, make the appropriate changes in the clustered index (making it unique and/or primary key in this case), and drop the non-clustered instead.
  8917. */'
  8918. PRINT CHAR(10) + '--############# Existing Duplicate indexes drop statements #############' + CHAR(10)
  8919. DECLARE Dup_Stats CURSOR FAST_FORWARD FOR SELECT 'USE ' + I.[DatabaseName] + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'''+ I.[indexName] + ''')' + CHAR(10) +
  8920. 'DROP INDEX ' + QUOTENAME(I.[indexName]) + ' ON ' + QUOTENAME(I.[schemaName]) + '.' + QUOTENAME(I.[objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  8921. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8922. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8923. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8924. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8925. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8926. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8927. AND I.[indexID] NOT IN (
  8928. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8929. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8930. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8931. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8932. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8933. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8934. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8935. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8936. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8937. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8938. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8939. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8940. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8941. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8942. ))
  8943. GROUP BY I.[databaseID], I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered
  8944. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8945. OPEN Dup_Stats
  8946. FETCH NEXT FROM Dup_Stats INTO @strSQL2
  8947. WHILE (@@FETCH_STATUS = 0)
  8948. BEGIN
  8949. PRINT @strSQL2
  8950. FETCH NEXT FROM Dup_Stats INTO @strSQL2
  8951. END
  8952. CLOSE Dup_Stats
  8953. DEALLOCATE Dup_Stats
  8954. PRINT '--############# Ended Duplicate indexes drop statements #############' + CHAR(10)
  8955. END;
  8956. RAISERROR (N' |-Starting index search in sql modules...', 10, 1) WITH NOWAIT
  8957. DECLARE Dup_HardCoded CURSOR FAST_FORWARD FOR SELECT I.[DatabaseName],I.[indexName]
  8958. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8959. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8960. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8961. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8962. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8963. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8964. AND I.[indexID] NOT IN (
  8965. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8966. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8967. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8968. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8969. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8970. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8971. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8972. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8973. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8974. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8975. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8976. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8977. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8978. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8979. ))
  8980. GROUP BY I.[databaseID], I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered
  8981. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8982. OPEN Dup_HardCoded
  8983. FETCH NEXT FROM Dup_HardCoded INTO @DatabaseName,@indexName
  8984. WHILE (@@FETCH_STATUS = 0)
  8985. BEGIN
  8986. SET @sqlcmd = 'USE [' + @DatabaseName + '];
  8987. SELECT ''' + @DatabaseName + ''' AS [database], ss.name AS [schemaName], so.name AS [objectName], ''' + @indexName + ''' AS indexName, so.type_desc
  8988. FROM sys.sql_modules sm
  8989. INNER JOIN sys.objects so ON sm.[object_id] = so.[object_id]
  8990. INNER JOIN sys.schemas ss ON ss.[schema_id] = so.[schema_id]
  8991. WHERE sm.[definition] LIKE ''%' + @indexName + '%'''
  8992. INSERT INTO #tblCode
  8993. EXECUTE sp_executesql @sqlcmd
  8994. FETCH NEXT FROM Dup_HardCoded INTO @DatabaseName,@indexName
  8995. END
  8996. CLOSE Dup_HardCoded
  8997. DEALLOCATE Dup_HardCoded
  8998. RAISERROR (N' |-Ended index search in sql modules', 10, 1) WITH NOWAIT
  8999. IF (SELECT COUNT(*) FROM #tblCode) > 0
  9000. BEGIN
  9001. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes_HardCoded' AS [Check], '[WARNING: Some sql modules have references to these duplicate indexes. Fix these references to be able to drop duplicate indexes]' AS [Deviation]
  9002. SELECT [DatabaseName],[schemaName],[objectName] AS [referedIn_objectName], indexName AS [referenced_indexName], type_desc AS [refered_objectType]
  9003. FROM #tblCode
  9004. ORDER BY [DatabaseName], [objectName]
  9005. END
  9006. ELSE
  9007. BEGIN
  9008. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes_HardCoded' AS [Check], '[OK]' AS [Deviation]
  9009. END
  9010. END
  9011. ELSE
  9012. BEGIN
  9013. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes' AS [Check], '[OK]' AS [Deviation]
  9014. END;
  9015. IF (SELECT COUNT(*) FROM #tblIxs1 I INNER JOIN #tblIxs1 I2 ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  9016. AND (I.[KeyCols] <> I2.[KeyCols] OR I.IncludedCols <> I2.IncludedCols)
  9017. AND (((I.[KeyColsOrdered] <> I2.[KeyColsOrdered] OR I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9018. AND ((CASE WHEN I.IncludedColsOrdered IS NULL THEN I.[KeyColsOrdered] ELSE I.[KeyColsOrdered] + ',' + I.IncludedColsOrdered END) = (CASE WHEN I2.IncludedColsOrdered IS NULL THEN I2.[KeyColsOrdered] ELSE I2.[KeyColsOrdered] + ',' + I2.IncludedColsOrdered END)
  9019. OR I.[AllColsOrdered] = I2.[AllColsOrdered]))
  9020. OR (I.[KeyColsOrdered] <> I2.[KeyColsOrdered] AND I.IncludedColsOrdered = I2.IncludedColsOrdered)
  9021. OR (I.[KeyColsOrdered] = I2.[KeyColsOrdered] AND I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9022. OR ((I.[AllColsOrdered] = I2.[AllColsOrdered] AND I.filter_definition IS NULL AND I2.filter_definition IS NOT NULL) OR (I.[AllColsOrdered] = I2.[AllColsOrdered] AND I.filter_definition IS NOT NULL AND I2.filter_definition IS NULL)))
  9023. AND I.indexID NOT IN (SELECT I3.[indexID]
  9024. FROM #tblIxs1 I3 INNER JOIN #tblIxs1 I4
  9025. ON I3.[databaseID] = I4.[databaseID] AND I3.[objectID] = I4.[objectID] AND I3.[indexID] <> I4.[indexID]
  9026. AND I3.[KeyCols] = I4.[KeyCols] AND (I3.IncludedCols = I4.IncludedCols OR (I3.IncludedCols IS NULL AND I4.IncludedCols IS NULL))
  9027. WHERE I3.[databaseID] = I.[databaseID] AND I3.[objectID] = I.[objectID]
  9028. GROUP BY I3.[indexID])
  9029. WHERE I.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9030. AND I2.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9031. AND I.is_unique_constraint = 0 -- no unique constraints
  9032. AND I2.is_unique_constraint = 0 -- no unique constraints
  9033. ) > 0
  9034. BEGIN
  9035. SELECT 'Index_and_Stats_checks' AS [Category], 'Redundant_Indexes' AS [Check], '[WARNING: Some databases have possibly redundant indexes. It is recommended to revise the need to maintain all these objects as soon as possible]' AS [Deviation]
  9036. SELECT 'Index_and_Stats_checks' AS [Category], 'Redundant_Indexes' AS [Information], I.[DatabaseName] AS [Database_Name], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name],
  9037. I.[indexID], I.[indexName] AS [Index_Name], I.is_unique, I.fill_factor, I.is_padded, I.has_filter, I.filter_definition,
  9038. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedColsOrdered IS NULL THEN I.[KeyColsOrdered] ELSE I.[KeyColsOrdered] + ',' + I.IncludedColsOrdered END AS [KeyInclColsOrdered]
  9039. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  9040. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  9041. AND (((I.[KeyColsOrdered] <> I2.[KeyColsOrdered] OR I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9042. AND ((CASE WHEN I.IncludedColsOrdered IS NULL THEN I.[KeyColsOrdered] ELSE I.[KeyColsOrdered] + ',' + I.IncludedColsOrdered END) = (CASE WHEN I2.IncludedColsOrdered IS NULL THEN I2.[KeyColsOrdered] ELSE I2.[KeyColsOrdered] + ',' + I2.IncludedColsOrdered END)
  9043. OR I.[AllColsOrdered] = I2.[AllColsOrdered]))
  9044. OR (I.[KeyColsOrdered] <> I2.[KeyColsOrdered] AND I.IncludedColsOrdered = I2.IncludedColsOrdered)
  9045. OR (I.[KeyColsOrdered] = I2.[KeyColsOrdered] AND I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9046. OR ((I.[AllColsOrdered] = I2.[AllColsOrdered] AND I.filter_definition IS NULL AND I2.filter_definition IS NOT NULL) OR (I.[AllColsOrdered] = I2.[AllColsOrdered] AND I.filter_definition IS NOT NULL AND I2.filter_definition IS NULL)))
  9047. AND I.indexID NOT IN (SELECT I3.[indexID]
  9048. FROM #tblIxs1 I3 INNER JOIN #tblIxs1 I4
  9049. ON I3.[databaseID] = I4.[databaseID] AND I3.[objectID] = I4.[objectID] AND I3.[indexID] <> I4.[indexID]
  9050. AND I3.[KeyCols] = I4.[KeyCols] AND (I3.IncludedCols = I4.IncludedCols OR (I3.IncludedCols IS NULL AND I4.IncludedCols IS NULL))
  9051. WHERE I3.[databaseID] = I.[databaseID] AND I3.[objectID] = I.[objectID]
  9052. GROUP BY I3.[indexID])
  9053. WHERE I.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9054. AND I2.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9055. AND I.is_unique_constraint = 0 -- no unique constraints
  9056. AND I2.is_unique_constraint = 0 -- no unique constraints
  9057. GROUP BY I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered, I.is_unique, I.fill_factor, I.is_padded, I.has_filter, I.filter_definition
  9058. ORDER BY I.DatabaseName, I.[objectName], I.[KeyColsOrdered], I.IncludedColsOrdered, I.[indexID]
  9059. END
  9060. ELSE
  9061. BEGIN
  9062. SELECT 'Index_and_Stats_checks' AS [Category], 'Redundant_Indexes' AS [Check], '[OK]' AS [Deviation]
  9063. END;
  9064. END;
  9065. --------------------------------------------------------------------------------------------------------------------------------
  9066. -- Unused and rarely used indexes subsection
  9067. --------------------------------------------------------------------------------------------------------------------------------
  9068. IF @ptochecks = 1
  9069. BEGIN
  9070. RAISERROR (N' |-Starting Unused and rarely used indexes', 10, 1) WITH NOWAIT
  9071. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  9072. DROP TABLE #tblIxs2;
  9073. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  9074. CREATE TABLE #tblIxs2 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  9075. [indexID] int, [indexName] VARCHAR(200), [Hits] bigint NULL, [Reads_Ratio] DECIMAL(5,2), [Writes_Ratio] DECIMAL(5,2),
  9076. user_updates bigint, last_user_seek DATETIME NULL, last_user_scan DATETIME NULL, last_user_lookup DATETIME NULL,
  9077. last_user_update DATETIME NULL, is_unique bit, [type] tinyint, is_primary_key bit, is_unique_constraint bit, is_disabled bit,
  9078. CONSTRAINT PK_Ixs2 PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]))
  9079. UPDATE #tmpdbs1
  9080. SET isdone = 0;
  9081. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9082. BEGIN
  9083. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9084. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9085. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9086. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, si.index_id AS indexID, si.[name] AS Index_Name,
  9087. (s.user_seeks + s.user_scans + s.user_lookups) AS [Hits],
  9088. RTRIM(CONVERT(NVARCHAR(10),CAST(CASE WHEN (s.user_seeks + s.user_scans + s.user_lookups) = 0 THEN 0 ELSE CONVERT(REAL, (s.user_seeks + s.user_scans + s.user_lookups)) * 100 /
  9089. CASE (s.user_seeks + s.user_scans + s.user_lookups + s.user_updates) WHEN 0 THEN 1 ELSE CONVERT(REAL, (s.user_seeks + s.user_scans + s.user_lookups + s.user_updates)) END END AS DECIMAL(18,2)))) AS [Reads_Ratio],
  9090. RTRIM(CONVERT(NVARCHAR(10),CAST(CASE WHEN s.user_updates = 0 THEN 0 ELSE CONVERT(REAL, s.user_updates) * 100 /
  9091. CASE (s.user_seeks + s.user_scans + s.user_lookups + s.user_updates) WHEN 0 THEN 1 ELSE CONVERT(REAL, (s.user_seeks + s.user_scans + s.user_lookups + s.user_updates)) END END AS DECIMAL(18,2)))) AS [Writes_Ratio],
  9092. s.user_updates,
  9093. MAX(s.last_user_seek) AS last_user_seek,
  9094. MAX(s.last_user_scan) AS last_user_scan,
  9095. MAX(s.last_user_lookup) AS last_user_lookup,
  9096. MAX(s.last_user_update) AS last_user_update,
  9097. si.is_unique, si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9098. FROM sys.indexes AS si (NOLOCK)
  9099. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  9100. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = si.[object_id]
  9101. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9102. INNER JOIN sys.dm_db_index_usage_stats AS s (NOLOCK) ON s.database_id = ' + CONVERT(VARCHAR(8), @dbid) + '
  9103. AND s.object_id = si.object_id AND s.index_id = si.index_id
  9104. WHERE mst.is_ms_shipped = 0
  9105. --AND OBJECTPROPERTY(o.object_id,''IsUserTable'') = 1 -- sys.tables only returns type U
  9106. AND si.type IN (2,6) -- non-clustered and non-clustered columnstore indexes only
  9107. AND si.is_primary_key = 0 -- no primary keys
  9108. AND si.is_unique_constraint = 0 -- no unique constraints
  9109. --AND si.is_unique = 0 -- no alternate keys
  9110. GROUP BY mst.[object_id], t.[name], mst.[name], si.index_id, si.[name], s.user_seeks, s.user_scans, s.user_lookups, s.user_updates, si.is_unique,
  9111. si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9112. ORDER BY objectName
  9113. OPTION (MAXDOP 2);'
  9114. BEGIN TRY
  9115. INSERT INTO #tblIxs2
  9116. EXECUTE sp_executesql @sqlcmd
  9117. END TRY
  9118. BEGIN CATCH
  9119. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9120. SELECT @ErrorMessage = 'Unused and rarely used indexes subsection - Error raised in TRY block 1 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9121. RAISERROR (@ErrorMessage, 16, 1);
  9122. END CATCH
  9123. UPDATE #tmpdbs1
  9124. SET isdone = 1
  9125. WHERE [dbid] = @dbid
  9126. END
  9127. UPDATE #tmpdbs1
  9128. SET isdone = 0;
  9129. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9130. BEGIN
  9131. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9132. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9133. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9134. si.[object_id] AS objectID, t.name AS schemaName, OBJECT_NAME(si.[object_id], ' + CONVERT(VARCHAR(8), @dbid) + ') AS objectName, si.index_id AS indexID,
  9135. si.[name] AS Index_Name, 0, 0, 0, 0, NULL, NULL, NULL, NULL,
  9136. si.is_unique, si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9137. FROM sys.indexes AS si (NOLOCK)
  9138. INNER JOIN sys.objects AS so (NOLOCK) ON si.object_id = so.object_id
  9139. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = si.[object_id]
  9140. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9141. WHERE OBJECTPROPERTY(so.object_id,''IsUserTable'') = 1
  9142. AND mst.is_ms_shipped = 0
  9143. AND si.index_id NOT IN (SELECT s.index_id
  9144. FROM sys.dm_db_index_usage_stats s
  9145. WHERE s.object_id = si.object_id
  9146. AND si.index_id = s.index_id
  9147. AND database_id = ' + CONVERT(VARCHAR(8), @dbid) + ')
  9148. AND si.name IS NOT NULL
  9149. AND si.type IN (2,6) -- non-clustered and non-clustered columnstore indexes only
  9150. AND si.is_primary_key = 0 -- no primary keys
  9151. AND si.is_unique_constraint = 0 -- no unique constraints
  9152. --AND si.is_unique = 0 -- no alternate keys
  9153. '
  9154. BEGIN TRY
  9155. INSERT INTO #tblIxs2
  9156. EXECUTE sp_executesql @sqlcmd
  9157. END TRY
  9158. BEGIN CATCH
  9159. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9160. SELECT @ErrorMessage = 'Unused and rarely used indexes subsection - Error raised in TRY block 2 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9161. RAISERROR (@ErrorMessage, 16, 1);
  9162. END CATCH
  9163. UPDATE #tmpdbs1
  9164. SET isdone = 1
  9165. WHERE [dbid] = @dbid
  9166. END;
  9167. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 /*AND is_disabled = 0*/) > 0
  9168. BEGIN
  9169. SELECT 'Index_and_Stats_checks' AS [Category], 'Unused_Indexes' AS [Check], '[WARNING: Some databases have unused indexes. It is recommended to revise the need to maintain all these objects as soon as possible]' AS [Deviation]
  9170. SELECT 'Index_and_Stats_checks' AS [Category], 'Unused_Indexes_With_Updates' AS [Information], [DatabaseName] AS [Database_Name], schemaName AS [Schema_Name], [objectName] AS [Table_Name], [indexID], [indexName] AS [Index_Name], is_unique,
  9171. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9172. user_updates, last_user_update
  9173. FROM #tblIxs2
  9174. WHERE [Hits] = 0 AND last_user_update > 0
  9175. UNION ALL
  9176. SELECT 'Index_and_Stats_checks' AS [Category], 'Unused_Indexes_No_Updates' AS [Information], [DatabaseName] AS [Database_Name], schemaName AS [Schema_Name], [objectName] AS [Table_Name], [indexID], [indexName] AS [Index_Name], is_unique,
  9177. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9178. user_updates, last_user_update
  9179. FROM #tblIxs2
  9180. WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)
  9181. ORDER BY [Information], [Database_Name], [Table_Name], [R/W_Ratio] DESC;
  9182. IF @gen_scripts = 1
  9183. BEGIN
  9184. DECLARE @strSQL3 NVARCHAR(4000)
  9185. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9186. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 AND last_user_update > 0) > 0
  9187. BEGIN
  9188. PRINT CHAR(10) + '--############# Existing unused indexes with updates drop statements #############' + CHAR(10)
  9189. DECLARE Un_Stats CURSOR FAST_FORWARD FOR SELECT 'USE ' + [DatabaseName] + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'''+ [indexName] + ''')' + CHAR(10) +
  9190. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9191. FROM #tblIxs2
  9192. WHERE [Hits] = 0 AND last_user_update > 0
  9193. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC;
  9194. OPEN Un_Stats
  9195. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9196. WHILE (@@FETCH_STATUS = 0)
  9197. BEGIN
  9198. PRINT @strSQL3
  9199. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9200. END
  9201. CLOSE Un_Stats
  9202. DEALLOCATE Un_Stats
  9203. PRINT CHAR(10) + '--############# Ended unused indexes with updates drop statements #############' + CHAR(10)
  9204. END;
  9205. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)) > 0
  9206. BEGIN
  9207. PRINT CHAR(10) + '--############# Existing unused indexes with no updates drop statements #############' + CHAR(10)
  9208. DECLARE Un_Stats CURSOR FAST_FORWARD FOR SELECT 'USE ' + [DatabaseName] + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'''+ [indexName] + ''')' + CHAR(10) +
  9209. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9210. FROM #tblIxs2
  9211. WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)
  9212. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC;
  9213. OPEN Un_Stats
  9214. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9215. WHILE (@@FETCH_STATUS = 0)
  9216. BEGIN
  9217. PRINT @strSQL3
  9218. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9219. END
  9220. CLOSE Un_Stats
  9221. DEALLOCATE Un_Stats
  9222. PRINT CHAR(10) + '--############# Ended unused indexes with no updates drop statements #############' + CHAR(10)
  9223. END
  9224. END;
  9225. END
  9226. ELSE
  9227. BEGIN
  9228. SELECT 'Index_and_Stats_checks' AS [Category], 'Unused_Indexes' AS [Check], '[OK]' AS [Deviation]
  9229. END;
  9230. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] > 0 AND [Reads_Ratio] < 5 AND type IN (1,2,5,6) AND is_primary_key = 0 AND is_unique_constraint = 0 /*AND is_disabled = 0*/) > 0
  9231. BEGIN
  9232. SELECT 'Index_and_Stats_checks' AS [Category], 'Rarely_Used_Indexes' AS [Check], '[WARNING: Some databases have rarely used indexes. It is recommended to revise the need to maintain all these objects as soon as possible]' AS [Deviation]
  9233. SELECT 'Index_and_Stats_checks' AS [Category], 'Rarely_Used_Indexes' AS [Information], [DatabaseName] AS [Database_Name], schemaName AS [Schema_Name], [objectName] AS [Table_Name], [indexID], [indexName] AS [Index_Name], is_unique,
  9234. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9235. user_updates, last_user_seek, last_user_scan, last_user_lookup, last_user_update
  9236. FROM #tblIxs2
  9237. WHERE [Hits] > 0 AND [Reads_Ratio] < 5
  9238. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC
  9239. IF @gen_scripts = 1
  9240. BEGIN
  9241. DECLARE @strSQL4 NVARCHAR(4000)
  9242. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9243. PRINT CHAR(10) + '--############# Existing rarely used indexes drop statements #############' + CHAR(10)
  9244. DECLARE curRarUsed CURSOR FAST_FORWARD FOR SELECT 'USE ' + [DatabaseName] + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'''+ [indexName] + ''')' + CHAR(10) +
  9245. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9246. FROM #tblIxs2
  9247. WHERE [Hits] > 0 AND [Reads_Ratio] < 5
  9248. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC
  9249. OPEN curRarUsed
  9250. FETCH NEXT FROM curRarUsed INTO @strSQL4
  9251. WHILE (@@FETCH_STATUS = 0)
  9252. BEGIN
  9253. PRINT @strSQL4
  9254. FETCH NEXT FROM curRarUsed INTO @strSQL4
  9255. END
  9256. CLOSE curRarUsed
  9257. DEALLOCATE curRarUsed
  9258. PRINT '--############# Ended rarely used indexes drop statements #############' + CHAR(10)
  9259. END;
  9260. END
  9261. ELSE
  9262. BEGIN
  9263. SELECT 'Index_and_Stats_checks' AS [Category], 'Rarely_Used_Indexes' AS [Check], '[OK]' AS [Deviation]
  9264. END;
  9265. END;
  9266. --------------------------------------------------------------------------------------------------------------------------------
  9267. -- Indexes with large keys (> 900 bytes) subsection
  9268. --------------------------------------------------------------------------------------------------------------------------------
  9269. IF @ptochecks = 1
  9270. BEGIN
  9271. RAISERROR (N' |-Starting Indexes with large keys (> 900 bytes)', 10, 1) WITH NOWAIT
  9272. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [KeyCols_data_length_bytes] > 900) > 0
  9273. BEGIN
  9274. SELECT 'Index_and_Stats_checks' AS [Category], 'Large_Index_Key' AS [Check], '[WARNING: Some indexes have keys larger than 900 bytes. It is recommended to revise these]' AS [Deviation]
  9275. SELECT 'Index_and_Stats_checks' AS [Category], 'Large_Index_Key' AS [Information], I.[DatabaseName] AS [Database_Name], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name], I.[indexID], I.[indexName] AS [Index_Name],
  9276. I.KeyCols, [KeyCols_data_length_bytes]
  9277. FROM #tblIxs1 I
  9278. WHERE [KeyCols_data_length_bytes] > 900
  9279. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9280. END
  9281. ELSE
  9282. BEGIN
  9283. SELECT 'Index_and_Stats_checks' AS [Category], 'Large_Index_Key' AS [Check], '[OK]' AS [Deviation]
  9284. END;
  9285. END;
  9286. --------------------------------------------------------------------------------------------------------------------------------
  9287. -- Indexes with fill factor < 80 pct subsection
  9288. --------------------------------------------------------------------------------------------------------------------------------
  9289. IF @ptochecks = 1
  9290. BEGIN
  9291. RAISERROR (N' |-Starting Indexes with fill factor < 80 pct', 10, 1) WITH NOWAIT
  9292. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [fill_factor] BETWEEN 1 AND 79) > 0
  9293. BEGIN
  9294. SELECT 'Index_and_Stats_checks' AS [Category], 'Low_Fill_Factor' AS [Check], '[WARNING: Some indexes have a fill factor lower than 80 percent. Revise the need to maintain such a low value]' AS [Deviation]
  9295. SELECT 'Index_and_Stats_checks' AS [Category], 'Low_Fill_Factor' AS [Information], I.[DatabaseName] AS [Database_Name], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name], I.[indexID], I.[indexName] AS [Index_Name],
  9296. [fill_factor], I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  9297. FROM #tblIxs1 I
  9298. WHERE [fill_factor] BETWEEN 1 AND 79
  9299. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9300. END
  9301. ELSE
  9302. BEGIN
  9303. SELECT 'Index_and_Stats_checks' AS [Category], 'Low_Fill_Factor' AS [Check], '[OK]' AS [Deviation]
  9304. END;
  9305. END;
  9306. --------------------------------------------------------------------------------------------------------------------------------
  9307. -- Disabled indexes subsection
  9308. --------------------------------------------------------------------------------------------------------------------------------
  9309. IF @ptochecks = 1
  9310. BEGIN
  9311. RAISERROR (N' |-Starting Disabled indexes', 10, 1) WITH NOWAIT
  9312. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [is_disabled] = 1) > 0
  9313. BEGIN
  9314. SELECT 'Index_and_Stats_checks' AS [Category], 'Disabled_IXs' AS [Check], '[WARNING: Some indexes are disabled. Revise the need to maintain these]' AS [Deviation]
  9315. SELECT 'Index_and_Stats_checks' AS [Category], 'Disabled_IXs' AS [Information], I.[DatabaseName] AS [Database_Name], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name], I.[indexID], I.[indexName] AS [Index_Name],
  9316. CASE WHEN [indexType] = 1 THEN 'Clustered'
  9317. WHEN [indexType] = 2 THEN 'Non-clustered'
  9318. WHEN [indexType] = 3 THEN 'Clustered columnstore'
  9319. ELSE 'Non-clustered columnstore' END AS [Index_Type],
  9320. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  9321. FROM #tblIxs1 I
  9322. WHERE [is_disabled] = 1
  9323. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9324. END
  9325. ELSE
  9326. BEGIN
  9327. SELECT 'Index_and_Stats_checks' AS [Category], 'Disabled_IXs' AS [Check], '[OK]' AS [Deviation]
  9328. END;
  9329. END;
  9330. --------------------------------------------------------------------------------------------------------------------------------
  9331. -- Non-unique clustered indexes subsection
  9332. --------------------------------------------------------------------------------------------------------------------------------
  9333. IF @ptochecks = 1
  9334. BEGIN
  9335. RAISERROR (N' |-Starting Non-unique clustered indexes', 10, 1) WITH NOWAIT
  9336. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [is_unique] = 0 AND indexID = 1) > 0
  9337. BEGIN
  9338. SELECT 'Index_and_Stats_checks' AS [Category], 'NonUnique_CIXs' AS [Check], '[WARNING: Some clustered indexes are non-unique. Revise the need to have non-unique clustering keys to which a uniquefier is added]' AS [Deviation]
  9339. SELECT 'Index_and_Stats_checks' AS [Category], 'NonUnique_CIXs' AS [Information], I.[DatabaseName] AS [Database_Name], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name], I.[indexID], I.[indexName] AS [Index_Name], I.[KeyCols]
  9340. FROM #tblIxs1 I
  9341. WHERE [is_unique] = 0 AND indexID = 1
  9342. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName]
  9343. END
  9344. ELSE
  9345. BEGIN
  9346. SELECT 'Index_and_Stats_checks' AS [Category], 'NonUnique_CIXs' AS [Check], '[OK]' AS [Deviation]
  9347. END;
  9348. END;
  9349. --------------------------------------------------------------------------------------------------------------------------------
  9350. -- Clustered Indexes with GUIDs in key subsection
  9351. --------------------------------------------------------------------------------------------------------------------------------
  9352. IF @ptochecks = 1
  9353. BEGIN
  9354. RAISERROR (N' |-Starting Clustered Indexes with GUIDs in key', 10, 1) WITH NOWAIT
  9355. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  9356. DROP TABLE #tblIxs6;
  9357. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  9358. CREATE TABLE #tblIxs6 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  9359. [indexID] int, [indexName] VARCHAR(200), [indexType] tinyint, [is_unique_constraint] bit, is_unique bit, is_disabled bit, fill_factor tinyint, is_padded bit,
  9360. KeyCols VARCHAR(4000), KeyColsOrdered VARCHAR(4000), Key_has_GUID int,
  9361. CONSTRAINT PK_Ixs3 PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]));
  9362. UPDATE #tmpdbs1
  9363. SET isdone = 0;
  9364. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9365. BEGIN
  9366. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9367. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  9368. USE ' + QUOTENAME(@dbname) + ';
  9369. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9370. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, mi.index_id AS indexID,
  9371. mi.[name] AS Index_Name, mi.[type] AS [indexType], mi.[is_unique_constraint], mi.is_unique, mi.is_disabled,
  9372. mi.fill_factor, mi.is_padded,
  9373. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  9374. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  9375. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  9376. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9377. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  9378. ORDER BY ic.key_ordinal
  9379. FOR XML PATH('''')), 2, 8000) AS KeyCols,
  9380. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  9381. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  9382. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  9383. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9384. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  9385. ORDER BY ac.name
  9386. FOR XML PATH('''')), 2, 8000) AS KeyColsOrdered,
  9387. (SELECT COUNT(sty.name) FROM sys.indexes AS i
  9388. INNER JOIN sys.tables AS t ON t.[object_id] = i.[object_id]
  9389. INNER JOIN sys.schemas ss ON ss.[schema_id] = t.[schema_id]
  9390. INNER JOIN sys.index_columns AS sic ON sic.object_id = mst.object_id AND sic.index_id = mi.index_id
  9391. INNER JOIN sys.columns AS sc ON sc.object_id = t.object_id AND sc.column_id = sic.column_id
  9392. INNER JOIN sys.types AS sty ON sc.user_type_id = sty.user_type_id
  9393. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND sic.is_included_column = 0 AND sty.name = ''uniqueidentifier'') AS [Key_has_GUID]
  9394. FROM sys.indexes AS mi
  9395. INNER JOIN sys.tables AS mst ON mst.[object_id] = mi.[object_id]
  9396. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  9397. WHERE mi.type = 1 AND mi.is_unique_constraint = 0
  9398. AND mst.is_ms_shipped = 0
  9399. --AND OBJECTPROPERTY(o.object_id,''IsUserTable'') = 1 -- sys.tables only returns type U
  9400. ORDER BY objectName
  9401. OPTION (MAXDOP 2);'
  9402. BEGIN TRY
  9403. INSERT INTO #tblIxs6
  9404. EXECUTE sp_executesql @sqlcmd
  9405. END TRY
  9406. BEGIN CATCH
  9407. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9408. SELECT @ErrorMessage = 'Clustered Indexes with GUIDs in key subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9409. RAISERROR (@ErrorMessage, 16, 1);
  9410. END CATCH
  9411. UPDATE #tmpdbs1
  9412. SET isdone = 1
  9413. WHERE [dbid] = @dbid
  9414. END;
  9415. IF (SELECT COUNT(*) FROM #tblIxs6 WHERE [Key_has_GUID] > 0) > 0
  9416. BEGIN
  9417. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Key_GUID' AS [Check], '[WARNING: Some clustered indexes have GUIDs in the key. It is recommended to revise these]' AS [Deviation]
  9418. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Key_GUID' AS [Information], I.[DatabaseName] AS [Database_Name], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name], I.[indexID], I.[indexName] AS [Index_Name], I.KeyCols
  9419. FROM #tblIxs6 I
  9420. WHERE [Key_has_GUID] > 0
  9421. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9422. END
  9423. ELSE
  9424. BEGIN
  9425. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Key_GUID' AS [Check], '[OK]' AS [Deviation]
  9426. END
  9427. END;
  9428. --------------------------------------------------------------------------------------------------------------------------------
  9429. -- Foreign Keys with no Index subsection
  9430. --------------------------------------------------------------------------------------------------------------------------------
  9431. IF @ptochecks = 1
  9432. BEGIN
  9433. RAISERROR (N' |-Starting Foreign Keys with no Index', 10, 1) WITH NOWAIT
  9434. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  9435. DROP TABLE #tblFK;
  9436. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  9437. CREATE TABLE #tblFK ([databaseID] int, [DatabaseName] sysname, [constraint_name] VARCHAR(200), [parent_schema_name] VARCHAR(100),
  9438. [parent_table_name] VARCHAR(200), parent_columns VARCHAR(4000), [referenced_schema] VARCHAR(100), [referenced_table_name] VARCHAR(200), referenced_columns VARCHAR(4000),
  9439. CONSTRAINT PK_FK PRIMARY KEY CLUSTERED(databaseID, [constraint_name]))
  9440. UPDATE #tmpdbs1
  9441. SET isdone = 0
  9442. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9443. BEGIN
  9444. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9445. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  9446. USE ' + QUOTENAME(@dbname) + '
  9447. ;WITH cteFK AS (
  9448. SELECT t.name AS [parent_schema_name],
  9449. OBJECT_NAME(FKC.parent_object_id) [parent_table_name],
  9450. OBJECT_NAME(constraint_object_id) AS [constraint_name],
  9451. t2.name AS [referenced_schema],
  9452. OBJECT_NAME(referenced_object_id) AS [referenced_table_name],
  9453. SUBSTRING((SELECT '','' + RTRIM(COL_NAME(k.parent_object_id,parent_column_id)) AS [data()]
  9454. FROM sys.foreign_key_columns k (NOLOCK)
  9455. INNER JOIN sys.foreign_keys (NOLOCK) ON k.constraint_object_id = [object_id]
  9456. AND k.constraint_object_id = FKC.constraint_object_id
  9457. ORDER BY constraint_column_id
  9458. FOR XML PATH('''')), 2, 8000) AS [parent_columns],
  9459. SUBSTRING((SELECT '','' + RTRIM(COL_NAME(k.referenced_object_id,referenced_column_id)) AS [data()]
  9460. FROM sys.foreign_key_columns k (NOLOCK)
  9461. INNER JOIN sys.foreign_keys (NOLOCK) ON k.constraint_object_id = [object_id]
  9462. AND k.constraint_object_id = FKC.constraint_object_id
  9463. ORDER BY constraint_column_id
  9464. FOR XML PATH('''')), 2, 8000) AS [referenced_columns]
  9465. FROM sys.foreign_key_columns FKC (NOLOCK)
  9466. INNER JOIN sys.objects o (NOLOCK) ON FKC.parent_object_id = o.[object_id]
  9467. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  9468. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9469. INNER JOIN sys.objects so (NOLOCK) ON FKC.referenced_object_id = so.[object_id]
  9470. INNER JOIN sys.tables AS mst2 (NOLOCK) ON mst2.[object_id] = so.[object_id]
  9471. INNER JOIN sys.schemas AS t2 (NOLOCK) ON t2.[schema_id] = mst2.[schema_id]
  9472. WHERE o.type = ''U'' AND so.type = ''U''
  9473. GROUP BY o.[schema_id],so.[schema_id],FKC.parent_object_id,constraint_object_id,referenced_object_id,t.name,t2.name
  9474. ),
  9475. cteIndexCols AS (
  9476. SELECT t.name AS schemaName,
  9477. OBJECT_NAME(mst.[object_id]) AS objectName,
  9478. SUBSTRING(( SELECT '','' + RTRIM(ac.name) FROM sys.tables AS st
  9479. INNER JOIN sys.indexes AS mi ON st.[object_id] = mi.[object_id]
  9480. INNER JOIN sys.index_columns AS ic ON mi.[object_id] = ic.[object_id] AND mi.[index_id] = ic.[index_id]
  9481. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9482. WHERE i.[object_id] = mi.[object_id] AND i.index_id = mi.index_id AND ic.is_included_column = 0
  9483. ORDER BY ac.column_id
  9484. FOR XML PATH('''')), 2, 8000) AS KeyCols
  9485. FROM sys.indexes AS i
  9486. INNER JOIN sys.tables AS mst ON mst.[object_id] = i.[object_id]
  9487. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  9488. WHERE i.[type] IN (1,2,5,6) AND i.is_unique_constraint = 0
  9489. AND mst.is_ms_shipped = 0
  9490. )
  9491. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name, fk.constraint_name AS constraintName,
  9492. fk.parent_schema_name AS schemaName, fk.parent_table_name AS tableName,
  9493. REPLACE(fk.parent_columns,'' ,'','','') AS parentColumns, fk.referenced_schema AS referencedSchemaName,
  9494. fk.referenced_table_name AS referencedTableName, REPLACE(fk.referenced_columns,'' ,'','','') AS referencedColumns
  9495. FROM cteFK fk
  9496. WHERE NOT EXISTS (SELECT 1 FROM cteIndexCols ict
  9497. WHERE fk.parent_schema_name = ict.schemaName
  9498. AND fk.parent_table_name = ict.objectName
  9499. AND REPLACE(fk.parent_columns,'' ,'','','') = ict.KeyCols);'
  9500. BEGIN TRY
  9501. INSERT INTO #tblFK
  9502. EXECUTE sp_executesql @sqlcmd
  9503. END TRY
  9504. BEGIN CATCH
  9505. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9506. SELECT @ErrorMessage = 'Foreign Keys with no Index subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9507. RAISERROR (@ErrorMessage, 16, 1);
  9508. END CATCH
  9509. UPDATE #tmpdbs1
  9510. SET isdone = 1
  9511. WHERE [dbid] = @dbid
  9512. END;
  9513. IF (SELECT COUNT(*) FROM #tblFK) > 0
  9514. BEGIN
  9515. SELECT 'Index_and_Stats_checks' AS [Category], 'FK_no_Index' AS [Check], '[WARNING: Some Foreign Key constraints are not supported by an Index. It is recommended to revise these]' AS [Deviation]
  9516. SELECT 'Index_and_Stats_checks' AS [Category], 'FK_no_Index' AS [Information], FK.[DatabaseName] AS [Database_Name], constraint_name AS [Constraint_Name],
  9517. FK.parent_schema_name AS [Schema_Name], FK.parent_table_name AS [Table_Name],
  9518. FK.parent_columns AS parentColumns, FK.referenced_schema AS Referenced_Schema_Name,
  9519. FK.referenced_table_name AS Referenced_Table_Name, FK.referenced_columns AS referencedColumns
  9520. FROM #tblFK FK
  9521. ORDER BY [DatabaseName], parent_schema_name, parent_table_name, referenced_schema, referenced_table_name
  9522. IF @gen_scripts = 1
  9523. BEGIN
  9524. DECLARE @strSQL5 NVARCHAR(4000)
  9525. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9526. PRINT CHAR(10) + '--############# FK index creation statements #############' + CHAR(10)
  9527. DECLARE curFKs CURSOR FAST_FORWARD FOR SELECT 'USE ' + [DatabaseName] + CHAR(10) + 'GO' + CHAR(10) +
  9528. 'CREATE INDEX IX_' + REPLACE(constraint_name,' ','_') + ' ON ' + QUOTENAME(parent_schema_name) + '.' + QUOTENAME(parent_table_name) + ' ([' + REPLACE(REPLACE(parent_columns,',','],['),']]',']') + ']);' + CHAR(10) + 'GO' + CHAR(10)
  9529. FROM #tblFK
  9530. ORDER BY [DatabaseName], parent_schema_name, parent_table_name, referenced_schema, referenced_table_name
  9531. OPEN curFKs
  9532. FETCH NEXT FROM curFKs INTO @strSQL5
  9533. WHILE (@@FETCH_STATUS = 0)
  9534. BEGIN
  9535. PRINT @strSQL5
  9536. FETCH NEXT FROM curFKs INTO @strSQL5
  9537. END
  9538. CLOSE curFKs
  9539. DEALLOCATE curFKs
  9540. PRINT '--############# Ended FK index creation statements #############' + CHAR(10)
  9541. END;
  9542. END
  9543. ELSE
  9544. BEGIN
  9545. SELECT 'Index_and_Stats_checks' AS [Category], 'FK_no_Index' AS [Check], '[OK]' AS [Deviation]
  9546. END;
  9547. END;
  9548. --------------------------------------------------------------------------------------------------------------------------------
  9549. -- Indexing per Table subsection
  9550. --------------------------------------------------------------------------------------------------------------------------------
  9551. IF @ptochecks = 1
  9552. BEGIN
  9553. RAISERROR (N' |-Starting Indexing per Table', 10, 1) WITH NOWAIT
  9554. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  9555. DROP TABLE #tblIxs3;
  9556. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  9557. CREATE TABLE #tblIxs3 ([Operation] tinyint, [databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200))
  9558. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  9559. DROP TABLE #tblIxs4;
  9560. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  9561. CREATE TABLE #tblIxs4 ([databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [CntCols] int, [CntIxs] int)
  9562. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  9563. DROP TABLE #tblIxs5;
  9564. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  9565. CREATE TABLE #tblIxs5 ([databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [indexName] VARCHAR(200), [indexLocation] VARCHAR(200))
  9566. UPDATE #tmpdbs1
  9567. SET isdone = 0
  9568. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9569. BEGIN
  9570. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9571. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9572. SELECT 1 AS [Check], ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name
  9573. FROM sys.indexes AS si (NOLOCK)
  9574. INNER JOIN sys.tables AS t (NOLOCK) ON si.[object_id] = t.[object_id]
  9575. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9576. WHERE si.is_hypothetical = 0
  9577. GROUP BY si.[object_id], t.name, s.name
  9578. HAVING COUNT(index_id) = 1 AND MAX(index_id) = 0
  9579. UNION ALL
  9580. SELECT 2 AS [Check], ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name
  9581. FROM sys.indexes AS si (NOLOCK)
  9582. INNER JOIN sys.tables AS t (NOLOCK) ON si.[object_id] = t.[object_id]
  9583. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9584. WHERE si.is_hypothetical = 0
  9585. GROUP BY t.name, s.name
  9586. HAVING COUNT(index_id) > 1 AND MIN(index_id) = 0;'
  9587. BEGIN TRY
  9588. INSERT INTO #tblIxs3
  9589. EXECUTE sp_executesql @sqlcmd
  9590. END TRY
  9591. BEGIN CATCH
  9592. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9593. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 1 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9594. RAISERROR (@ErrorMessage, 16, 1);
  9595. END CATCH
  9596. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9597. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name, COUNT(c.column_id),
  9598. (SELECT COUNT(si.index_id) FROM sys.tables AS t2 INNER JOIN sys.indexes AS si ON si.[object_id] = t2.[object_id]
  9599. WHERE si.index_id > 0 AND si.[object_id] = t.[object_id] AND si.is_hypothetical = 0
  9600. GROUP BY si.[object_id])
  9601. FROM sys.tables AS t (NOLOCK)
  9602. INNER JOIN sys.columns AS c (NOLOCK) ON t.[object_id] = c.[object_id]
  9603. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9604. GROUP BY s.name, t.name, t.[object_id];'
  9605. BEGIN TRY
  9606. INSERT INTO #tblIxs4
  9607. EXECUTE sp_executesql @sqlcmd
  9608. END TRY
  9609. BEGIN CATCH
  9610. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9611. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 2 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9612. RAISERROR (@ErrorMessage, 16, 1);
  9613. END CATCH
  9614. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9615. SELECT DISTINCT ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name, i.name, ds.name
  9616. FROM sys.tables AS t (NOLOCK)
  9617. INNER JOIN sys.indexes AS i (NOLOCK) ON t.[object_id] = i.[object_id]
  9618. INNER JOIN sys.data_spaces AS ds (NOLOCK) ON ds.data_space_id = i.data_space_id
  9619. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9620. WHERE t.[type] = ''U''
  9621. AND i.[type] IN (1,2)
  9622. AND i.is_hypothetical = 0
  9623. -- Get partitioned tables
  9624. AND t.name IN (SELECT ob.name
  9625. FROM sys.tables AS ob (NOLOCK)
  9626. INNER JOIN sys.indexes AS ind (NOLOCK) ON ind.[object_id] = ob.[object_id]
  9627. INNER JOIN sys.data_spaces AS sds (NOLOCK) ON sds.data_space_id = ind.data_space_id
  9628. WHERE sds.[type] = ''PS''
  9629. GROUP BY ob.name)
  9630. AND ds.[type] <> ''PS'';'
  9631. BEGIN TRY
  9632. INSERT INTO #tblIxs5
  9633. EXECUTE sp_executesql @sqlcmd
  9634. END TRY
  9635. BEGIN CATCH
  9636. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9637. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 3 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9638. RAISERROR (@ErrorMessage, 16, 1);
  9639. END CATCH
  9640. UPDATE #tmpdbs1
  9641. SET isdone = 1
  9642. WHERE [dbid] = @dbid
  9643. END;
  9644. IF (SELECT COUNT(*) FROM #tblIxs3 WHERE [Operation] = 1) > 0
  9645. BEGIN
  9646. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_Indexes' AS [Check], '[WARNING: Some tables do not have indexes]' AS [Deviation]
  9647. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_Indexes' AS [Check], [DatabaseName] AS [Database_Name], schemaName AS [Schema_Name], [objectName] AS [Table_Name] FROM #tblIxs3 WHERE [Operation] = 1
  9648. END
  9649. ELSE
  9650. BEGIN
  9651. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_Indexes' AS [Check], '[OK]' AS [Deviation]
  9652. END;
  9653. IF (SELECT COUNT(*) FROM #tblIxs3 WHERE [Operation] = 2) > 0
  9654. BEGIN
  9655. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_CL_Index' AS [Check], '[WARNING: Some tables do not have a clustered index, but have non-clustered index(es)]' AS [Deviation]
  9656. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_CL_Index' AS [Check], [DatabaseName] AS [Database_Name], schemaName AS [Schema_Name], [objectName] AS [Table_Name] FROM #tblIxs3 WHERE [Operation] = 2
  9657. END
  9658. ELSE
  9659. BEGIN
  9660. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_CL_Index' AS [Check], '[OK]' AS [Deviation]
  9661. END;
  9662. IF (SELECT COUNT(*) FROM #tblIxs4 WHERE [CntCols] < [CntIxs]) > 0
  9663. BEGIN
  9664. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_more_Indexes_than_Cols' AS [Check], '[WARNING: Some tables have more indexes than columns]' AS [Deviation]
  9665. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_more_Indexes_than_Cols' AS [Check], [DatabaseName] AS [Database_Name], schemaName AS [Schema_Name], [objectName] AS [Table_Name], [CntCols] AS [Cnt_Columns], [CntIxs] AS [Cnt_Indexes] FROM #tblIxs4 WHERE [CntCols] < [CntIxs]
  9666. END
  9667. ELSE
  9668. BEGIN
  9669. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_more_Indexes_than_Cols' AS [Check], '[OK]' AS [Deviation]
  9670. END;
  9671. IF (SELECT COUNT(*) FROM #tblIxs5) > 0
  9672. BEGIN
  9673. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_partition_misaligned_Indexes' AS [Check], '[WARNING: Some partitioned tables have indexes that are not aligned with the partition schema]' AS [Deviation]
  9674. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_partition_misaligned_Indexes' AS [Check], [DatabaseName] AS [Database_Name], schemaName AS [Schema_Name], [objectName] AS [Table_Name], [indexName] AS [Index_Name], [indexLocation] FROM #tblIxs5
  9675. END
  9676. ELSE
  9677. BEGIN
  9678. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_partition_misaligned_Indexes' AS [Check], '[OK]' AS [Deviation]
  9679. END;
  9680. END;
  9681. --------------------------------------------------------------------------------------------------------------------------------
  9682. -- Missing Indexes subsection
  9683. -- Outputs only potentially most relevant, based in scoring method - use at you own discretion)
  9684. --------------------------------------------------------------------------------------------------------------------------------
  9685. IF @ptochecks = 1
  9686. BEGIN
  9687. RAISERROR (N' |-Starting Missing Indexes', 10, 1) WITH NOWAIT
  9688. DECLARE @IC VARCHAR(4000), @ICWI VARCHAR(4000), @editionCheck bit
  9689. /* Refer to http://msdn.microsoft.com/en-us/library/ms174396.aspx */
  9690. IF (SELECT SERVERPROPERTY('EditionID')) IN (1804890536, 1872460670, 610778273, -2117995310)
  9691. SET @editionCheck = 1 -- supports enterprise only features
  9692. ELSE
  9693. SET @editionCheck = 0; -- does not support enterprise only features
  9694. -- Create the helper functions
  9695. EXEC ('USE tempdb; IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID(''tempdb.dbo.fn_createindex_allcols'')) DROP FUNCTION dbo.fn_createindex_allcols')
  9696. EXEC ('USE tempdb; EXEC(''
  9697. CREATE FUNCTION dbo.fn_createindex_allcols (@ix_handle int)
  9698. RETURNS NVARCHAR(max)
  9699. AS
  9700. BEGIN
  9701. DECLARE @ReturnCols NVARCHAR(max)
  9702. ;WITH ColumnToPivot ([data()]) AS (
  9703. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9704. FROM sys.dm_db_missing_index_details id
  9705. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9706. WHERE id.index_handle = @ix_handle
  9707. ORDER BY ic.column_id ASC
  9708. FOR XML PATH(''''''''), TYPE
  9709. ),
  9710. XmlRawData (CSVString) AS (
  9711. SELECT (SELECT [data()] AS InputData
  9712. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9713. )
  9714. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9715. FROM XmlRawData
  9716. RETURN (@ReturnCols)
  9717. END'')
  9718. ')
  9719. EXEC ('USE tempdb; IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID(''tempdb.dbo.fn_createindex_keycols'')) DROP FUNCTION dbo.fn_createindex_keycols')
  9720. EXEC ('USE tempdb; EXEC(''
  9721. CREATE FUNCTION dbo.fn_createindex_keycols (@ix_handle int)
  9722. RETURNS NVARCHAR(max)
  9723. AS
  9724. BEGIN
  9725. DECLARE @ReturnCols NVARCHAR(max)
  9726. ;WITH ColumnToPivot ([data()]) AS (
  9727. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9728. FROM sys.dm_db_missing_index_details id
  9729. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9730. WHERE id.index_handle = @ix_handle
  9731. AND (ic.column_usage = ''''EQUALITY'''' OR ic.column_usage = ''''INEQUALITY'''')
  9732. ORDER BY ic.column_id ASC
  9733. FOR XML PATH(''''''''), TYPE
  9734. ),
  9735. XmlRawData (CSVString) AS (
  9736. SELECT (SELECT [data()] AS InputData
  9737. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9738. )
  9739. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9740. FROM XmlRawData
  9741. RETURN (@ReturnCols)
  9742. END'')
  9743. ')
  9744. EXEC ('USE tempdb; IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID(''tempdb.dbo.fn_createindex_includecols'')) DROP FUNCTION dbo.fn_createindex_includecols')
  9745. EXEC ('USE tempdb; EXEC(''
  9746. CREATE FUNCTION dbo.fn_createindex_includecols (@ix_handle int)
  9747. RETURNS NVARCHAR(max)
  9748. AS
  9749. BEGIN
  9750. DECLARE @ReturnCols NVARCHAR(max)
  9751. ;WITH ColumnToPivot ([data()]) AS (
  9752. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9753. FROM sys.dm_db_missing_index_details id
  9754. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9755. WHERE id.index_handle = @ix_handle
  9756. AND ic.column_usage = ''''INCLUDE''''
  9757. ORDER BY ic.column_id ASC
  9758. FOR XML PATH(''''''''), TYPE
  9759. ),
  9760. XmlRawData (CSVString) AS (
  9761. SELECT (SELECT [data()] AS InputData
  9762. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9763. )
  9764. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9765. FROM XmlRawData
  9766. RETURN (@ReturnCols)
  9767. END'')
  9768. ')
  9769. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  9770. DROP TABLE #IndexCreation;
  9771. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  9772. CREATE TABLE #IndexCreation (
  9773. [database_id] int,
  9774. DBName VARCHAR(255),
  9775. [Table] VARCHAR(255),
  9776. [ix_handle] int,
  9777. [User_Hits_on_Missing_Index] int,
  9778. [Estimated_Improvement_Percent] DECIMAL(5,2),
  9779. [Avg_Total_User_Cost] int,
  9780. [Unique_Compiles] int,
  9781. [Score] NUMERIC(19,3),
  9782. [KeyCols] VARCHAR(1000),
  9783. [IncludedCols] VARCHAR(4000),
  9784. [Ix_Name] VARCHAR(255),
  9785. [AllCols] NVARCHAR(max),
  9786. [KeyColsOrdered] NVARCHAR(max),
  9787. [IncludedColsOrdered] NVARCHAR(max)
  9788. )
  9789. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  9790. DROP TABLE #IndexRedundant;
  9791. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  9792. CREATE TABLE #IndexRedundant (
  9793. DBName VARCHAR(255),
  9794. [Table] VARCHAR(255),
  9795. [Ix_Name] VARCHAR(255),
  9796. [ix_handle] int,
  9797. [KeyCols] VARCHAR(1000),
  9798. [IncludedCols] VARCHAR(4000),
  9799. [Redundant_With] VARCHAR(255)
  9800. )
  9801. INSERT INTO #IndexCreation
  9802. SELECT i.database_id,
  9803. m.[name],
  9804. RIGHT(i.[statement], LEN(i.[statement]) - (LEN(m.[name]) + 3)) AS [Table],
  9805. i.index_handle AS [ix_handle],
  9806. [User_Hits_on_Missing_Index] = (s.user_seeks + s.user_scans),
  9807. s.avg_user_impact, -- Query cost would reduce by this amount in percentage, on average.
  9808. s.avg_total_user_cost, -- Average cost of the user queries that could be reduced by the index in the group.
  9809. s.unique_compiles, -- Number of compilations and recompilations that would benefit from this missing index group.
  9810. (CONVERT(NUMERIC(19,3), s.user_seeks) + CONVERT(NUMERIC(19,3), s.user_scans))
  9811. * CONVERT(NUMERIC(19,3), s.avg_total_user_cost)
  9812. * CONVERT(NUMERIC(19,3), s.avg_user_impact) AS Score, -- The higher the score, higher is the anticipated improvement for user queries.
  9813. CASE WHEN (i.equality_columns IS NOT NULL AND i.inequality_columns IS NULL) THEN i.equality_columns
  9814. WHEN (i.equality_columns IS NULL AND i.inequality_columns IS NOT NULL) THEN i.inequality_columns
  9815. ELSE i.equality_columns + ',' + i.inequality_columns END AS [KeyCols],
  9816. i.included_columns AS [IncludedCols],
  9817. 'IX_' + LEFT(RIGHT(RIGHT(i.[statement], LEN(i.[statement]) - (LEN(m.[name]) + 3)), LEN(RIGHT(i.[statement], LEN(i.[statement]) - (LEN(m.[name]) + 3))) - (CHARINDEX('.', RIGHT(i.[statement], LEN(i.[statement]) - (LEN(m.[name]) + 3)), 1)) - 1),
  9818. LEN(RIGHT(RIGHT(i.[statement], LEN(i.[statement]) - (LEN(m.[name]) + 3)), LEN(RIGHT(i.[statement], LEN(i.[statement]) - (LEN(m.[name]) + 3))) - (CHARINDEX('.', RIGHT(i.[statement], LEN(i.[statement]) - (LEN(m.[name]) + 3)), 1)) - 1)) - 1) + '_' + CAST(i.index_handle AS NVARCHAR) AS [Ix_Name],
  9819. tempdb.dbo.fn_createindex_allcols(i.index_handle),
  9820. tempdb.dbo.fn_createindex_keycols(i.index_handle),
  9821. tempdb.dbo.fn_createindex_includecols(i.index_handle)
  9822. FROM sys.dm_db_missing_index_details i
  9823. INNER JOIN master.sys.databases m ON i.database_id = m.database_id
  9824. INNER JOIN sys.dm_db_missing_index_groups g ON i.index_handle = g.index_handle
  9825. INNER JOIN sys.dm_db_missing_index_group_stats s ON s.group_handle = g.index_group_handle
  9826. WHERE i.database_id > 4
  9827. INSERT INTO #IndexRedundant
  9828. SELECT I.DBName, I.[Table], I.[Ix_Name], I.[ix_handle], I.[KeyCols], I.[IncludedCols], I2.[Ix_Name]
  9829. FROM #IndexCreation I
  9830. INNER JOIN #IndexCreation I2 ON I.[database_id] = I2.[database_id] AND I.[Table] = I2.[Table] AND I.[Ix_Name] <> I2.[Ix_Name]
  9831. AND (((I.KeyColsOrdered <> I2.KeyColsOrdered OR I.[IncludedColsOrdered] <> I2.[IncludedColsOrdered])
  9832. AND ((CASE WHEN I.[IncludedColsOrdered] IS NULL THEN I.KeyColsOrdered ELSE I.KeyColsOrdered + ',' + I.[IncludedColsOrdered] END) = (CASE WHEN I2.[IncludedColsOrdered] IS NULL THEN I2.KeyColsOrdered ELSE I2.KeyColsOrdered + ',' + I2.[IncludedColsOrdered] END)
  9833. OR I.[AllCols] = I2.[AllCols]))
  9834. OR (I.KeyColsOrdered <> I2.KeyColsOrdered AND I.[IncludedColsOrdered] = I2.[IncludedColsOrdered])
  9835. OR (I.KeyColsOrdered = I2.KeyColsOrdered AND I.[IncludedColsOrdered] <> I2.[IncludedColsOrdered]))
  9836. WHERE I.[Score] >= 100000
  9837. AND I2.[Score] >= 100000
  9838. GROUP BY I.DBName, I.[Table], I.[Ix_Name], I.[ix_handle], I.[KeyCols], I.[IncludedCols], I2.[Ix_Name]
  9839. ORDER BY I.DBName, I.[Table], I.[Ix_Name]
  9840. IF (SELECT COUNT(*) FROM #IndexCreation WHERE [Score] >= 100000) > 0
  9841. BEGIN
  9842. SELECT 'Index_and_Stats_checks' AS [Category], 'Missing_Indexes' AS [Check], '[INFORMATION: Potentially missing indexes were found. It may be important to revise these]' AS [Deviation]
  9843. SELECT 'Index_and_Stats_checks' AS [Category], 'Missing_Indexes' AS [Information], IC.DBName AS [Database_Name], IC.[Table] AS [Table_Name], CONVERT(bigint,[Score]) AS [Score], [User_Hits_on_Missing_Index],
  9844. [Estimated_Improvement_Percent], [Avg_Total_User_Cost], [Unique_Compiles], IC.[KeyCols], IC.[IncludedCols], IC.[Ix_Name] AS [Index_Name],
  9845. SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9846. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9847. ORDER BY IR.[Redundant_With]
  9848. FOR XML PATH('')), 2, 8000) AS [Possibly_Redundant_With],
  9849. CASE WHEN IC.[Score] >= 100000 THEN 'Y' ELSE 'N' END AS [Generate_Script]
  9850. FROM #IndexCreation IC
  9851. --WHERE [Score] >= 100000
  9852. ORDER BY IC.DBName, IC.[Score] DESC, IC.[User_Hits_on_Missing_Index], IC.[Estimated_Improvement_Percent];
  9853. SELECT DISTINCT 'Index_and_Stats_checks' AS [Category], 'Missing_Indexes' AS [Check], 'Possibly_redundant_IXs_in_list' AS Comments, I.DBName AS [Database_Name], I.[Table] AS [Table_Name],
  9854. I.[Ix_Name] AS [Index_Name], I.[KeyCols], I.[IncludedCols]
  9855. FROM #IndexRedundant I
  9856. ORDER BY I.DBName, I.[Table], I.[Ix_Name]
  9857. IF @gen_scripts = 1
  9858. BEGIN
  9859. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */' + CHAR(10)
  9860. IF (SELECT COUNT(*) FROM #IndexCreation IC
  9861. WHERE IC.[IncludedCols] IS NULL AND IC.[Score] >= 100000
  9862. ) > 0
  9863. BEGIN
  9864. PRINT '--############# Indexes creation statements #############' + CHAR(10)
  9865. DECLARE cIC CURSOR FAST_FORWARD FOR
  9866. SELECT '-- User Hits on Missing Index ' + IC.[Ix_Name] + ': ' + CONVERT(VARCHAR(20),IC.[User_Hits_on_Missing_Index]) + CHAR(10) +
  9867. '-- Estimated Improvement Percent: ' + CONVERT(VARCHAR(6),IC.[Estimated_Improvement_Percent]) + CHAR(10) +
  9868. '-- Average Total User Cost: ' + CONVERT(VARCHAR(50),IC.[Avg_Total_User_Cost]) + CHAR(10) +
  9869. '-- Unique Compiles: ' + CONVERT(VARCHAR(50),IC.[Unique_Compiles]) + CHAR(10) +
  9870. '-- Score: ' + CONVERT(VARCHAR(20),CONVERT(bigint,IC.[Score])) +
  9871. CASE WHEN (SELECT COUNT(IR.[Redundant_With]) FROM #IndexRedundant IR
  9872. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]) > 0
  9873. THEN CHAR(10) + '-- Possibly Redundant with Missing Index(es): ' + SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9874. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9875. FOR XML PATH('')), 2, 8000)
  9876. ELSE '' END +
  9877. CHAR(10) + 'USE ' + QUOTENAME(IC.DBName) + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sysindexes WHERE name = N''' +
  9878. IC.[Ix_Name] + ''') DROP INDEX ' + IC.[Table] + '.' +
  9879. IC.[Ix_Name] + ';' + CHAR(10) + 'GO' + CHAR(10) + 'CREATE INDEX ' +
  9880. IC.[Ix_Name] + ' ON ' + IC.[Table] + ' (' + IC.[KeyCols] + CASE WHEN @editionCheck = 1 THEN ') WITH (ONLINE = ON);' ELSE ');' END + CHAR(10) + 'GO' + CHAR(10)
  9881. FROM #IndexCreation IC
  9882. WHERE IC.[IncludedCols] IS NULL AND IC.[Score] >= 100000
  9883. ORDER BY IC.DBName, IC.[Table], IC.[Ix_Name]
  9884. OPEN cIC
  9885. FETCH NEXT FROM cIC INTO @IC
  9886. WHILE @@FETCH_STATUS = 0
  9887. BEGIN
  9888. PRINT @IC
  9889. FETCH NEXT FROM cIC INTO @IC
  9890. END
  9891. CLOSE cIC
  9892. DEALLOCATE cIC
  9893. END;
  9894. IF (SELECT COUNT(*) FROM #IndexCreation IC
  9895. WHERE IC.[IncludedCols] IS NOT NULL AND IC.[Score] >= 100000
  9896. ) > 0
  9897. BEGIN
  9898. PRINT '--############# Covering indexes creation statements #############' + CHAR(10)
  9899. DECLARE cICWI CURSOR FAST_FORWARD FOR
  9900. SELECT '-- User Hits on Missing Index ' + IC.[Ix_Name] + ': ' + CONVERT(VARCHAR(20),IC.[User_Hits_on_Missing_Index]) + CHAR(10) +
  9901. '-- Estimated Improvement Percent: ' + CONVERT(VARCHAR(6),IC.[Estimated_Improvement_Percent]) + CHAR(10) +
  9902. '-- Average Total User Cost: ' + CONVERT(VARCHAR(50),IC.[Avg_Total_User_Cost]) + CHAR(10) +
  9903. '-- Unique Compiles: ' + CONVERT(VARCHAR(50),IC.[Unique_Compiles]) + CHAR(10) +
  9904. '-- Score: ' + CONVERT(VARCHAR(20),CONVERT(bigint,IC.[Score])) +
  9905. CASE WHEN (SELECT COUNT(IR.[Redundant_With]) FROM #IndexRedundant IR
  9906. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]) > 0
  9907. THEN CHAR(10) + '-- Possibly Redundant with Missing Index(es): ' + SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9908. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9909. FOR XML PATH('')), 2, 8000)
  9910. ELSE '' END +
  9911. CHAR(10) + 'USE ' + QUOTENAME(IC.DBName) + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sysindexes WHERE name = N''' +
  9912. IC.[Ix_Name] + ''') DROP INDEX ' + IC.[Table] + '.' +
  9913. IC.[Ix_Name] + ';' + CHAR(10) + 'GO' + CHAR(10) + 'CREATE INDEX ' +
  9914. IC.[Ix_Name] + ' ON ' + IC.[Table] + ' (' + IC.[KeyCols] + ')' + CHAR(10) + 'INCLUDE(' + IC.[IncludedCols] + CASE WHEN @editionCheck = 1 THEN ') WITH (ONLINE = ON);' ELSE ');' END + CHAR(10) + 'GO' + CHAR(10)
  9915. FROM #IndexCreation IC
  9916. WHERE IC.[IncludedCols] IS NOT NULL AND IC.[Score] >= 100000
  9917. ORDER BY IC.DBName, IC.[Table], IC.[Ix_Name]
  9918. OPEN cICWI
  9919. FETCH NEXT FROM cICWI INTO @ICWI
  9920. WHILE @@FETCH_STATUS = 0
  9921. BEGIN
  9922. PRINT @ICWI
  9923. FETCH NEXT FROM cICWI INTO @ICWI
  9924. END
  9925. CLOSE cICWI
  9926. DEALLOCATE cICWI
  9927. END;
  9928. PRINT '--############# Ended missing indexes creation statements #############' + CHAR(10)
  9929. END;
  9930. END
  9931. ELSE IF (SELECT COUNT(*) FROM #IndexCreation WHERE [Score] < 100000) > 0
  9932. BEGIN
  9933. SELECT 'Index_and_Stats_checks' AS [Category], 'Missing_Indexes' AS [Check], '[INFORMATION: no relevant missing indexes were found, although missing indexes were identified by SQL Server]' AS [Deviation]
  9934. SELECT 'Index_and_Stats_checks' AS [Category], 'Missing_Indexes' AS [Information], IC.DBName AS [Database_Name], IC.[Table] AS [Table_Name], CONVERT(bigint,[Score]) AS [Score], [User_Hits_on_Missing_Index],
  9935. [Estimated_Improvement_Percent], [Avg_Total_User_Cost], [Unique_Compiles], IC.[KeyCols], IC.[IncludedCols], IC.[Ix_Name] AS [Index_Name],
  9936. SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9937. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9938. ORDER BY IR.[Redundant_With]
  9939. FOR XML PATH('')), 2, 8000) AS [Possibly_Redundant_With],
  9940. CASE WHEN IC.[Score] >= 100000 THEN 'Y' ELSE 'N' END AS [Generate_Script]
  9941. FROM #IndexCreation IC
  9942. --WHERE [Score] < 100000
  9943. ORDER BY IC.DBName, IC.[Score] DESC, IC.[User_Hits_on_Missing_Index], IC.[Estimated_Improvement_Percent];
  9944. END
  9945. ELSE
  9946. BEGIN
  9947. SELECT 'Index_and_Stats_checks' AS [Category], 'Missing_Indexes' AS [Check], '[OK]' AS [Deviation]
  9948. END
  9949. END;
  9950. --------------------------------------------------------------------------------------------------------------------------------
  9951. -- Objects naming conventions subsection
  9952. -- Refer to BOL for more information
  9953. -- (http://msdn.microsoft.com/en-us/library/dd172115(v=vs.100).aspx)
  9954. -- (http://msdn.microsoft.com/en-us/library/dd172134.aspx)
  9955. -- (http://msdn.microsoft.com/en-us/library/ms189822.aspx)
  9956. --------------------------------------------------------------------------------------------------------------------------------
  9957. RAISERROR (N'|-Starting Objects naming conventions Checks', 10, 1) WITH NOWAIT
  9958. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  9959. DROP TABLE #tmpobjectnames;
  9960. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  9961. CREATE TABLE #tmpobjectnames ([DBName] sysname, [schemaName] VARCHAR(100), [Object] VARCHAR(255), [Col] VARCHAR(255), [type] CHAR(2), type_desc VARCHAR(60));
  9962. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  9963. DROP TABLE #tmpfinalobjectnames;
  9964. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  9965. CREATE TABLE #tmpfinalobjectnames ([Deviation] tinyint, [DBName] sysname, [schemaName] VARCHAR(100), [Object] VARCHAR(255), [Col] VARCHAR(255), type_desc VARCHAR(60), [Comment] VARCHAR(500) NULL);
  9966. UPDATE #tmpdbs1
  9967. SET isdone = 0
  9968. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9969. BEGIN
  9970. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9971. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9972. SELECT ''' + @dbname + ''' AS [DBName], s.name, so.name, NULL, type, type_desc
  9973. FROM sys.objects so
  9974. INNER JOIN sys.schemas s ON so.schema_id = s.schema_id
  9975. WHERE so.is_ms_shipped = 0
  9976. UNION ALL
  9977. SELECT ''' + @dbname + ''' AS [DBName], s.name, so.name, sc.name, ''TC'' AS [type], ''TABLE_COLUMN'' AS [type_desc]
  9978. FROM sys.columns sc
  9979. INNER JOIN sys.objects so ON sc.object_id = so.object_id
  9980. INNER JOIN sys.schemas s ON so.schema_id = s.schema_id
  9981. WHERE so.is_ms_shipped = 0'
  9982. BEGIN TRY
  9983. INSERT INTO #tmpobjectnames
  9984. EXECUTE sp_executesql @sqlcmd
  9985. END TRY
  9986. BEGIN CATCH
  9987. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9988. SELECT @ErrorMessage = 'Object naming conventions subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9989. RAISERROR (@ErrorMessage, 16, 1);
  9990. END CATCH
  9991. UPDATE #tmpdbs1
  9992. SET isdone = 1
  9993. WHERE [dbid] = @dbid
  9994. END;
  9995. UPDATE #tmpdbs1
  9996. SET isdone = 0
  9997. CREATE INDEX IX1 ON #tmpobjectnames([type],[Object]);
  9998. /* http://msdn.microsoft.com/en-us/library/dd172115(v=vs.100).aspx */
  9999. INSERT INTO #tmpfinalobjectnames
  10000. SELECT 1, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10001. FROM #tmpobjectnames
  10002. WHERE [type] = 'P' AND [Object] LIKE 'sp[_]%'
  10003. AND [Object] NOT IN ('sp_alterdiagram','sp_creatediagram','sp_dropdiagram','sp_helpdiagramdefinition','sp_helpdiagrams','sp_renamediagram','sp_upgraddiagrams');
  10004. /* http://msdn.microsoft.com/en-us/library/dd172134.aspx */
  10005. INSERT INTO #tmpfinalobjectnames
  10006. SELECT 2, [DBName], [schemaName], [Object], [Col], type_desc, CASE WHEN [Object] LIKE '% %' THEN 'Space - ' + QUOTENAME([Object]) ELSE NULL END COLLATE database_default AS [Comment]
  10007. FROM #tmpobjectnames
  10008. WHERE [type] <> 'S' AND [type] <> 'TC'
  10009. AND ([Object] LIKE '% %' --space
  10010. OR [Object] LIKE '%[[]%'
  10011. OR [Object] LIKE '%]%'
  10012. OR [Object] LIKE '%-%'
  10013. OR [Object] LIKE '%.%'
  10014. OR [Object] LIKE '%,%'
  10015. OR [Object] LIKE '%;%'
  10016. OR [Object] LIKE '%' + CHAR(34) + '%' --double quote
  10017. OR [Object] LIKE '%' + CHAR(39) + '%'); --single quote
  10018. INSERT INTO #tmpfinalobjectnames
  10019. SELECT 3, [DBName], [schemaName], [Object], [Col], type_desc, CASE WHEN [Col] LIKE '% %' THEN 'Space - ' + QUOTENAME([Col]) ELSE NULL END COLLATE database_default AS [Comment]
  10020. FROM #tmpobjectnames
  10021. WHERE [type] = 'TC'
  10022. AND ([Col] LIKE '% %' --space
  10023. OR [Col] LIKE '%[[]%'
  10024. OR [Col] LIKE '%]%'
  10025. OR [Col] LIKE '%-%'
  10026. OR [Col] LIKE '%.%'
  10027. OR [Col] LIKE '%,%'
  10028. OR [Col] LIKE '%;%'
  10029. OR [Col] LIKE '%' + CHAR(34) + '%' --double quote
  10030. OR [Col] LIKE '%' + CHAR(39) + '%'); --single quote
  10031. /* http://msdn.microsoft.com/en-us/library/ms189822.aspx */
  10032. INSERT INTO #tmpfinalobjectnames
  10033. SELECT 4, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10034. FROM #tmpobjectnames
  10035. WHERE [type] <> 'S'
  10036. AND ([Object] LIKE '% ABSOLUTE %' OR [Object] LIKE '% ABSOLUTE' OR [Object] = 'ABSOLUTE'
  10037. OR [Object] LIKE '% ACTION %' OR [Object] LIKE '% ACTION' OR [Object] = 'ACTION'
  10038. OR [Object] LIKE '% ADA %' OR [Object] LIKE '% ADA' OR [Object] = 'ADA'
  10039. OR [Object] LIKE '% ADD %' OR [Object] LIKE '% ADD' OR [Object] = 'ADD'
  10040. OR [Object] LIKE '% ADMIN %' OR [Object] LIKE '% ADMIN' OR [Object] = 'ADMIN'
  10041. OR [Object] LIKE '% AFTER %' OR [Object] LIKE '% AFTER' OR [Object] = 'AFTER'
  10042. OR [Object] LIKE '% AGGREGATE %' OR [Object] LIKE '% AGGREGATE' OR [Object] = 'AGGREGATE'
  10043. OR [Object] LIKE '% ALIAS %' OR [Object] LIKE '% ALIAS' OR [Object] = 'ALIAS'
  10044. OR [Object] LIKE '% ALL %' OR [Object] LIKE '% ALL' OR [Object] = 'ALL'
  10045. OR [Object] LIKE '% ALLOCATE %' OR [Object] LIKE '% ALLOCATE' OR [Object] = 'ALLOCATE'
  10046. OR [Object] LIKE '% ALTER %' OR [Object] LIKE '% ALTER' OR [Object] = 'ALTER'
  10047. OR [Object] LIKE '% AND %' OR [Object] LIKE '% AND' OR [Object] = 'AND'
  10048. OR [Object] LIKE '% ANY %' OR [Object] LIKE '% ANY' OR [Object] = 'ANY'
  10049. OR [Object] LIKE '% ARE %' OR [Object] LIKE '% ARE' OR [Object] = 'ARE'
  10050. OR [Object] LIKE '% ARRAY %' OR [Object] LIKE '% ARRAY' OR [Object] = 'ARRAY'
  10051. OR [Object] LIKE '% AS %' OR [Object] LIKE '% AS' OR [Object] = 'AS'
  10052. OR [Object] LIKE '% ASC %' OR [Object] LIKE '% ASC' OR [Object] = 'ASC'
  10053. OR [Object] LIKE '% ASSERTION %' OR [Object] LIKE '% ASSERTION' OR [Object] = 'ASSERTION'
  10054. OR [Object] LIKE '% AT %' OR [Object] LIKE '% AT' OR [Object] = 'AT'
  10055. OR [Object] LIKE '% AUTHORIZATION %' OR [Object] LIKE '% AUTHORIZATION' OR [Object] = 'AUTHORIZATION'
  10056. OR [Object] LIKE '% AVG %' OR [Object] LIKE '% AVG' OR [Object] = 'AVG'
  10057. OR [Object] LIKE '% BACKUP %' OR [Object] LIKE '% BACKUP' OR [Object] = 'BACKUP'
  10058. OR [Object] LIKE '% BEFORE %' OR [Object] LIKE '% BEFORE' OR [Object] = 'BEFORE'
  10059. OR [Object] LIKE '% BEGIN %' OR [Object] LIKE '% BEGIN' OR [Object] = 'BEGIN'
  10060. OR [Object] LIKE '% BETWEEN %' OR [Object] LIKE '% BETWEEN' OR [Object] = 'BETWEEN'
  10061. OR [Object] LIKE '% BINARY %' OR [Object] LIKE '% BINARY' OR [Object] = 'BINARY'
  10062. OR [Object] LIKE '% BIT %' OR [Object] LIKE '% BIT' OR [Object] = 'BIT'
  10063. OR [Object] LIKE '% BIT_LENGTH %' OR [Object] LIKE '% BIT_LENGTH' OR [Object] = 'BIT_LENGTH'
  10064. OR [Object] LIKE '% BLOB %' OR [Object] LIKE '% BLOB' OR [Object] = 'BLOB'
  10065. OR [Object] LIKE '% BOOLEAN %' OR [Object] LIKE '% BOOLEAN' OR [Object] = 'BOOLEAN'
  10066. OR [Object] LIKE '% BOTH %' OR [Object] LIKE '% BOTH' OR [Object] = 'BOTH'
  10067. OR [Object] LIKE '% BREADTH %' OR [Object] LIKE '% BREADTH' OR [Object] = 'BREADTH'
  10068. OR [Object] LIKE '% BREAK %' OR [Object] LIKE '% BREAK' OR [Object] = 'BREAK'
  10069. OR [Object] LIKE '% BROWSE %' OR [Object] LIKE '% BROWSE' OR [Object] = 'BROWSE'
  10070. OR [Object] LIKE '% BULK %' OR [Object] LIKE '% BULK' OR [Object] = 'BULK'
  10071. OR [Object] LIKE '% BY %' OR [Object] LIKE '% BY' OR [Object] = 'BY'
  10072. OR [Object] LIKE '% CALL %' OR [Object] LIKE '% CALL' OR [Object] = 'CALL'
  10073. OR [Object] LIKE '% CASCADE %' OR [Object] LIKE '% CASCADE' OR [Object] = 'CASCADE'
  10074. OR [Object] LIKE '% CASCADED %' OR [Object] LIKE '% CASCADED' OR [Object] = 'CASCADED'
  10075. OR [Object] LIKE '% CASE %' OR [Object] LIKE '% CASE' OR [Object] = 'CASE'
  10076. OR [Object] LIKE '% CAST %' OR [Object] LIKE '% CAST' OR [Object] = 'CAST'
  10077. OR [Object] LIKE '% CATALOG %' OR [Object] LIKE '% CATALOG' OR [Object] = 'CATALOG'
  10078. OR [Object] LIKE '% CHAR %' OR [Object] LIKE '% CHAR' OR [Object] = 'CHAR'
  10079. OR [Object] LIKE '% CHAR_LENGTH %' OR [Object] LIKE '% CHAR_LENGTH' OR [Object] = 'CHAR_LENGTH'
  10080. OR [Object] LIKE '% CHARACTER %' OR [Object] LIKE '% CHARACTER' OR [Object] = 'CHARACTER'
  10081. OR [Object] LIKE '% CHARACTER_LENGTH %' OR [Object] LIKE '% CHARACTER_LENGTH' OR [Object] = 'CHARACTER_LENGTH'
  10082. OR [Object] LIKE '% CHECK %' OR [Object] LIKE '% CHECK' OR [Object] = 'CHECK'
  10083. OR [Object] LIKE '% CHECKPOINT %' OR [Object] LIKE '% CHECKPOINT' OR [Object] = 'CHECKPOINT'
  10084. OR [Object] LIKE '% CLASS %' OR [Object] LIKE '% CLASS' OR [Object] = 'CLASS'
  10085. OR [Object] LIKE '% CLOB %' OR [Object] LIKE '% CLOB' OR [Object] = 'CLOB'
  10086. OR [Object] LIKE '% CLOSE %' OR [Object] LIKE '% CLOSE' OR [Object] = 'CLOSE'
  10087. OR [Object] LIKE '% CLUSTERED %' OR [Object] LIKE '% CLUSTERED' OR [Object] = 'CLUSTERED'
  10088. OR [Object] LIKE '% COALESCE %' OR [Object] LIKE '% COALESCE' OR [Object] = 'COALESCE'
  10089. OR [Object] LIKE '% COLLATE %' OR [Object] LIKE '% COLLATE' OR [Object] = 'COLLATE'
  10090. OR [Object] LIKE '% COLLATION %' OR [Object] LIKE '% COLLATION' OR [Object] = 'COLLATION'
  10091. OR [Object] LIKE '% COLUMN %' OR [Object] LIKE '% COLUMN' OR [Object] = 'COLUMN'
  10092. OR [Object] LIKE '% COMMIT %' OR [Object] LIKE '% COMMIT' OR [Object] = 'COMMIT'
  10093. OR [Object] LIKE '% COMPLETION %' OR [Object] LIKE '% COMPLETION' OR [Object] = 'COMPLETION'
  10094. OR [Object] LIKE '% COMPUTE %' OR [Object] LIKE '% COMPUTE' OR [Object] = 'COMPUTE'
  10095. OR [Object] LIKE '% CONNECT %' OR [Object] LIKE '% CONNECT' OR [Object] = 'CONNECT'
  10096. OR [Object] LIKE '% CONNECTION %' OR [Object] LIKE '% CONNECTION' OR [Object] = 'CONNECTION'
  10097. OR [Object] LIKE '% CONSTRAINT %' OR [Object] LIKE '% CONSTRAINT' OR [Object] = 'CONSTRAINT'
  10098. OR [Object] LIKE '% CONSTRAINTS %' OR [Object] LIKE '% CONSTRAINTS' OR [Object] = 'CONSTRAINTS'
  10099. OR [Object] LIKE '% CONSTRUCTOR %' OR [Object] LIKE '% CONSTRUCTOR' OR [Object] = 'CONSTRUCTOR'
  10100. OR [Object] LIKE '% CONTAINS %' OR [Object] LIKE '% CONTAINS' OR [Object] = 'CONTAINS'
  10101. OR [Object] LIKE '% CONTAINSTABLE %' OR [Object] LIKE '% CONTAINSTABLE' OR [Object] = 'CONTAINSTABLE'
  10102. OR [Object] LIKE '% CONTINUE %' OR [Object] LIKE '% CONTINUE' OR [Object] = 'CONTINUE'
  10103. OR [Object] LIKE '% CONVERT %' OR [Object] LIKE '% CONVERT' OR [Object] = 'CONVERT'
  10104. OR [Object] LIKE '% CORRESPONDING %' OR [Object] LIKE '% CORRESPONDING' OR [Object] = 'CORRESPONDING'
  10105. OR [Object] LIKE '% COUNT %' OR [Object] LIKE '% COUNT' OR [Object] = 'COUNT'
  10106. OR [Object] LIKE '% CREATE %' OR [Object] LIKE '% CREATE' OR [Object] = 'CREATE'
  10107. OR [Object] LIKE '% CROSS %' OR [Object] LIKE '% CROSS' OR [Object] = 'CROSS'
  10108. OR [Object] LIKE '% CUBE %' OR [Object] LIKE '% CUBE' OR [Object] = 'CUBE'
  10109. OR [Object] LIKE '% CURRENT %' OR [Object] LIKE '% CURRENT' OR [Object] = 'CURRENT'
  10110. OR [Object] LIKE '% CURRENT_DATE %' OR [Object] LIKE '% CURRENT_DATE' OR [Object] = 'CURRENT_DATE'
  10111. OR [Object] LIKE '% CURRENT_PATH %' OR [Object] LIKE '% CURRENT_PATH' OR [Object] = 'CURRENT_PATH'
  10112. OR [Object] LIKE '% CURRENT_ROLE %' OR [Object] LIKE '% CURRENT_ROLE' OR [Object] = 'CURRENT_ROLE'
  10113. OR [Object] LIKE '% CURRENT_TIME %' OR [Object] LIKE '% CURRENT_TIME' OR [Object] = 'CURRENT_TIME'
  10114. OR [Object] LIKE '% CURRENT_TIMESTAMP %' OR [Object] LIKE '% CURRENT_TIMESTAMP' OR [Object] = 'CURRENT_TIMESTAMP'
  10115. OR [Object] LIKE '% CURRENT_USER %' OR [Object] LIKE '% CURRENT_USER' OR [Object] = 'CURRENT_USER'
  10116. OR [Object] LIKE '% CURSOR %' OR [Object] LIKE '% CURSOR' OR [Object] = 'CURSOR'
  10117. OR [Object] LIKE '% CYCLE %' OR [Object] LIKE '% CYCLE' OR [Object] = 'CYCLE'
  10118. OR [Object] LIKE '% DATA %' OR [Object] LIKE '% DATA' OR [Object] = 'DATA'
  10119. OR [Object] LIKE '% DATABASE %' OR [Object] LIKE '% DATABASE' OR [Object] = 'DATABASE'
  10120. OR [Object] LIKE '% DATE %' OR [Object] LIKE '% DATE' OR [Object] = 'DATE'
  10121. OR [Object] LIKE '% DAY %' OR [Object] LIKE '% DAY' OR [Object] = 'DAY'
  10122. OR [Object] LIKE '% DBCC %' OR [Object] LIKE '% DBCC' OR [Object] = 'DBCC'
  10123. OR [Object] LIKE '% DEALLOCATE %' OR [Object] LIKE '% DEALLOCATE' OR [Object] = 'DEALLOCATE'
  10124. OR [Object] LIKE '% DEC %' OR [Object] LIKE '% DEC' OR [Object] = 'DEC'
  10125. OR [Object] LIKE '% DECIMAL %' OR [Object] LIKE '% DECIMAL' OR [Object] = 'DECIMAL'
  10126. OR [Object] LIKE '% DECLARE %' OR [Object] LIKE '% DECLARE' OR [Object] = 'DECLARE'
  10127. OR [Object] LIKE '% DEFAULT %' OR [Object] LIKE '% DEFAULT' OR [Object] = 'DEFAULT'
  10128. OR [Object] LIKE '% DEFERRABLE %' OR [Object] LIKE '% DEFERRABLE' OR [Object] = 'DEFERRABLE'
  10129. OR [Object] LIKE '% DEFERRED %' OR [Object] LIKE '% DEFERRED' OR [Object] = 'DEFERRED'
  10130. OR [Object] LIKE '% DELETE %' OR [Object] LIKE '% DELETE' OR [Object] = 'DELETE'
  10131. OR [Object] LIKE '% DENY %' OR [Object] LIKE '% DENY' OR [Object] = 'DENY'
  10132. OR [Object] LIKE '% DEPTH %' OR [Object] LIKE '% DEPTH' OR [Object] = 'DEPTH'
  10133. OR [Object] LIKE '% DEREF %' OR [Object] LIKE '% DEREF' OR [Object] = 'DEREF'
  10134. OR [Object] LIKE '% DESC %' OR [Object] LIKE '% DESC' OR [Object] = 'DESC'
  10135. OR [Object] LIKE '% DESCRIBE %' OR [Object] LIKE '% DESCRIBE' OR [Object] = 'DESCRIBE'
  10136. OR [Object] LIKE '% DESCRIPTOR %' OR [Object] LIKE '% DESCRIPTOR' OR [Object] = 'DESCRIPTOR'
  10137. OR [Object] LIKE '% DESTROY %' OR [Object] LIKE '% DESTROY' OR [Object] = 'DESTROY'
  10138. OR [Object] LIKE '% DESTRUCTOR %' OR [Object] LIKE '% DESTRUCTOR' OR [Object] = 'DESTRUCTOR'
  10139. OR [Object] LIKE '% DETERMINISTIC %' OR [Object] LIKE '% DETERMINISTIC' OR [Object] = 'DETERMINISTIC'
  10140. OR [Object] LIKE '% DIAGNOSTICS %' OR [Object] LIKE '% DIAGNOSTICS' OR [Object] = 'DIAGNOSTICS'
  10141. OR [Object] LIKE '% DICTIONARY %' OR [Object] LIKE '% DICTIONARY' OR [Object] = 'DICTIONARY'
  10142. OR [Object] LIKE '% DISCONNECT %' OR [Object] LIKE '% DISCONNECT' OR [Object] = 'DISCONNECT'
  10143. OR [Object] LIKE '% DISK %' OR [Object] LIKE '% DISK' OR [Object] = 'DISK'
  10144. OR [Object] LIKE '% DISTINCT %' OR [Object] LIKE '% DISTINCT' OR [Object] = 'DISTINCT'
  10145. OR [Object] LIKE '% DISTRIBUTED %' OR [Object] LIKE '% DISTRIBUTED' OR [Object] = 'DISTRIBUTED'
  10146. OR [Object] LIKE '% DOMAIN %' OR [Object] LIKE '% DOMAIN' OR [Object] = 'DOMAIN'
  10147. OR [Object] LIKE '% DOUBLE %' OR [Object] LIKE '% DOUBLE' OR [Object] = 'DOUBLE'
  10148. OR [Object] LIKE '% DROP %' OR [Object] LIKE '% DROP' OR [Object] = 'DROP'
  10149. OR [Object] LIKE '% DUMMY %' OR [Object] LIKE '% DUMMY' OR [Object] = 'DUMMY'
  10150. OR [Object] LIKE '% DUMP %' OR [Object] LIKE '% DUMP' OR [Object] = 'DUMP'
  10151. OR [Object] LIKE '% DYNAMIC %' OR [Object] LIKE '% DYNAMIC' OR [Object] = 'DYNAMIC'
  10152. OR [Object] LIKE '% EACH %' OR [Object] LIKE '% EACH' OR [Object] = 'EACH'
  10153. OR [Object] LIKE '% ELSE %' OR [Object] LIKE '% ELSE' OR [Object] = 'ELSE'
  10154. OR [Object] LIKE '% END %' OR [Object] LIKE '% END' OR [Object] = 'END'
  10155. OR [Object] LIKE '% END-EXEC %' OR [Object] LIKE '% END-EXEC' OR [Object] = 'END-EXEC'
  10156. OR [Object] LIKE '% EQUALS %' OR [Object] LIKE '% EQUALS' OR [Object] = 'EQUALS'
  10157. OR [Object] LIKE '% ERRLVL %' OR [Object] LIKE '% ERRLVL' OR [Object] = 'ERRLVL'
  10158. OR [Object] LIKE '% ESCAPE %' OR [Object] LIKE '% ESCAPE' OR [Object] = 'ESCAPE'
  10159. OR [Object] LIKE '% EVERY %' OR [Object] LIKE '% EVERY' OR [Object] = 'EVERY'
  10160. OR [Object] LIKE '% EXCEPT %' OR [Object] LIKE '% EXCEPT' OR [Object] = 'EXCEPT'
  10161. OR [Object] LIKE '% EXCEPTION %' OR [Object] LIKE '% EXCEPTION' OR [Object] = 'EXCEPTION'
  10162. OR [Object] LIKE '% EXEC %' OR [Object] LIKE '% EXEC' OR [Object] = 'EXEC'
  10163. OR [Object] LIKE '% EXECUTE %' OR [Object] LIKE '% EXECUTE' OR [Object] = 'EXECUTE'
  10164. OR [Object] LIKE '% EXISTS %' OR [Object] LIKE '% EXISTS' OR [Object] = 'EXISTS'
  10165. OR [Object] LIKE '% EXIT %' OR [Object] LIKE '% EXIT' OR [Object] = 'EXIT'
  10166. OR [Object] LIKE '% EXTERNAL %' OR [Object] LIKE '% EXTERNAL' OR [Object] = 'EXTERNAL'
  10167. OR [Object] LIKE '% EXTRACT %' OR [Object] LIKE '% EXTRACT' OR [Object] = 'EXTRACT'
  10168. OR [Object] LIKE '% FALSE %' OR [Object] LIKE '% FALSE' OR [Object] = 'FALSE'
  10169. OR [Object] LIKE '% FETCH %' OR [Object] LIKE '% FETCH' OR [Object] = 'FETCH'
  10170. OR [Object] LIKE '% FILE %' OR [Object] LIKE '% FILE' OR [Object] = 'FILE'
  10171. OR [Object] LIKE '% FILLFACTOR %' OR [Object] LIKE '% FILLFACTOR' OR [Object] = 'FILLFACTOR'
  10172. OR [Object] LIKE '% FIRST %' OR [Object] LIKE '% FIRST' OR [Object] = 'FIRST'
  10173. OR [Object] LIKE '% FLOAT %' OR [Object] LIKE '% FLOAT' OR [Object] = 'FLOAT'
  10174. OR [Object] LIKE '% FOR %' OR [Object] LIKE '% FOR' OR [Object] = 'FOR'
  10175. OR [Object] LIKE '% FOREIGN %' OR [Object] LIKE '% FOREIGN' OR [Object] = 'FOREIGN'
  10176. OR [Object] LIKE '% FORTRAN %' OR [Object] LIKE '% FORTRAN' OR [Object] = 'FORTRAN'
  10177. OR [Object] LIKE '% FOUND %' OR [Object] LIKE '% FOUND' OR [Object] = 'FOUND'
  10178. OR [Object] LIKE '% FREE %' OR [Object] LIKE '% FREE' OR [Object] = 'FREE'
  10179. OR [Object] LIKE '% FREETEXT %' OR [Object] LIKE '% FREETEXT' OR [Object] = 'FREETEXT'
  10180. OR [Object] LIKE '% FREETEXTTABLE %' OR [Object] LIKE '% FREETEXTTABLE' OR [Object] = 'FREETEXTTABLE'
  10181. OR [Object] LIKE '% FROM %' OR [Object] LIKE '% FROM' OR [Object] = 'FROM'
  10182. OR [Object] LIKE '% FULL %' OR [Object] LIKE '% FULL' OR [Object] = 'FULL'
  10183. OR [Object] LIKE '% FULLTEXTTABLE %' OR [Object] LIKE '% FULLTEXTTABLE' OR [Object] = 'FULLTEXTTABLE'
  10184. OR [Object] LIKE '% FUNCTION %' OR [Object] LIKE '% FUNCTION' OR [Object] = 'FUNCTION'
  10185. OR [Object] LIKE '% GENERAL %' OR [Object] LIKE '% GENERAL' OR [Object] = 'GENERAL'
  10186. OR [Object] LIKE '% GET %' OR [Object] LIKE '% GET' OR [Object] = 'GET'
  10187. OR [Object] LIKE '% GLOBAL %' OR [Object] LIKE '% GLOBAL' OR [Object] = 'GLOBAL'
  10188. OR [Object] LIKE '% GO %' OR [Object] LIKE '% GO' OR [Object] = 'GO'
  10189. OR [Object] LIKE '% GOTO %' OR [Object] LIKE '% GOTO' OR [Object] = 'GOTO'
  10190. OR [Object] LIKE '% GRANT %' OR [Object] LIKE '% GRANT' OR [Object] = 'GRANT'
  10191. OR [Object] LIKE '% GROUP %' OR [Object] LIKE '% GROUP' OR [Object] = 'GROUP'
  10192. OR [Object] LIKE '% GROUPING %' OR [Object] LIKE '% GROUPING' OR [Object] = 'GROUPING'
  10193. OR [Object] LIKE '% HAVING %' OR [Object] LIKE '% HAVING' OR [Object] = 'HAVING'
  10194. OR [Object] LIKE '% HOLDLOCK %' OR [Object] LIKE '% HOLDLOCK' OR [Object] = 'HOLDLOCK'
  10195. OR [Object] LIKE '% HOST %' OR [Object] LIKE '% HOST' OR [Object] = 'HOST'
  10196. OR [Object] LIKE '% HOUR %' OR [Object] LIKE '% HOUR' OR [Object] = 'HOUR'
  10197. OR [Object] LIKE '% IDENTITY %' OR [Object] LIKE '% IDENTITY' OR [Object] = 'IDENTITY'
  10198. OR [Object] LIKE '% IDENTITY_INSERT %' OR [Object] LIKE '% IDENTITY_INSERT' OR [Object] = 'IDENTITY_INSERT'
  10199. OR [Object] LIKE '% IDENTITYCOL %' OR [Object] LIKE '% IDENTITYCOL' OR [Object] = 'IDENTITYCOL'
  10200. OR [Object] LIKE '% IF %' OR [Object] LIKE '% IF' OR [Object] = 'IF'
  10201. OR [Object] LIKE '% IGNORE %' OR [Object] LIKE '% IGNORE' OR [Object] = 'IGNORE'
  10202. OR [Object] LIKE '% IMMEDIATE %' OR [Object] LIKE '% IMMEDIATE' OR [Object] = 'IMMEDIATE'
  10203. OR [Object] LIKE '% IN %' OR [Object] LIKE '% IN' OR [Object] = 'IN'
  10204. OR [Object] LIKE '% INCLUDE %' OR [Object] LIKE '% INCLUDE' OR [Object] = 'INCLUDE'
  10205. OR [Object] LIKE '% INDEX %' OR [Object] LIKE '% INDEX' OR [Object] = 'INDEX'
  10206. OR [Object] LIKE '% INDICATOR %' OR [Object] LIKE '% INDICATOR' OR [Object] = 'INDICATOR'
  10207. OR [Object] LIKE '% INITIALIZE %' OR [Object] LIKE '% INITIALIZE' OR [Object] = 'INITIALIZE'
  10208. OR [Object] LIKE '% INITIALLY %' OR [Object] LIKE '% INITIALLY' OR [Object] = 'INITIALLY'
  10209. OR [Object] LIKE '% INNER %' OR [Object] LIKE '% INNER' OR [Object] = 'INNER'
  10210. OR [Object] LIKE '% INOUT %' OR [Object] LIKE '% INOUT' OR [Object] = 'INOUT'
  10211. OR [Object] LIKE '% INPUT %' OR [Object] LIKE '% INPUT' OR [Object] = 'INPUT'
  10212. OR [Object] LIKE '% INSENSITIVE %' OR [Object] LIKE '% INSENSITIVE' OR [Object] = 'INSENSITIVE'
  10213. OR [Object] LIKE '% INSERT %' OR [Object] LIKE '% INSERT' OR [Object] = 'INSERT'
  10214. OR [Object] LIKE '% INT %' OR [Object] LIKE '% INT' OR [Object] = 'INT'
  10215. OR [Object] LIKE '% INTEGER %' OR [Object] LIKE '% INTEGER' OR [Object] = 'INTEGER'
  10216. OR [Object] LIKE '% INTERSECT %' OR [Object] LIKE '% INTERSECT' OR [Object] = 'INTERSECT'
  10217. OR [Object] LIKE '% INTERVAL %' OR [Object] LIKE '% INTERVAL' OR [Object] = 'INTERVAL'
  10218. OR [Object] LIKE '% INTO %' OR [Object] LIKE '% INTO' OR [Object] = 'INTO'
  10219. OR [Object] LIKE '% IS %' OR [Object] LIKE '% IS' OR [Object] = 'IS'
  10220. OR [Object] LIKE '% ISOLATION %' OR [Object] LIKE '% ISOLATION' OR [Object] = 'ISOLATION'
  10221. OR [Object] LIKE '% ITERATE %' OR [Object] LIKE '% ITERATE' OR [Object] = 'ITERATE'
  10222. OR [Object] LIKE '% JOIN %' OR [Object] LIKE '% JOIN' OR [Object] = 'JOIN'
  10223. OR [Object] LIKE '% KEY %' OR [Object] LIKE '% KEY' OR [Object] = 'KEY'
  10224. OR [Object] LIKE '% KILL %' OR [Object] LIKE '% KILL' OR [Object] = 'KILL'
  10225. OR [Object] LIKE '% LANGUAGE %' OR [Object] LIKE '% LANGUAGE' OR [Object] = 'LANGUAGE'
  10226. OR [Object] LIKE '% LARGE %' OR [Object] LIKE '% LARGE' OR [Object] = 'LARGE'
  10227. OR [Object] LIKE '% LAST %' OR [Object] LIKE '% LAST' OR [Object] = 'LAST'
  10228. OR [Object] LIKE '% LATERAL %' OR [Object] LIKE '% LATERAL' OR [Object] = 'LATERAL'
  10229. OR [Object] LIKE '% LEADING %' OR [Object] LIKE '% LEADING' OR [Object] = 'LEADING'
  10230. OR [Object] LIKE '% LEFT %' OR [Object] LIKE '% LEFT' OR [Object] = 'LEFT'
  10231. OR [Object] LIKE '% LESS %' OR [Object] LIKE '% LESS' OR [Object] = 'LESS'
  10232. OR [Object] LIKE '% LEVEL %' OR [Object] LIKE '% LEVEL' OR [Object] = 'LEVEL'
  10233. OR [Object] LIKE '% LIKE %' OR [Object] LIKE '% LIKE' OR [Object] = 'LIKE'
  10234. OR [Object] LIKE '% LIMIT %' OR [Object] LIKE '% LIMIT' OR [Object] = 'LIMIT'
  10235. OR [Object] LIKE '% LINENO %' OR [Object] LIKE '% LINENO' OR [Object] = 'LINENO'
  10236. OR [Object] LIKE '% LOAD %' OR [Object] LIKE '% LOAD' OR [Object] = 'LOAD'
  10237. OR [Object] LIKE '% LOCAL %' OR [Object] LIKE '% LOCAL' OR [Object] = 'LOCAL'
  10238. OR [Object] LIKE '% LOCALTIME %' OR [Object] LIKE '% LOCALTIME' OR [Object] = 'LOCALTIME'
  10239. OR [Object] LIKE '% LOCALTIMESTAMP %' OR [Object] LIKE '% LOCALTIMESTAMP' OR [Object] = 'LOCALTIMESTAMP'
  10240. OR [Object] LIKE '% LOCATOR %' OR [Object] LIKE '% LOCATOR' OR [Object] = 'LOCATOR'
  10241. OR [Object] LIKE '% LOWER %' OR [Object] LIKE '% LOWER' OR [Object] = 'LOWER'
  10242. OR [Object] LIKE '% MAP %' OR [Object] LIKE '% MAP' OR [Object] = 'MAP'
  10243. OR [Object] LIKE '% MATCH %' OR [Object] LIKE '% MATCH' OR [Object] = 'MATCH'
  10244. OR [Object] LIKE '% MAX %' OR [Object] LIKE '% MAX' OR [Object] = 'MAX'
  10245. OR [Object] LIKE '% MIN %' OR [Object] LIKE '% MIN' OR [Object] = 'MIN'
  10246. OR [Object] LIKE '% MINUTE %' OR [Object] LIKE '% MINUTE' OR [Object] = 'MINUTE'
  10247. OR [Object] LIKE '% MODIFIES %' OR [Object] LIKE '% MODIFIES' OR [Object] = 'MODIFIES'
  10248. OR [Object] LIKE '% MODIFY %' OR [Object] LIKE '% MODIFY' OR [Object] = 'MODIFY'
  10249. OR [Object] LIKE '% MODULE %' OR [Object] LIKE '% MODULE' OR [Object] = 'MODULE'
  10250. OR [Object] LIKE '% MONTH %' OR [Object] LIKE '% MONTH' OR [Object] = 'MONTH'
  10251. OR [Object] LIKE '% NAMES %' OR [Object] LIKE '% NAMES' OR [Object] = 'NAMES'
  10252. OR [Object] LIKE '% NATIONAL %' OR [Object] LIKE '% NATIONAL' OR [Object] = 'NATIONAL'
  10253. OR [Object] LIKE '% NATURAL %' OR [Object] LIKE '% NATURAL' OR [Object] = 'NATURAL'
  10254. OR [Object] LIKE '% NCHAR %' OR [Object] LIKE '% NCHAR' OR [Object] = 'NCHAR'
  10255. OR [Object] LIKE '% NCLOB %' OR [Object] LIKE '% NCLOB' OR [Object] = 'NCLOB'
  10256. OR [Object] LIKE '% NEW %' OR [Object] LIKE '% NEW' OR [Object] = 'NEW'
  10257. OR [Object] LIKE '% NEXT %' OR [Object] LIKE '% NEXT' OR [Object] = 'NEXT'
  10258. OR [Object] LIKE '% NO %' OR [Object] LIKE '% NO' OR [Object] = 'NO'
  10259. OR [Object] LIKE '% NOCHECK %' OR [Object] LIKE '% NOCHECK' OR [Object] = 'NOCHECK'
  10260. OR [Object] LIKE '% NONCLUSTERED %' OR [Object] LIKE '% NONCLUSTERED' OR [Object] = 'NONCLUSTERED'
  10261. OR [Object] LIKE '% NONE %' OR [Object] LIKE '% NONE' OR [Object] = 'NONE'
  10262. OR [Object] LIKE '% NOT %' OR [Object] LIKE '% NOT' OR [Object] = 'NOT'
  10263. OR [Object] LIKE '% NULL %' OR [Object] LIKE '% NULL' OR [Object] = 'NULL'
  10264. OR [Object] LIKE '% NULLIF %' OR [Object] LIKE '% NULLIF' OR [Object] = 'NULLIF'
  10265. OR [Object] LIKE '% NUMERIC %' OR [Object] LIKE '% NUMERIC' OR [Object] = 'NUMERIC'
  10266. OR [Object] LIKE '% OBJECT %' OR [Object] LIKE '% OBJECT' OR [Object] = 'OBJECT'
  10267. OR [Object] LIKE '% OCTET_LENGTH %' OR [Object] LIKE '% OCTET_LENGTH' OR [Object] = 'OCTET_LENGTH'
  10268. OR [Object] LIKE '% OF %' OR [Object] LIKE '% OF' OR [Object] = 'OF'
  10269. OR [Object] LIKE '% OFF %' OR [Object] LIKE '% OFF' OR [Object] = 'OFF'
  10270. OR [Object] LIKE '% OFFSETS %' OR [Object] LIKE '% OFFSETS' OR [Object] = 'OFFSETS'
  10271. OR [Object] LIKE '% OLD %' OR [Object] LIKE '% OLD' OR [Object] = 'OLD'
  10272. OR [Object] LIKE '% ON %' OR [Object] LIKE '% ON' OR [Object] = 'ON'
  10273. OR [Object] LIKE '% ONLY %' OR [Object] LIKE '% ONLY' OR [Object] = 'ONLY'
  10274. OR [Object] LIKE '% OPEN %' OR [Object] LIKE '% OPEN' OR [Object] = 'OPEN'
  10275. OR [Object] LIKE '% OPENDATASOURCE %' OR [Object] LIKE '% OPENDATASOURCE' OR [Object] = 'OPENDATASOURCE'
  10276. OR [Object] LIKE '% OPENQUERY %' OR [Object] LIKE '% OPENQUERY' OR [Object] = 'OPENQUERY'
  10277. OR [Object] LIKE '% OPENROWSET %' OR [Object] LIKE '% OPENROWSET' OR [Object] = 'OPENROWSET'
  10278. OR [Object] LIKE '% OPENXML %' OR [Object] LIKE '% OPENXML' OR [Object] = 'OPENXML'
  10279. OR [Object] LIKE '% OPERATION %' OR [Object] LIKE '% OPERATION' OR [Object] = 'OPERATION'
  10280. OR [Object] LIKE '% OPTION %' OR [Object] LIKE '% OPTION' OR [Object] = 'OPTION'
  10281. OR [Object] LIKE '% OR %' OR [Object] LIKE '% OR' OR [Object] = 'OR'
  10282. OR [Object] LIKE '% ORDER %' OR [Object] LIKE '% ORDER' OR [Object] = 'ORDER'
  10283. OR [Object] LIKE '% ORDINALITY %' OR [Object] LIKE '% ORDINALITY' OR [Object] = 'ORDINALITY'
  10284. OR [Object] LIKE '% OUT %' OR [Object] LIKE '% OUT' OR [Object] = 'OUT'
  10285. OR [Object] LIKE '% OUTER %' OR [Object] LIKE '% OUTER' OR [Object] = 'OUTER'
  10286. OR [Object] LIKE '% OUTPUT %' OR [Object] LIKE '% OUTPUT' OR [Object] = 'OUTPUT'
  10287. OR [Object] LIKE '% OVER %' OR [Object] LIKE '% OVER' OR [Object] = 'OVER'
  10288. OR [Object] LIKE '% OVERLAPS %' OR [Object] LIKE '% OVERLAPS' OR [Object] = 'OVERLAPS'
  10289. OR [Object] LIKE '% PAD %' OR [Object] LIKE '% PAD' OR [Object] = 'PAD'
  10290. OR [Object] LIKE '% PARAMETER %' OR [Object] LIKE '% PARAMETER' OR [Object] = 'PARAMETER'
  10291. OR [Object] LIKE '% PARAMETERS %' OR [Object] LIKE '% PARAMETERS' OR [Object] = 'PARAMETERS'
  10292. OR [Object] LIKE '% PARTIAL %' OR [Object] LIKE '% PARTIAL' OR [Object] = 'PARTIAL'
  10293. OR [Object] LIKE '% PASCAL %' OR [Object] LIKE '% PASCAL' OR [Object] = 'PASCAL'
  10294. OR [Object] LIKE '% PATH %' OR [Object] LIKE '% PATH' OR [Object] = 'PATH'
  10295. OR [Object] LIKE '% PERCENT %' OR [Object] LIKE '% PERCENT' OR [Object] = 'PERCENT'
  10296. OR [Object] LIKE '% PLAN %' OR [Object] LIKE '% PLAN' OR [Object] = 'PLAN'
  10297. OR [Object] LIKE '% POSITION %' OR [Object] LIKE '% POSITION' OR [Object] = 'POSITION'
  10298. OR [Object] LIKE '% POSTFIX %' OR [Object] LIKE '% POSTFIX' OR [Object] = 'POSTFIX'
  10299. OR [Object] LIKE '% PRECISION %' OR [Object] LIKE '% PRECISION' OR [Object] = 'PRECISION'
  10300. OR [Object] LIKE '% PREFIX %' OR [Object] LIKE '% PREFIX' OR [Object] = 'PREFIX'
  10301. OR [Object] LIKE '% PREORDER %' OR [Object] LIKE '% PREORDER' OR [Object] = 'PREORDER'
  10302. OR [Object] LIKE '% PREPARE %' OR [Object] LIKE '% PREPARE' OR [Object] = 'PREPARE'
  10303. OR [Object] LIKE '% PRESERVE %' OR [Object] LIKE '% PRESERVE' OR [Object] = 'PRESERVE'
  10304. OR [Object] LIKE '% PRIMARY %' OR [Object] LIKE '% PRIMARY' OR [Object] = 'PRIMARY'
  10305. OR [Object] LIKE '% PRINT %' OR [Object] LIKE '% PRINT' OR [Object] = 'PRINT'
  10306. OR [Object] LIKE '% PRIOR %' OR [Object] LIKE '% PRIOR' OR [Object] = 'PRIOR'
  10307. OR [Object] LIKE '% PRIVILEGES %' OR [Object] LIKE '% PRIVILEGES' OR [Object] = 'PRIVILEGES'
  10308. OR [Object] LIKE '% PROC %' OR [Object] LIKE '% PROC' OR [Object] = 'PROC'
  10309. OR [Object] LIKE '% PROCEDURE %' OR [Object] LIKE '% PROCEDURE' OR [Object] = 'PROCEDURE'
  10310. OR [Object] LIKE '% PUBLIC %' OR [Object] LIKE '% PUBLIC' OR [Object] = 'PUBLIC'
  10311. OR [Object] LIKE '% RAISERROR %' OR [Object] LIKE '% RAISERROR' OR [Object] = 'RAISERROR'
  10312. OR [Object] LIKE '% READ %' OR [Object] LIKE '% READ' OR [Object] = 'READ'
  10313. OR [Object] LIKE '% READS %' OR [Object] LIKE '% READS' OR [Object] = 'READS'
  10314. OR [Object] LIKE '% READTEXT %' OR [Object] LIKE '% READTEXT' OR [Object] = 'READTEXT'
  10315. OR [Object] LIKE '% REAL %' OR [Object] LIKE '% REAL' OR [Object] = 'REAL'
  10316. OR [Object] LIKE '% RECONFIGURE %' OR [Object] LIKE '% RECONFIGURE' OR [Object] = 'RECONFIGURE'
  10317. OR [Object] LIKE '% RECURSIVE %' OR [Object] LIKE '% RECURSIVE' OR [Object] = 'RECURSIVE'
  10318. OR [Object] LIKE '% REF %' OR [Object] LIKE '% REF' OR [Object] = 'REF'
  10319. OR [Object] LIKE '% REFERENCES %' OR [Object] LIKE '% REFERENCES' OR [Object] = 'REFERENCES'
  10320. OR [Object] LIKE '% REFERENCING %' OR [Object] LIKE '% REFERENCING' OR [Object] = 'REFERENCING'
  10321. OR [Object] LIKE '% RELATIVE %' OR [Object] LIKE '% RELATIVE' OR [Object] = 'RELATIVE'
  10322. OR [Object] LIKE '% REPLICATION %' OR [Object] LIKE '% REPLICATION' OR [Object] = 'REPLICATION'
  10323. OR [Object] LIKE '% RESTORE %' OR [Object] LIKE '% RESTORE' OR [Object] = 'RESTORE'
  10324. OR [Object] LIKE '% RESTRICT %' OR [Object] LIKE '% RESTRICT' OR [Object] = 'RESTRICT'
  10325. OR [Object] LIKE '% RESULT %' OR [Object] LIKE '% RESULT' OR [Object] = 'RESULT'
  10326. OR [Object] LIKE '% RETURN %' OR [Object] LIKE '% RETURN' OR [Object] = 'RETURN'
  10327. OR [Object] LIKE '% RETURNS %' OR [Object] LIKE '% RETURNS' OR [Object] = 'RETURNS'
  10328. OR [Object] LIKE '% REVOKE %' OR [Object] LIKE '% REVOKE' OR [Object] = 'REVOKE'
  10329. OR [Object] LIKE '% RIGHT %' OR [Object] LIKE '% RIGHT' OR [Object] = 'RIGHT'
  10330. OR [Object] LIKE '% ROLE %' OR [Object] LIKE '% ROLE' OR [Object] = 'ROLE'
  10331. OR [Object] LIKE '% ROLLBACK %' OR [Object] LIKE '% ROLLBACK' OR [Object] = 'ROLLBACK'
  10332. OR [Object] LIKE '% ROLLUP %' OR [Object] LIKE '% ROLLUP' OR [Object] = 'ROLLUP'
  10333. OR [Object] LIKE '% ROUTINE %' OR [Object] LIKE '% ROUTINE' OR [Object] = 'ROUTINE'
  10334. OR [Object] LIKE '% ROW %' OR [Object] LIKE '% ROW' OR [Object] = 'ROW'
  10335. OR [Object] LIKE '% ROWCOUNT %' OR [Object] LIKE '% ROWCOUNT' OR [Object] = 'ROWCOUNT'
  10336. OR [Object] LIKE '% ROWGUIDCOL %' OR [Object] LIKE '% ROWGUIDCOL' OR [Object] = 'ROWGUIDCOL'
  10337. OR [Object] LIKE '% ROWS %' OR [Object] LIKE '% ROWS' OR [Object] = 'ROWS'
  10338. OR [Object] LIKE '% RULE %' OR [Object] LIKE '% RULE' OR [Object] = 'RULE'
  10339. OR [Object] LIKE '% SAVE %' OR [Object] LIKE '% SAVE' OR [Object] = 'SAVE'
  10340. OR [Object] LIKE '% SAVEPOINT %' OR [Object] LIKE '% SAVEPOINT' OR [Object] = 'SAVEPOINT'
  10341. OR [Object] LIKE '% SCHEMA %' OR [Object] LIKE '% SCHEMA' OR [Object] = 'SCHEMA'
  10342. OR [Object] LIKE '% SCOPE %' OR [Object] LIKE '% SCOPE' OR [Object] = 'SCOPE'
  10343. OR [Object] LIKE '% SCROLL %' OR [Object] LIKE '% SCROLL' OR [Object] = 'SCROLL'
  10344. OR [Object] LIKE '% SEARCH %' OR [Object] LIKE '% SEARCH' OR [Object] = 'SEARCH'
  10345. OR [Object] LIKE '% SECOND %' OR [Object] LIKE '% SECOND' OR [Object] = 'SECOND'
  10346. OR [Object] LIKE '% SECTION %' OR [Object] LIKE '% SECTION' OR [Object] = 'SECTION'
  10347. OR [Object] LIKE '% SELECT %' OR [Object] LIKE '% SELECT' OR [Object] = 'SELECT'
  10348. OR [Object] LIKE '% SEQUENCE %' OR [Object] LIKE '% SEQUENCE' OR [Object] = 'SEQUENCE'
  10349. OR [Object] LIKE '% SESSION %' OR [Object] LIKE '% SESSION' OR [Object] = 'SESSION'
  10350. OR [Object] LIKE '% SESSION_USER %' OR [Object] LIKE '% SESSION_USER' OR [Object] = 'SESSION_USER'
  10351. OR [Object] LIKE '% SET %' OR [Object] LIKE '% SET' OR [Object] = 'SET'
  10352. OR [Object] LIKE '% SETS %' OR [Object] LIKE '% SETS' OR [Object] = 'SETS'
  10353. OR [Object] LIKE '% SETUSER %' OR [Object] LIKE '% SETUSER' OR [Object] = 'SETUSER'
  10354. OR [Object] LIKE '% SHUTDOWN %' OR [Object] LIKE '% SHUTDOWN' OR [Object] = 'SHUTDOWN'
  10355. OR [Object] LIKE '% SIZE %' OR [Object] LIKE '% SIZE' OR [Object] = 'SIZE'
  10356. OR [Object] LIKE '% SMALLINT %' OR [Object] LIKE '% SMALLINT' OR [Object] = 'SMALLINT'
  10357. OR [Object] LIKE '% SOME %' OR [Object] LIKE '% SOME' OR [Object] = 'SOME'
  10358. OR [Object] LIKE '% SPACE %' OR [Object] LIKE '% SPACE' OR [Object] = 'SPACE'
  10359. OR [Object] LIKE '% SPECIFIC %' OR [Object] LIKE '% SPECIFIC' OR [Object] = 'SPECIFIC'
  10360. OR [Object] LIKE '% SPECIFICTYPE %' OR [Object] LIKE '% SPECIFICTYPE' OR [Object] = 'SPECIFICTYPE'
  10361. OR [Object] LIKE '% SQL %' OR [Object] LIKE '% SQL' OR [Object] = 'SQL'
  10362. OR [Object] LIKE '% SQLCA %' OR [Object] LIKE '% SQLCA' OR [Object] = 'SQLCA'
  10363. OR [Object] LIKE '% SQLCODE %' OR [Object] LIKE '% SQLCODE' OR [Object] = 'SQLCODE'
  10364. OR [Object] LIKE '% SQLERROR %' OR [Object] LIKE '% SQLERROR' OR [Object] = 'SQLERROR'
  10365. OR [Object] LIKE '% SQLEXCEPTION %' OR [Object] LIKE '% SQLEXCEPTION' OR [Object] = 'SQLEXCEPTION'
  10366. OR [Object] LIKE '% SQLSTATE %' OR [Object] LIKE '% SQLSTATE' OR [Object] = 'SQLSTATE'
  10367. OR [Object] LIKE '% SQLWARNING %' OR [Object] LIKE '% SQLWARNING' OR [Object] = 'SQLWARNING'
  10368. OR [Object] LIKE '% START %' OR [Object] LIKE '% START' OR [Object] = 'START'
  10369. OR [Object] LIKE '% STATE %' OR [Object] LIKE '% STATE' OR [Object] = 'STATE'
  10370. OR [Object] LIKE '% STATEMENT %' OR [Object] LIKE '% STATEMENT' OR [Object] = 'STATEMENT'
  10371. OR [Object] LIKE '% STATIC %' OR [Object] LIKE '% STATIC' OR [Object] = 'STATIC'
  10372. OR [Object] LIKE '% STATISTICS %' OR [Object] LIKE '% STATISTICS' OR [Object] = 'STATISTICS'
  10373. OR [Object] LIKE '% STRUCTURE %' OR [Object] LIKE '% STRUCTURE' OR [Object] = 'STRUCTURE'
  10374. OR [Object] LIKE '% SUBSTRING %' OR [Object] LIKE '% SUBSTRING' OR [Object] = 'SUBSTRING'
  10375. OR [Object] LIKE '% SUM %' OR [Object] LIKE '% SUM' OR [Object] = 'SUM'
  10376. OR [Object] LIKE '% SYSTEM_USER %' OR [Object] LIKE '% SYSTEM_USER' OR [Object] = 'SYSTEM_USER'
  10377. OR [Object] LIKE '% TABLE %' OR [Object] LIKE '% TABLE' OR [Object] = 'TABLE'
  10378. OR [Object] LIKE '% TEMPORARY %' OR [Object] LIKE '% TEMPORARY' OR [Object] = 'TEMPORARY'
  10379. OR [Object] LIKE '% TERMINATE %' OR [Object] LIKE '% TERMINATE' OR [Object] = 'TERMINATE'
  10380. OR [Object] LIKE '% TEXTSIZE %' OR [Object] LIKE '% TEXTSIZE' OR [Object] = 'TEXTSIZE'
  10381. OR [Object] LIKE '% THAN %' OR [Object] LIKE '% THAN' OR [Object] = 'THAN'
  10382. OR [Object] LIKE '% THEN %' OR [Object] LIKE '% THEN' OR [Object] = 'THEN'
  10383. OR [Object] LIKE '% TIME %' OR [Object] LIKE '% TIME' OR [Object] = 'TIME'
  10384. OR [Object] LIKE '% TIMESTAMP %' OR [Object] LIKE '% TIMESTAMP' OR [Object] = 'TIMESTAMP'
  10385. OR [Object] LIKE '% TIMEZONE_HOUR %' OR [Object] LIKE '% TIMEZONE_HOUR' OR [Object] = 'TIMEZONE_HOUR'
  10386. OR [Object] LIKE '% TIMEZONE_MINUTE %' OR [Object] LIKE '% TIMEZONE_MINUTE' OR [Object] = 'TIMEZONE_MINUTE'
  10387. OR [Object] LIKE '% TO %' OR [Object] LIKE '% TO' OR [Object] = 'TO'
  10388. OR [Object] LIKE '% TOP %' OR [Object] LIKE '% TOP' OR [Object] = 'TOP'
  10389. OR [Object] LIKE '% TRAILING %' OR [Object] LIKE '% TRAILING' OR [Object] = 'TRAILING'
  10390. OR [Object] LIKE '% TRAN %' OR [Object] LIKE '% TRAN' OR [Object] = 'TRAN'
  10391. OR [Object] LIKE '% TRANSACTION %' OR [Object] LIKE '% TRANSACTION' OR [Object] = 'TRANSACTION'
  10392. OR [Object] LIKE '% TRANSLATE %' OR [Object] LIKE '% TRANSLATE' OR [Object] = 'TRANSLATE'
  10393. OR [Object] LIKE '% TRANSLATION %' OR [Object] LIKE '% TRANSLATION' OR [Object] = 'TRANSLATION'
  10394. OR [Object] LIKE '% TREAT %' OR [Object] LIKE '% TREAT' OR [Object] = 'TREAT'
  10395. OR [Object] LIKE '% TRIGGER %' OR [Object] LIKE '% TRIGGER' OR [Object] = 'TRIGGER'
  10396. OR [Object] LIKE '% TRIM %' OR [Object] LIKE '% TRIM' OR [Object] = 'TRIM'
  10397. OR [Object] LIKE '% TRUE %' OR [Object] LIKE '% TRUE' OR [Object] = 'TRUE'
  10398. OR [Object] LIKE '% TRUNCATE %' OR [Object] LIKE '% TRUNCATE' OR [Object] = 'TRUNCATE'
  10399. OR [Object] LIKE '% UNDER %' OR [Object] LIKE '% UNDER' OR [Object] = 'UNDER'
  10400. OR [Object] LIKE '% UNION %' OR [Object] LIKE '% UNION' OR [Object] = 'UNION'
  10401. OR [Object] LIKE '% UNIQUE %' OR [Object] LIKE '% UNIQUE' OR [Object] = 'UNIQUE'
  10402. OR [Object] LIKE '% UNKNOWN %' OR [Object] LIKE '% UNKNOWN' OR [Object] = 'UNKNOWN'
  10403. OR [Object] LIKE '% UNNEST %' OR [Object] LIKE '% UNNEST' OR [Object] = 'UNNEST'
  10404. OR [Object] LIKE '% UPDATE %' OR [Object] LIKE '% UPDATE' OR [Object] = 'UPDATE'
  10405. OR [Object] LIKE '% UPDATETEXT %' OR [Object] LIKE '% UPDATETEXT' OR [Object] = 'UPDATETEXT'
  10406. OR [Object] LIKE '% UPPER %' OR [Object] LIKE '% UPPER' OR [Object] = 'UPPER'
  10407. OR [Object] LIKE '% USAGE %' OR [Object] LIKE '% USAGE' OR [Object] = 'USAGE'
  10408. OR [Object] LIKE '% USE %' OR [Object] LIKE '% USE' OR [Object] = 'USE'
  10409. OR [Object] LIKE '% USER %' OR [Object] LIKE '% USER' OR [Object] = 'USER'
  10410. OR [Object] LIKE '% USING %' OR [Object] LIKE '% USING' OR [Object] = 'USING'
  10411. OR [Object] LIKE '% VALUE %' OR [Object] LIKE '% VALUE' OR [Object] = 'VALUE'
  10412. OR [Object] LIKE '% VALUES %' OR [Object] LIKE '% VALUES' OR [Object] = 'VALUES'
  10413. OR [Object] LIKE '% VARCHAR %' OR [Object] LIKE '% VARCHAR' OR [Object] = 'VARCHAR'
  10414. OR [Object] LIKE '% VARIABLE %' OR [Object] LIKE '% VARIABLE' OR [Object] = 'VARIABLE'
  10415. OR [Object] LIKE '% VARYING %' OR [Object] LIKE '% VARYING' OR [Object] = 'VARYING'
  10416. OR [Object] LIKE '% VIEW %' OR [Object] LIKE '% VIEW' OR [Object] = 'VIEW'
  10417. OR [Object] LIKE '% WAITFOR %' OR [Object] LIKE '% WAITFOR' OR [Object] = 'WAITFOR'
  10418. OR [Object] LIKE '% WHEN %' OR [Object] LIKE '% WHEN' OR [Object] = 'WHEN'
  10419. OR [Object] LIKE '% WHENEVER %' OR [Object] LIKE '% WHENEVER' OR [Object] = 'WHENEVER'
  10420. OR [Object] LIKE '% WHERE %' OR [Object] LIKE '% WHERE' OR [Object] = 'WHERE'
  10421. OR [Object] LIKE '% WHILE %' OR [Object] LIKE '% WHILE' OR [Object] = 'WHILE'
  10422. OR [Object] LIKE '% WITH %' OR [Object] LIKE '% WITH' OR [Object] = 'WITH'
  10423. OR [Object] LIKE '% WITHOUT %' OR [Object] LIKE '% WITHOUT' OR [Object] = 'WITHOUT'
  10424. OR [Object] LIKE '% WORK %' OR [Object] LIKE '% WORK' OR [Object] = 'WORK'
  10425. OR [Object] LIKE '% WRITE %' OR [Object] LIKE '% WRITE' OR [Object] = 'WRITE'
  10426. OR [Object] LIKE '% WRITETEXT %' OR [Object] LIKE '% WRITETEXT' OR [Object] = 'WRITETEXT'
  10427. OR [Object] LIKE '% YEAR %' OR [Object] LIKE '% YEAR' OR [Object] = 'YEAR'
  10428. OR [Object] LIKE '% ZONE %' OR [Object] LIKE '% ZONE' OR [Object] = 'ZONE');
  10429. /* http://msdn.microsoft.com/en-us/library/ms186755.aspx */
  10430. INSERT INTO #tmpfinalobjectnames
  10431. SELECT 5, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10432. FROM #tmpobjectnames
  10433. WHERE [type] IN ('FN','FS','TF','IF') AND [Object] LIKE 'fn[_]%'
  10434. AND [Object] NOT IN ('fn_diagram_objects');
  10435. IF (SELECT COUNT(*) FROM #tmpfinalobjectnames) > 0
  10436. BEGIN
  10437. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check], '[WARNING: Reserved words or special characters have been found in object names]' AS [Deviation]
  10438. END
  10439. ELSE
  10440. BEGIN
  10441. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check], '[OK]' AS [Deviation]
  10442. END;
  10443. IF (SELECT COUNT(*) FROM #tmpfinalobjectnames) > 0
  10444. BEGIN
  10445. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check],
  10446. CASE [Deviation] WHEN 1 THEN '[sp_ as prefix for stored procedures]'
  10447. WHEN 2 THEN '[Special character as part of object name]'
  10448. WHEN 3 THEN '[Special character as part of column name]'
  10449. WHEN 4 THEN '[Reserved words as part of object name]'
  10450. WHEN 5 THEN '[fn_ as prefix for user defined functions]'
  10451. END AS [Deviation],
  10452. [DBName] AS [Database_Name], [schemaName] AS [Schema_Name], [Object] AS [Object_Name], QUOTENAME([Col]) AS [Col], [type_desc] AS [Object_Type]
  10453. FROM #tmpfinalobjectnames
  10454. ORDER BY [Deviation], type_desc, [DBName], [schemaName], [Object];
  10455. END;
  10456. RAISERROR (N'|-Starting Security Checks', 10, 1) WITH NOWAIT
  10457. --------------------------------------------------------------------------------------------------------------------------------
  10458. -- Password check subsection
  10459. --------------------------------------------------------------------------------------------------------------------------------
  10460. RAISERROR (N' |-Starting Password check', 10, 1) WITH NOWAIT
  10461. DECLARE @passwords TABLE ([Deviation] VARCHAR(15), [Name] sysname, [CreateDate] DATETIME)
  10462. DECLARE @word TABLE (word NVARCHAR(50))
  10463. INSERT INTO @word values (0)
  10464. INSERT INTO @word values (1)
  10465. INSERT INTO @word values (12)
  10466. INSERT INTO @word values (123)
  10467. INSERT INTO @word values (1234)
  10468. INSERT INTO @word values (12345)
  10469. INSERT INTO @word values (123456)
  10470. INSERT INTO @word values (1234567)
  10471. INSERT INTO @word values (12345678)
  10472. INSERT INTO @word values (123456789)
  10473. INSERT INTO @word values (1234567890)
  10474. INSERT INTO @word values (11111)
  10475. INSERT INTO @word values (111111)
  10476. INSERT INTO @word values (1111111)
  10477. INSERT INTO @word values (11111111)
  10478. INSERT INTO @word values (21)
  10479. INSERT INTO @word values (321)
  10480. INSERT INTO @word values (4321)
  10481. INSERT INTO @word values (54321)
  10482. INSERT INTO @word values (654321)
  10483. INSERT INTO @word values (7654321)
  10484. INSERT INTO @word values (87654321)
  10485. INSERT INTO @word values (987654321)
  10486. INSERT INTO @word values (0987654321)
  10487. INSERT INTO @word values ('pwd')
  10488. INSERT INTO @word values ('Password')
  10489. INSERT INTO @word values ('password')
  10490. INSERT INTO @word values ('P@ssw0rd')
  10491. INSERT INTO @word values ('p@ssw0rd')
  10492. INSERT INTO @word values ('Teste')
  10493. INSERT INTO @word values ('teste')
  10494. INSERT INTO @word values ('Test')
  10495. INSERT INTO @word values ('test')
  10496. INSERT INTO @word values ('')
  10497. INSERT INTO @word values ('p@wd')
  10498. INSERT INTO @passwords
  10499. SELECT DISTINCT 'Weak_Password' AS Deviation, RTRIM(s.name) AS [Name], createdate AS [CreateDate]
  10500. FROM @word d
  10501. INNER JOIN master.sys.syslogins s ON PWDCOMPARE(RTRIM(RTRIM(d.word)), s.[password]) = 1
  10502. UNION ALL
  10503. SELECT 'NULL_Passwords' AS Deviation, RTRIM(name) AS [Name], createdate AS [CreateDate]
  10504. FROM master.sys.syslogins
  10505. WHERE [password] IS NULL
  10506. AND isntname = 0
  10507. AND name NOT IN ('MSCRMSqlClrLogin','##MS_SmoExtendedSigningCertificate##','##MS_PolicySigningCertificate##','##MS_SQLResourceSigningCertificate##','##MS_SQLReplicationSigningCertificate##','##MS_SQLAuthenticatorCertificate##','##MS_AgentSigningCertificate##','##MS_SQLEnableSystemAssemblyLoadingUser##')
  10508. UNION ALL
  10509. SELECT DISTINCT 'Name=Password' AS Deviation, RTRIM(s.name) AS [Name], createdate AS [CreateDate]
  10510. FROM master.sys.syslogins s
  10511. WHERE PWDCOMPARE(RTRIM(RTRIM(s.name)), s.[password]) = 1
  10512. ORDER BY [Deviation], [Name]
  10513. IF (SELECT COUNT([Deviation]) FROM @passwords) > 0
  10514. BEGIN
  10515. SELECT 'Security_checks' AS [Category], 'Password_checks' AS [Check], '[WARNING: Some user logins have weak passwords. Please review these as soon as possible]' AS [Deviation]
  10516. SELECT 'Security_checks' AS [Category], 'Password_checks' AS [Information], [Deviation], [Name], [CreateDate]
  10517. FROM @passwords
  10518. ORDER BY [Deviation], [Name]
  10519. END
  10520. ELSE
  10521. BEGIN
  10522. SELECT 'Security_checks' AS [Category], 'Password_checks' AS [Check], '[OK]' AS [Deviation]
  10523. END;
  10524. RAISERROR (N'|-Starting Maintenance and Monitoring Checks', 10, 1) WITH NOWAIT
  10525. --------------------------------------------------------------------------------------------------------------------------------
  10526. -- SQL Agent alerts for severe errors subsection
  10527. --------------------------------------------------------------------------------------------------------------------------------
  10528. RAISERROR (N' |-Starting SQL Agent alerts for severe errors', 10, 1) WITH NOWAIT
  10529. IF (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 1) = 0 AND (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 2) = 0
  10530. BEGIN
  10531. RAISERROR('[WARNING: If not sysadmin, then you must be a member of MSDB SQLAgentOperatorRole role, or have SELECT permission on the sysalerts table in MSDB. Bypassing check]', 16, 1, N'msdbperms')
  10532. --RETURN
  10533. END
  10534. ELSE
  10535. BEGIN
  10536. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Agent_Alerts_Severity_10' AS [Check], CASE WHEN COUNT([name]) > 0 THEN '[OK]' ELSE '[WARNING: Important errors (825,833,855,856,3452,3619,17179,17883,17884,17887,17888,17890,28036) are not raising alerts. Please review the need to create these]' END AS [Deviation]
  10537. FROM msdb.dbo.sysalerts
  10538. WHERE [message_id] IN (825,833,855,856,3452,3619,17179,17883,17884,17887,17888,17890,28036) OR severity = 10
  10539. UNION ALL
  10540. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Agent_Alerts_Severity_16' AS [Check], CASE WHEN COUNT([name]) > 0 THEN '[OK]' ELSE '[WARNING: Important errors (2508,2511,3271,5228,5229,5242,5243,5250,5901,17130,17300) are not raising alerts. Please review the need to create these]' END AS [Deviation]
  10541. FROM msdb.dbo.sysalerts
  10542. WHERE [message_id] IN (610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300) OR severity = 16
  10543. UNION ALL
  10544. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Agent_Alerts_Severity_17' AS [Check], CASE WHEN COUNT([name]) > 0 THEN '[OK]' ELSE '[WARNING: Important errors (802,845,1101,1105,1121,1214,9002) are not raising alerts. Please review the need to create these]' END AS [Deviation]
  10545. FROM msdb.dbo.sysalerts
  10546. WHERE [message_id] IN (802,845,1101,1105,1121,1214,8642,9002) OR severity = 17
  10547. UNION ALL
  10548. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Agent_Alerts_Severity_19' AS [Check], CASE WHEN COUNT([name]) > 0 THEN '[OK]' ELSE '[WARNING: Important errors (701) are not raising alerts. Please review the need to create these]' END AS [Deviation]
  10549. FROM msdb.dbo.sysalerts
  10550. WHERE [message_id] IN (701) OR severity = 19
  10551. UNION ALL
  10552. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Agent_Alerts_Severity_20' AS [Check], CASE WHEN COUNT([name]) > 0 THEN '[OK]' ELSE '[WARNING: Important errors (3624) are not raising alerts. Please review the need to create these]' END AS [Deviation]
  10553. FROM msdb.dbo.sysalerts
  10554. WHERE [message_id] IN (3624) OR severity = 20
  10555. UNION ALL
  10556. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Agent_Alerts_Severity_21' AS [Check], CASE WHEN COUNT([name]) > 0 THEN '[OK]' ELSE '[WARNING: Important errors (605) are not raising alerts. Please review the need to create these]' END AS [Deviation]
  10557. FROM msdb.dbo.sysalerts
  10558. WHERE [message_id] IN (605) OR severity = 21
  10559. UNION ALL
  10560. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Agent_Alerts_Severity_22' AS [Check], CASE WHEN COUNT([name]) > 0 THEN '[OK]' ELSE '[WARNING: Important errors (5180,8966) are not raising alerts. Please review the need to create these]' END AS [Deviation]
  10561. FROM msdb.dbo.sysalerts
  10562. WHERE [message_id] IN (5180,8966) OR severity = 22
  10563. UNION ALL
  10564. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Agent_Alerts_Severity_23' AS [Check], CASE WHEN COUNT([name]) > 0 THEN '[OK]' ELSE '[WARNING: Important errors (5572,9100) are not raising alerts. Please review the need to create these]' END AS [Deviation]
  10565. FROM msdb.dbo.sysalerts
  10566. WHERE [message_id] IN (5572,9100) OR severity = 23
  10567. UNION ALL
  10568. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Agent_Alerts_Severity_24' AS [Check], CASE WHEN COUNT([name]) > 0 THEN '[OK]' ELSE '[WARNING: Important errors (823,824,832) are not raising alerts. Please review the need to create these]' END AS [Deviation]
  10569. FROM msdb.dbo.sysalerts
  10570. WHERE [message_id] IN (823,824,832) OR severity = 24
  10571. IF (SELECT COUNT([name]) FROM msdb.dbo.sysalerts WHERE ([message_id] IN (825,833,855,856,3452,3619,17179,17883,17884,17887,17888,17890,28036, -- Sev 10
  10572. 610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300, -- Sev 16
  10573. 802,845,1101,1105,1121,1214,8642,9002, -- Sev 17
  10574. 701, -- Sev 19
  10575. 3624, -- Sev 20
  10576. 605, -- Sev 21
  10577. 5180,8966, -- Sev 22
  10578. 5572,9100, -- Sev 23
  10579. 823,824,832 -- Sev 24
  10580. ) OR [severity] >= 17)) > 0
  10581. BEGIN
  10582. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Agent_Alerts' AS [Information], QUOTENAME([name]) AS [Configured_Alert], CASE WHEN [enabled] = 1 THEN 'Enabled' ELSE 'Disabled' END AS [Alert_Status], [event_source] AS [Event_Source], [message_id], [severity]
  10583. FROM msdb.dbo.sysalerts
  10584. WHERE ([message_id] IN (825,833,855,856,3452,3619,17179,17883,17884,17887,17888,17890,28036, -- Sev 10
  10585. 610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300, -- Sev 16
  10586. 802,845,1101,1105,1121,1214,8642,9002, -- Sev 17
  10587. 701, -- Sev 19
  10588. 3624, -- Sev 20
  10589. 605, -- Sev 21
  10590. 5180,8966, -- Sev 22
  10591. 5572,9100, -- Sev 23
  10592. 823,824,832 -- Sev 24
  10593. ) OR [severity] >= 17);
  10594. END
  10595. END;
  10596. --------------------------------------------------------------------------------------------------------------------------------
  10597. -- DBCC CHECKDB, Direct Catalog Updates and Data Purity subsection
  10598. --------------------------------------------------------------------------------------------------------------------------------
  10599. RAISERROR (N' |-Starting DBCC CHECKDB, Direct Catalog Updates and Data Purity', 10, 1) WITH NOWAIT
  10600. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  10601. DROP TABLE #output_dbinfo;
  10602. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  10603. CREATE TABLE #output_dbinfo (ParentObject VARCHAR(255), [Object] VARCHAR(255), Field VARCHAR(255), [value] VARCHAR(255))
  10604. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  10605. DROP TABLE #dbinfo;
  10606. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  10607. CREATE TABLE #dbinfo (rowid int IDENTITY(1,1) PRIMARY KEY CLUSTERED, dbname NVARCHAR(255), lst_known_checkdb DATETIME NULL, updSysCatalog DATETIME NULL, dbi_createVersion int NULL, dbi_dbccFlags int NULL)
  10608. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1)
  10609. BEGIN
  10610. --DECLARE @dbname NVARCHAR(255);
  10611. DECLARE @dbcc bit, @catupd bit, @purity bit;
  10612. DECLARE curDBs CURSOR FAST_FORWARD FOR SELECT name FROM master.sys.databases (NOLOCK) WHERE is_read_only = 0 AND [state] = 0
  10613. OPEN curDBs
  10614. FETCH NEXT FROM curDBs INTO @dbname
  10615. WHILE (@@FETCH_STATUS = 0)
  10616. BEGIN
  10617. SET @dbname = RTRIM(LTRIM(@dbname))
  10618. INSERT INTO #output_dbinfo
  10619. EXEC('DBCC DBINFO(''' + @dbname + ''') WITH TABLERESULTS, NO_INFOMSGS')
  10620. INSERT INTO #dbinfo (dbname, lst_known_checkdb)
  10621. SELECT @dbname, [value] FROM #output_dbinfo WHERE Field LIKE 'dbi_dbccLastKnownGood%';
  10622. UPDATE #dbinfo
  10623. SET #dbinfo.updSysCatalog = #output_dbinfo.[value]
  10624. FROM #output_dbinfo
  10625. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_updSysCatalog%';
  10626. UPDATE #dbinfo
  10627. SET #dbinfo.dbi_createVersion = #output_dbinfo.[value]
  10628. FROM #output_dbinfo
  10629. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_createVersion%';
  10630. UPDATE #dbinfo
  10631. SET #dbinfo.dbi_dbccFlags = #output_dbinfo.[value]
  10632. FROM #output_dbinfo
  10633. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_dbccFlags%';
  10634. TRUNCATE TABLE #output_dbinfo;
  10635. FETCH NEXT FROM curDBs INTO @dbname
  10636. END
  10637. CLOSE curDBs
  10638. DEALLOCATE curDBs;
  10639. ;WITH cte_dbcc (name, lst_known_checkdb) AS (SELECT sd.name, tmpdbi.lst_known_checkdb
  10640. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10641. WHERE sd.database_id <> 2 AND is_read_only = 0 AND [state] = 0)
  10642. SELECT @dbcc = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10643. FROM cte_dbcc WHERE DATEDIFF(dd, lst_known_checkdb, GETDATE()) > 7 OR lst_known_checkdb IS NULL;
  10644. ;WITH cte_catupd (name, updSysCatalog) AS (SELECT sd.name, tmpdbi.updSysCatalog
  10645. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10646. WHERE sd.database_id <> 2 AND is_read_only = 0 AND [state] = 0)
  10647. SELECT @catupd = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10648. FROM cte_catupd WHERE updSysCatalog > '1900-01-01 00:00:00.000';
  10649. ;WITH cte_purity (name, dbi_createVersion, dbi_dbccFlags) AS (SELECT sd.name, tmpdbi.dbi_createVersion, tmpdbi.dbi_dbccFlags
  10650. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10651. WHERE sd.database_id > 4 AND is_read_only = 0 AND [state] = 0)
  10652. SELECT @purity = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10653. FROM cte_purity WHERE dbi_createVersion <= 611 AND dbi_dbccFlags = 0; -- <= SQL Server 2005
  10654. IF @dbcc = 1
  10655. BEGIN
  10656. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'DBCC_CHECKDB' AS [Check], '[WARNING: database integrity checks have not been executed for over 7 days on some or all databases. It is recommended to run DBCC CHECKDB on these databases as soon as possible]' AS [Deviation]
  10657. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'DBCC_CHECKDB' AS [Information], [name] AS [Database_Name], MAX(lst_known_checkdb) AS Last_Known_CHECKDB
  10658. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10659. WHERE database_id <> 2 AND is_read_only = 0 AND [state] = 0
  10660. GROUP BY [name]
  10661. HAVING DATEDIFF(dd, MAX(lst_known_checkdb), GETDATE()) > 7 OR MAX(lst_known_checkdb) IS NULL
  10662. ORDER BY [name]
  10663. END
  10664. ELSE
  10665. BEGIN
  10666. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'DBCC_CHECKDB' AS [Check], '[OK]' AS [Deviation]
  10667. END;
  10668. IF @catupd = 1
  10669. BEGIN
  10670. SELECT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Check], '[WARNING: Microsoft does not support direct catalog updates to databases.]' AS [Deviation]
  10671. SELECT DISTINCT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Information], [name] AS [Database_Name], MAX(updSysCatalog) AS Last_Direct_Catalog_Update
  10672. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10673. WHERE database_id <> 2 AND is_read_only = 0 AND [state] = 0
  10674. GROUP BY [name]
  10675. HAVING (MAX(updSysCatalog) > '1900-01-01 00:00:00.000')
  10676. ORDER BY [name]
  10677. END
  10678. ELSE
  10679. BEGIN
  10680. SELECT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Check], '[OK]' AS [Deviation]
  10681. END;
  10682. -- http://support.microsoft.com/kb/923247/en-us
  10683. -- http://www.sqlskills.com/blogs/paul/checkdb-from-every-angle-how-to-tell-if-data-purity-checks-will-be-run
  10684. IF @purity = 1
  10685. BEGIN
  10686. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Databases_need_data_purity_check' AS [Check], '[WARNING: Databases were found that need to run data purity checks.]' AS [Deviation]
  10687. SELECT DISTINCT 'Maintenance_Monitoring_checks' AS [Category], 'Databases_need_data_purity_check' AS [Information], [name] AS [Database_Name], dbi_dbccFlags AS Needs_Data_Purity_Checks
  10688. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10689. WHERE database_id > 4 AND dbi_createVersion <= 611 AND dbi_dbccFlags = 0 AND is_read_only = 0 AND [state] = 0
  10690. ORDER BY [name]
  10691. END
  10692. ELSE
  10693. BEGIN
  10694. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Databases_need_data_purity_check' AS [Check], '[OK]' AS [Deviation]
  10695. END;
  10696. END
  10697. ELSE
  10698. BEGIN
  10699. RAISERROR('[WARNING: Only a sysadmin can run the "DBCC CHECKDB, Direct Catalog Updates and Data Purity" checks. Bypassing check]', 16, 1, N'sysadmin')
  10700. --RETURN
  10701. END;
  10702. --------------------------------------------------------------------------------------------------------------------------------
  10703. -- AlwaysOn/Mirroring automatic page repair subsection
  10704. -- Refer to "Automatic Page Repair" BOL entry for more information (http://msdn.microsoft.com/en-us/library/bb677167.aspx)
  10705. --------------------------------------------------------------------------------------------------------------------------------
  10706. IF @sqlmajorver > 9
  10707. BEGIN
  10708. RAISERROR (N' |-Starting AlwaysOn/Mirroring automatic page repair', 10, 1) WITH NOWAIT
  10709. IF @sqlmajorver > 10
  10710. BEGIN
  10711. DECLARE @HadrRep int--, @sqlcmd NVARCHAR(4000), @params NVARCHAR(500)
  10712. SET @sqlcmd = N'SELECT @HadrRepOUT = COUNT(*) FROM sys.dm_hadr_auto_page_repair';
  10713. SET @params = N'@HadrRepOUT int OUTPUT';
  10714. EXECUTE sp_executesql @sqlcmd, @params, @HadrRepOUT=@HadrRep OUTPUT;
  10715. END
  10716. ELSE
  10717. BEGIN
  10718. SET @HadrRep = 0
  10719. END;
  10720. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  10721. DROP TABLE #pagerepair;
  10722. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  10723. CREATE TABLE #pagerepair (rowid int IDENTITY(1,1) PRIMARY KEY CLUSTERED, dbname NVARCHAR(255), [file_id] int NULL, [page_id] bigint NULL, error_type smallint NULL, page_status tinyint NULL, lst_modification_time DATETIME NULL, Repair_Source VARCHAR(20) NULL)
  10724. IF (SELECT COUNT(*) FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)) > 0
  10725. BEGIN
  10726. INSERT INTO #pagerepair
  10727. SELECT DB_NAME(database_id) AS [Database_Name], [file_id], [page_id], [error_type], page_status, MAX(modification_time), 'Mirroring' AS [Repair_Source]
  10728. FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)
  10729. GROUP BY database_id, [file_id], [page_id], [error_type], page_status
  10730. END
  10731. IF @HadrRep > 0
  10732. BEGIN
  10733. INSERT INTO #pagerepair
  10734. EXEC ('SELECT DB_NAME(database_id) AS [Database_Name], [file_id], [page_id], [error_type], page_status, MAX(modification_time), ''HADR'' AS [Repair_Source] FROM sys.dm_hadr_auto_page_repair GROUP BY database_id, [file_id], [page_id], [error_type], page_status ORDER BY DB_NAME(database_id), MAX(modification_time) DESC, [file_id], [page_id]')
  10735. END;
  10736. IF (SELECT COUNT(*) FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)) > 0
  10737. OR @HadrRep > 0
  10738. BEGIN
  10739. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Check], '[WARNING: Page repairs have been found. Check for suspect pages]' AS [Deviation]
  10740. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Information], dbname AS [Database_Name],
  10741. [file_id] AS [File_ID],
  10742. [page_id] AS [Page_ID],
  10743. CASE [error_type]
  10744. WHEN -1 THEN 'Error 823'
  10745. WHEN 1 THEN 'Unspecified Error 824'
  10746. WHEN 2 THEN 'Bad Checksum'
  10747. WHEN 3 THEN 'Torn Page'
  10748. ELSE NULL
  10749. END AS [Error_Type],
  10750. CASE page_status
  10751. WHEN 2 THEN 'Queued for request from partner'
  10752. WHEN 3 THEN 'Request sent to partner'
  10753. WHEN 4 THEN 'Queued for automatic page repair'
  10754. WHEN 5 THEN 'Automatic page repair succeeded'
  10755. WHEN 6 THEN 'Irreparable'
  10756. END AS [Page_Status],
  10757. lst_modification_time AS [Last_Modification_Time], [Repair_Source]
  10758. FROM #pagerepair
  10759. END
  10760. ELSE
  10761. BEGIN
  10762. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Check], '[None]' AS [Deviation], '' AS [Source]
  10763. END
  10764. END;
  10765. --------------------------------------------------------------------------------------------------------------------------------
  10766. -- Suspect pages subsection
  10767. -- Refer to "Manage the suspect_pages Table" BOL entry for more information (http://msdn.microsoft.com/en-us/library/ms191301.aspx)
  10768. --------------------------------------------------------------------------------------------------------------------------------
  10769. RAISERROR (N' |-Starting Suspect pages', 10, 1) WITH NOWAIT
  10770. IF (SELECT COUNT(*) FROM msdb.dbo.suspect_pages WHERE (event_type = 1 OR event_type = 2 OR event_type = 3)) > 0
  10771. BEGIN
  10772. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Suspect_Pages' AS [Check], '[WARNING: Suspect pages have been found. Run DBCC CHECKDB to verify affected databases]' AS [Deviation]
  10773. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Suspect_Pages' AS [Information], DB_NAME(database_id) AS [Database_Name],
  10774. [file_id] AS [File_ID],
  10775. [page_id] AS [Page_ID],
  10776. CASE event_type
  10777. WHEN 1 THEN 'Error 823 or unspecified Error 824'
  10778. WHEN 2 THEN 'Bad Checksum'
  10779. WHEN 3 THEN 'Torn Page'
  10780. ELSE NULL
  10781. END AS [Event_Type],
  10782. error_count AS [Error_Count],
  10783. last_update_date AS [Last_Update_Date]
  10784. FROM msdb.dbo.suspect_pages (NOLOCK)
  10785. WHERE (event_type = 1 OR event_type = 2 OR event_type = 3)
  10786. ORDER BY DB_NAME(database_id), last_update_date DESC, [file_id], [page_id]
  10787. END
  10788. ELSE
  10789. BEGIN
  10790. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Suspect_Pages' AS [Check], '[None]' AS [Deviation]
  10791. END;
  10792. --------------------------------------------------------------------------------------------------------------------------------
  10793. -- Replication Errors subsection
  10794. --------------------------------------------------------------------------------------------------------------------------------
  10795. IF @replication = 1 AND (SELECT COUNT(*) FROM master.sys.databases (NOLOCK) WHERE [name] = 'distribution') > 0
  10796. BEGIN
  10797. RAISERROR (N' |-Starting Replication Errors', 10, 1) WITH NOWAIT
  10798. IF (SELECT COUNT(*) FROM distribution.dbo.MSdistribution_history AS msh
  10799. INNER JOIN distribution.dbo.MSrepl_errors AS mse ON mse.id = msh.error_id
  10800. INNER JOIN distribution.dbo.MSdistribution_agents AS msa ON msh.agent_id = msa.id
  10801. WHERE mse.time >= DATEADD(hh, - 24, GETDATE())) > 0
  10802. BEGIN
  10803. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Lst_24H' AS [Check], '[WARNING: Replication Errors have been found in the last 24 hours]' AS [Deviation]
  10804. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Lst_24H' AS [Information],
  10805. msa.[name] AS [Distribution_Agent], msa.publisher_db AS [Publisher_DB],
  10806. msa.publication AS [Publication], msa.subscriber_db AS [Subscriber_DB], mse.error_code
  10807. FROM distribution.dbo.MSdistribution_history AS msh
  10808. INNER JOIN distribution.dbo.MSrepl_errors AS mse ON mse.id = msh.error_id
  10809. INNER JOIN distribution.dbo.MSdistribution_agents AS msa ON msh.agent_id = msa.id
  10810. WHERE mse.time >= DATEADD(hh, - 24, GETDATE())
  10811. GROUP BY msa.[name], msa.publisher_db, msa.publication, msa.subscriber_db, mse.error_code
  10812. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Details' AS [Information], msh.time,
  10813. msa.[name] AS [Distribution_Agent], msa.publisher_db AS [Publisher_DB],
  10814. msa.publication AS [Publication], msa.subscriber_db AS [Subscriber_DB],
  10815. mse.error_code, mse.error_text
  10816. FROM distribution.dbo.MSdistribution_history AS msh (NOLOCK)
  10817. INNER JOIN distribution.dbo.MSrepl_errors AS mse (NOLOCK) ON mse.id = msh.error_id AND mse.time = msh.time
  10818. INNER JOIN distribution.dbo.MSdistribution_agents AS msa (NOLOCK) ON msh.agent_id = msa.id
  10819. WHERE (mse.time >= DATEADD(hh, - 24, GETDATE()))
  10820. ORDER BY msh.time
  10821. END
  10822. ELSE
  10823. BEGIN
  10824. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Lst_24H' AS [Check], '[None]' AS [Deviation]
  10825. END
  10826. END;
  10827. --------------------------------------------------------------------------------------------------------------------------------
  10828. -- Errorlog based checks subsection
  10829. -- Because it is a string based search, add other search conditions as deemed fit.
  10830. --------------------------------------------------------------------------------------------------------------------------------
  10831. RAISERROR (N' |-Starting Errorlog based checks', 10, 1) WITH NOWAIT
  10832. --DECLARE @lognumber int, @logcount int
  10833. DECLARE @langid smallint
  10834. SELECT @langid = lcid FROM sys.syslanguages WHERE name = @@LANGUAGE
  10835. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  10836. OR ISNULL(IS_SRVROLEMEMBER(N'securityadmin'), 0) = 1 -- Is securityadmin
  10837. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_readerrorlog') > 0
  10838. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_readerrorlog') > 0
  10839. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_enumerrorlogs') > 0)
  10840. BEGIN
  10841. SET @lognumber = 0
  10842. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10843. DROP TABLE #dbcc;
  10844. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10845. CREATE TABLE #dbcc (rowid int IDENTITY(1,1) PRIMARY KEY, logid int NULL, logdate DATETIME, spid VARCHAR(50), logmsg VARCHAR(4000))
  10846. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10847. CREATE INDEX [dbcc_logmsg] ON dbo.[#dbcc](logid)
  10848. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  10849. DROP TABLE #avail_logs;
  10850. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  10851. CREATE TABLE #avail_logs (lognum int, logdate DATETIME, logsize int)
  10852. -- Get the number of available logs
  10853. INSERT INTO #avail_logs
  10854. EXEC xp_enumerrorlogs
  10855. SELECT @logcount = MAX(lognum) FROM #avail_logs
  10856. WHILE @lognumber < @logcount
  10857. BEGIN
  10858. -- Cycle thru sql error logs
  10859. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''15 seconds'''
  10860. BEGIN TRY
  10861. INSERT INTO #dbcc (logdate, spid, logmsg)
  10862. EXECUTE (@sqlcmd);
  10863. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10864. END TRY
  10865. BEGIN CATCH
  10866. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10867. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  10868. RAISERROR (@ErrorMessage, 16, 1);
  10869. END CATCH
  10870. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''deadlock'''
  10871. BEGIN TRY
  10872. INSERT INTO #dbcc (logdate, spid, logmsg)
  10873. EXECUTE (@sqlcmd);
  10874. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10875. END TRY
  10876. BEGIN CATCH
  10877. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10878. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  10879. RAISERROR (@ErrorMessage, 16, 1);
  10880. END CATCH
  10881. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''stack dump'''
  10882. BEGIN TRY
  10883. INSERT INTO #dbcc (logdate, spid, logmsg)
  10884. EXECUTE (@sqlcmd);
  10885. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10886. END TRY
  10887. BEGIN CATCH
  10888. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10889. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  10890. RAISERROR (@ErrorMessage, 16, 1);
  10891. END CATCH
  10892. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''Error:'''
  10893. BEGIN TRY
  10894. INSERT INTO #dbcc (logdate, spid, logmsg)
  10895. EXECUTE (@sqlcmd);
  10896. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10897. END TRY
  10898. BEGIN CATCH
  10899. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10900. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 4. ' + ERROR_MESSAGE()
  10901. RAISERROR (@ErrorMessage, 16, 1);
  10902. END CATCH
  10903. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''A significant part of sql server process memory has been paged out'''
  10904. BEGIN TRY
  10905. INSERT INTO #dbcc (logdate, spid, logmsg)
  10906. EXECUTE (@sqlcmd);
  10907. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10908. END TRY
  10909. BEGIN CATCH
  10910. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10911. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 5. ' + ERROR_MESSAGE()
  10912. RAISERROR (@ErrorMessage, 16, 1);
  10913. END CATCH
  10914. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''cachestore flush'''
  10915. BEGIN TRY
  10916. INSERT INTO #dbcc (logdate, spid, logmsg)
  10917. EXECUTE (@sqlcmd);
  10918. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10919. END TRY
  10920. BEGIN CATCH
  10921. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10922. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 6. ' + ERROR_MESSAGE()
  10923. RAISERROR (@ErrorMessage, 16, 1);
  10924. END CATCH
  10925. -- Next log
  10926. --SET @lognumber = @lognumber + 1
  10927. SELECT @lognumber = MIN(lognum) FROM #avail_logs WHERE lognum > @lognumber
  10928. END
  10929. IF (SELECT COUNT([rowid]) FROM #dbcc) > 0
  10930. BEGIN
  10931. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog' AS [Check], '[WARNING: Errorlog contains important messages.]' AS [Deviation];
  10932. ;WITH cte_dbcc (err, errcnt, logdate, logmsg)
  10933. AS (SELECT CASE WHEN logmsg LIKE 'Error: %' THEN RIGHT(LEFT(#dbcc.logmsg, CHARINDEX(',', #dbcc.logmsg)-1), CHARINDEX(',', #dbcc.logmsg)-8)
  10934. WHEN logmsg LIKE 'SQL Server has encountered % longer than 15 seconds %' THEN CONVERT(CHAR(3),833)
  10935. WHEN logmsg LIKE 'A significant part of sql server process memory has been paged out%' THEN CONVERT(CHAR(5),17890)
  10936. ELSE '' END AS err,
  10937. COUNT(logmsg) AS errcnt,
  10938. logdate,
  10939. CASE WHEN logmsg LIKE 'SQL Server has encountered % longer than 15 seconds %' THEN 'SQL Server has encountered XXX occurrence(s) of IO requests taking longer than 15 seconds to complete on file YYY'
  10940. WHEN logmsg LIKE 'A significant part of sql server process memory has been paged out%' THEN 'A significant part of sql server process memory has been paged out.'
  10941. ELSE logmsg END AS logmsg
  10942. FROM #dbcc
  10943. GROUP BY logmsg, logdate
  10944. )
  10945. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog_Summary' AS [Information],
  10946. err AS [Error_Number],
  10947. SUM(errcnt) AS Error_Count,
  10948. MIN(logdate) AS [First_Logged_Date],
  10949. MAX(logdate) AS [Last_Logged_Date],
  10950. logmsg AS [Logged_Message],
  10951. CASE WHEN logmsg LIKE 'Error: 825%' THEN 'IO transient failure. Possible corruption'
  10952. WHEN logmsg LIKE 'Error: 833%' OR logmsg LIKE 'SQL Server has encountered % longer than 15 seconds %' THEN 'Long IO detected: http://support.microsoft.com/kb/897284'
  10953. WHEN logmsg LIKE 'Error: 855%' OR logmsg LIKE 'Error: 856%' THEN 'Hardware memory corruption'
  10954. WHEN logmsg LIKE 'Error: 3452%' THEN 'Metadata inconsistency in DB. Run DBCC CHECKIDENT'
  10955. WHEN logmsg LIKE 'Error: 3619%' THEN 'Chkpoint failed. No Log space available'
  10956. WHEN logmsg LIKE 'Error: 9002%' THEN 'No Log space available'
  10957. WHEN logmsg LIKE 'Error: 17204%' OR logmsg LIKE 'Error: 17207%' THEN 'Error opening file during startup process'
  10958. WHEN logmsg LIKE 'Error: 17179%' THEN 'No AWE - LPIM related'
  10959. WHEN logmsg LIKE 'Error: 17890%' THEN 'sqlservr process paged out'
  10960. WHEN logmsg LIKE 'Error: 2508%' THEN 'Catalog views inaccuracies in DB. Run DBCC UPDATEUSAGE'
  10961. WHEN logmsg LIKE 'Error: 2511%' THEN 'Index Keys errors'
  10962. WHEN logmsg LIKE 'Error: 3271%' THEN 'IO nonrecoverable error'
  10963. WHEN logmsg LIKE 'Error: 5228%' OR logmsg LIKE 'Error: 5229%' THEN 'Online Index operation errors'
  10964. WHEN logmsg LIKE 'Error: 5242%' THEN 'Page structural inconsistency'
  10965. WHEN logmsg LIKE 'Error: 5243%' THEN 'In-memory structural inconsistency'
  10966. WHEN logmsg LIKE 'Error: 5250%' THEN 'Corrupt page. Error cannot be fixed'
  10967. WHEN logmsg LIKE 'Error: 5901%' THEN 'Chkpoint failed. Possible corruption'
  10968. WHEN logmsg LIKE 'Error: 17130%' THEN 'No lock memory'
  10969. WHEN logmsg LIKE 'Error: 17300%' THEN 'Unable to run new system task'
  10970. WHEN logmsg LIKE 'Error: 802%' THEN 'No BP memory'
  10971. WHEN logmsg LIKE 'Error: 845%' OR logmsg LIKE 'Error: 1105%' OR logmsg LIKE 'Error: 1121%' THEN 'No disk space available'
  10972. WHEN logmsg LIKE 'Error: 1214%' THEN 'Internal parallelism error'
  10973. WHEN logmsg LIKE 'Error: 823%' OR logmsg LIKE 'Error: 824%' THEN 'IO failure. Possible corruption'
  10974. WHEN logmsg LIKE 'Error: 832%' THEN 'Page checksum error. Possible corruption'
  10975. WHEN logmsg LIKE 'Error: 3624%' OR logmsg LIKE 'Error: 17065%' OR logmsg LIKE 'Error: 17066%' OR logmsg LIKE 'Error: 17067%' THEN 'System assertion check failed. Possible corruption'
  10976. WHEN logmsg LIKE 'Error: 5572%' THEN 'Possible FILESTREAM corruption'
  10977. WHEN logmsg LIKE 'Error: 9100%' THEN 'Possible index corruption'
  10978. -- How To Diagnose and Correct Errors 17883, 17884, 17887, and 17888 (http://technet.microsoft.com/en-us/library/cc917684.aspx)
  10979. WHEN logmsg LIKE 'Error: 17883%' THEN 'Non-yielding scheduler: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10980. WHEN logmsg LIKE 'Error: 17884%' OR logmsg LIKE 'Error: 17888%' THEN 'Deadlocked scheduler: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10981. WHEN logmsg LIKE 'Error: 17887%' THEN 'IO completion error: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10982. WHEN logmsg LIKE 'Error: 1205%' THEN 'Deadlocked transaction'
  10983. WHEN logmsg LIKE 'Error: 610%' THEN 'Page header invalid. Possible corruption'
  10984. WHEN logmsg LIKE 'Error: 8621%' THEN 'QP stack overflow during optimization. Please simplify the query'
  10985. WHEN logmsg LIKE 'Error: 8642%' THEN 'QP insufficient threads for parallelism'
  10986. WHEN logmsg LIKE 'Error: 701%' THEN 'Insufficient memory'
  10987. -- How to troubleshoot SQL Server error 8645 (http://support.microsoft.com/kb/309256)
  10988. WHEN logmsg LIKE 'Error: 8645%' THEN 'Insufficient memory: http://support.microsoft.com/kb/309256'
  10989. WHEN logmsg LIKE 'Error: 605%' THEN 'Page retrieval failed. Possible corruption'
  10990. -- How to troubleshoot Msg 5180 (http://support.microsoft.com/kb/2015747)
  10991. WHEN logmsg LIKE 'Error: 5180%' THEN 'Invalid file ID. Possible corruption: http://support.microsoft.com/kb/2015747'
  10992. WHEN logmsg LIKE 'Error: 8966%' THEN 'Unable to read and latch on a PFS or GAM page'
  10993. WHEN logmsg LIKE 'Error: 9001%' OR logmsg LIKE 'Error: 9002%' THEN 'Transaction log errors.'
  10994. WHEN logmsg LIKE 'Error: 9003%' OR logmsg LIKE 'Error: 9004%' OR logmsg LIKE 'Error: 9015%' THEN 'Transaction log errors. Possible corruption'
  10995. -- How to reduce paging of buffer pool memory in the 64-bit version of SQL Server (http://support.microsoft.com/kb/918483)
  10996. WHEN logmsg LIKE 'A significant part of sql server process memory has been paged out%' THEN 'SQL Server process was trimmed by the OS. Preventable if LPIM is granted'
  10997. WHEN logmsg LIKE '%cachestore flush%' THEN 'CacheStore flush'
  10998. ELSE '' END AS [Comment],
  10999. CASE WHEN logmsg LIKE 'Error: %' THEN (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(text,'%.*ls','%'),'%d','%'),'%ls','%'),'%S_MSG','%'),'%S_PGID','%'),'%#016I64x','%'),'%p','%'),'%08x','%'),'%u','%'),'%I64d','%'),'%s','%'),'%ld','%'),'%lx','%'), '%%%', '%')
  11000. FROM sys.messages WHERE message_id = (CONVERT(int, RIGHT(LEFT(cte_dbcc.logmsg, CHARINDEX(',', cte_dbcc.logmsg)-1), CHARINDEX(',', cte_dbcc.logmsg)-8))) AND language_id = @langid)
  11001. ELSE '' END AS [Look_for_Message_example]
  11002. FROM cte_dbcc
  11003. GROUP BY err, logmsg
  11004. ORDER BY SUM(errcnt) DESC;
  11005. IF @logdetail = 1
  11006. BEGIN
  11007. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog_Detail' AS [Information], logid AS [Errorlog_Id], logdate AS [Logged_Date], spid AS [Process], logmsg AS [Logged_Message],
  11008. CASE WHEN logmsg LIKE 'Error: 825%' THEN 'IO transient failure. Possible corruption'
  11009. WHEN logmsg LIKE 'Error: 833%' OR logmsg LIKE 'SQL Server has encountered % longer than 15 seconds %' THEN 'Long IO detected'
  11010. WHEN logmsg LIKE 'Error: 855%' OR logmsg LIKE 'Error: 856%' THEN 'Hardware memory corruption'
  11011. WHEN logmsg LIKE 'Error: 3452%' THEN 'Metadata inconsistency in DB. Run DBCC CHECKIDENT'
  11012. WHEN logmsg LIKE 'Error: 3619%' THEN 'Chkpoint failed. No Log space available'
  11013. WHEN logmsg LIKE 'Error: 9002%' THEN 'No Log space available'
  11014. WHEN logmsg LIKE 'Error: 17179%' THEN 'No AWE - LPIM related'
  11015. WHEN logmsg LIKE 'Error: 17890%' THEN 'sqlservr process paged out'
  11016. WHEN logmsg LIKE 'Error: 17204%' OR logmsg LIKE 'Error: 17207%' THEN 'Error opening file during startup process'
  11017. WHEN logmsg LIKE 'Error: 2508%' THEN 'Catalog views inaccuracies in DB. Run DBCC UPDATEUSAGE'
  11018. WHEN logmsg LIKE 'Error: 2511%' THEN 'Index Keys errors'
  11019. WHEN logmsg LIKE 'Error: 3271%' THEN 'IO nonrecoverable error'
  11020. WHEN logmsg LIKE 'Error: 5228%' OR logmsg LIKE 'Error: 5229%' THEN 'Online Index operation errors'
  11021. WHEN logmsg LIKE 'Error: 5242%' THEN 'Page structural inconsistency'
  11022. WHEN logmsg LIKE 'Error: 5243%' THEN 'In-memory structural inconsistency'
  11023. WHEN logmsg LIKE 'Error: 5250%' THEN 'Corrupt page. Error cannot be fixed'
  11024. WHEN logmsg LIKE 'Error: 5901%' THEN 'Chkpoint failed. Possible corruption'
  11025. WHEN logmsg LIKE 'Error: 17130%' THEN 'No lock memory'
  11026. WHEN logmsg LIKE 'Error: 17300%' THEN 'Unable to run new system task'
  11027. WHEN logmsg LIKE 'Error: 802%' THEN 'No BP memory'
  11028. WHEN logmsg LIKE 'Error: 845%' OR logmsg LIKE 'Error: 1105%' OR logmsg LIKE 'Error: 1121%' THEN 'No disk space available'
  11029. WHEN logmsg LIKE 'Error: 1214%' THEN 'Internal parallelism error'
  11030. WHEN logmsg LIKE 'Error: 823%' OR logmsg LIKE 'Error: 824%' THEN 'IO failure. Possible corruption'
  11031. WHEN logmsg LIKE 'Error: 832%' THEN 'Page checksum error. Possible corruption'
  11032. WHEN logmsg LIKE 'Error: 3624%' OR logmsg LIKE 'Error: 17065%' OR logmsg LIKE 'Error: 17066%' OR logmsg LIKE 'Error: 17067%' THEN 'System assertion check failed. Possible corruption'
  11033. WHEN logmsg LIKE 'Error: 5572%' THEN 'Possible FILESTREAM corruption'
  11034. WHEN logmsg LIKE 'Error: 9100%' THEN 'Possible index corruption'
  11035. -- How To Diagnose and Correct Errors 17883, 17884, 17887, and 17888 (http://technet.microsoft.com/en-us/library/cc917684.aspx)
  11036. WHEN logmsg LIKE 'Error: 17883%' THEN 'Non-yielding scheduler'
  11037. WHEN logmsg LIKE 'Error: 17884%' OR logmsg LIKE 'Error: 17888%' THEN 'Deadlocked scheduler'
  11038. WHEN logmsg LIKE 'Error: 17887%' THEN 'IO completion error'
  11039. WHEN logmsg LIKE 'Error: 1205%' THEN 'Deadlocked transaction'
  11040. WHEN logmsg LIKE 'Error: 610%' THEN 'Page header invalid. Possible corruption'
  11041. WHEN logmsg LIKE 'Error: 8621%' THEN 'QP stack overflow during optimization. Please simplify the query'
  11042. WHEN logmsg LIKE 'Error: 8642%' THEN 'QP insufficient threads for parallelism'
  11043. WHEN logmsg LIKE 'Error: 701%' THEN 'Insufficient memory'
  11044. -- How to troubleshoot SQL Server error 8645 (http://support.microsoft.com/kb/309256)
  11045. WHEN logmsg LIKE 'Error: 8645%' THEN 'Insufficient memory'
  11046. WHEN logmsg LIKE 'Error: 605%' THEN 'Page retrieval failed. Possible corruption'
  11047. -- How to troubleshoot Msg 5180 (http://support.microsoft.com/kb/2015747)
  11048. WHEN logmsg LIKE 'Error: 5180%' THEN 'Invalid file ID. Possible corruption'
  11049. WHEN logmsg LIKE 'Error: 8966%' THEN 'Unable to read and latch on a PFS or GAM page'
  11050. WHEN logmsg LIKE 'Error: 9001%' OR logmsg LIKE 'Error: 9002%' THEN 'Transaction log errors.'
  11051. WHEN logmsg LIKE 'Error: 9003%' OR logmsg LIKE 'Error: 9004%' OR logmsg LIKE 'Error: 9015%' THEN 'Transaction log errors. Possible corruption'
  11052. -- How to reduce paging of buffer pool memory in the 64-bit version of SQL Server (http://support.microsoft.com/kb/918483)
  11053. WHEN logmsg LIKE 'A significant part of sql server process memory has been paged out%' THEN 'SQL Server process was trimmed by the OS. Preventable if LPIM is granted'
  11054. WHEN logmsg LIKE '%cachestore flush%' THEN 'CacheStore flush'
  11055. ELSE '' END AS [Comment]
  11056. FROM #dbcc
  11057. ORDER BY logdate DESC
  11058. END
  11059. END
  11060. ELSE
  11061. BEGIN
  11062. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog' AS [Check], '[OK]' AS [Deviation]
  11063. END;
  11064. END
  11065. ELSE
  11066. BEGIN
  11067. RAISERROR('[WARNING: Only a sysadmin or securityadmin can run the "Errorlog" check. Bypassing check]', 16, 1, N'permissions')
  11068. RAISERROR('[WARNING: If not sysadmin or securityadmin, then user must be a granted EXECUTE permissions on the following sprocs to run checks: xp_enumerrorlogs and sp_readerrorlog. Bypassing check]', 16, 1, N'extended_sprocs')
  11069. --RETURN
  11070. END;
  11071. --------------------------------------------------------------------------------------------------------------------------------
  11072. -- System health error checks subsection
  11073. --------------------------------------------------------------------------------------------------------------------------------
  11074. IF @sqlmajorver > 10
  11075. BEGIN
  11076. RAISERROR (N' |-Starting System health checks', 10, 1) WITH NOWAIT
  11077. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11078. DROP TABLE #SystemHealthSessionData;
  11079. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11080. CREATE TABLE #SystemHealthSessionData (target_data XML)
  11081. -- Store the XML data in a temporary table
  11082. INSERT INTO #SystemHealthSessionData
  11083. SELECT CAST(xet.target_data AS XML)
  11084. FROM sys.dm_xe_session_targets xet
  11085. INNER JOIN sys.dm_xe_sessions xe ON xe.address = xet.event_session_address
  11086. WHERE xe.name = 'system_health'
  11087. IF (SELECT COUNT(*) FROM #SystemHealthSessionData a WHERE CONVERT(VARCHAR(max), target_data) LIKE '%error_reported%') > 0
  11088. BEGIN
  11089. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors' AS [Check], '[WARNING: System Health Session contains important messages.]' AS [Deviation];
  11090. -- Get statistical information about all the errors reported
  11091. ;WITH cteHealthSession (EventXML) AS (SELECT C.query('.') EventXML
  11092. FROM #SystemHealthSessionData a
  11093. CROSS APPLY a.target_data.nodes('/RingBufferTarget/event') AS T(C)
  11094. ),
  11095. cteErrorReported (EventTime, ErrorNumber) AS (SELECT EventXML.value('(/event/@timestamp)[1]', 'datetime') AS EventTime,
  11096. EventXML.value('(/event/data[@name="error_number"]/value)[1]', 'int') AS ErrorNumber
  11097. FROM cteHealthSession
  11098. WHERE EventXML.value('(/event/@name)[1]', 'VARCHAR(500)') = 'error_reported'
  11099. )
  11100. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors_Summary' AS [Information],
  11101. ErrorNumber AS [Error_Number],
  11102. MIN(EventTime) AS [First_Logged_Date],
  11103. MAX(EventTime) AS [Last_Logged_Date],
  11104. COUNT(ErrorNumber) AS Error_Count,
  11105. REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(b.text,'%.*ls','%'),'%d','%'),'%ls','%'),'%S_MSG','%'),'%S_PGID','%'),'%#016I64x','%'),'%p','%'),'%08x','%'),'%u','%'),'%I64d','%'),'%s','%'),'%ld','%'),'%lx','%'), '%%%', '%') AS [Look_for_Message_example]
  11106. FROM cteErrorReported a
  11107. INNER JOIN sys.messages b ON a.ErrorNumber = b.message_id
  11108. WHERE b.language_id = @langid
  11109. GROUP BY a.ErrorNumber, b.[text]
  11110. -- Get detailed information about all the errors reported
  11111. ;WITH cteHealthSession AS (SELECT C.query('.').value('(/event/@timestamp)[1]', 'datetime') AS EventTime,
  11112. C.query('.').value('(/event/data[@name="error_number"]/value)[1]', 'int') AS ErrorNumber,
  11113. C.query('.').value('(/event/data[@name="severity"]/value)[1]', 'int') AS ErrorSeverity,
  11114. C.query('.').value('(/event/data[@name="state"]/value)[1]', 'int') AS ErrorState,
  11115. C.query('.').value('(/event/data[@name="message"]/value)[1]', 'VARCHAR(MAX)') AS ErrorText,
  11116. C.query('.').value('(/event/action[@name="session_id"]/value)[1]', 'int') AS SessionID,
  11117. C.query('.').value('(/event/data[@name="category"]/text)[1]', 'VARCHAR(10)') AS ErrorCategory
  11118. FROM #SystemHealthSessionData a
  11119. CROSS APPLY a.target_data.nodes('/RingBufferTarget/event') AS T(C)
  11120. WHERE C.query('.').value('(/event/@name)[1]', 'VARCHAR(500)') = 'error_reported')
  11121. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors_Detail' AS [Information],
  11122. EventTime AS [Logged_Date],
  11123. ErrorNumber AS [Error_Number],
  11124. ErrorSeverity AS [Error_Sev],
  11125. ErrorState AS [Error_State],
  11126. ErrorText AS [Logged_Message],
  11127. SessionID
  11128. FROM cteHealthSession
  11129. ORDER BY EventTime
  11130. END
  11131. ELSE
  11132. BEGIN
  11133. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors' AS [Check], '[OK]' AS [Deviation]
  11134. END;
  11135. END;
  11136. --------------------------------------------------------------------------------------------------------------------------------
  11137. -- Clean up temp objects
  11138. --------------------------------------------------------------------------------------------------------------------------------
  11139. RAISERROR (N'Clearing up temporary objects', 10, 1) WITH NOWAIT
  11140. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  11141. DROP TABLE #dbinfo;
  11142. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  11143. DROP TABLE #output_dbinfo;
  11144. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  11145. DROP TABLE #tblIOStall;
  11146. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  11147. DROP TABLE #tmpdbs1;
  11148. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  11149. DROP TABLE #tmpdbs0;
  11150. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  11151. DROP TABLE #tblPerfCount;
  11152. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  11153. DROP TABLE tempdb.dbo.tblPerfThresholds;
  11154. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  11155. DROP TABLE #tblHypObj;
  11156. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  11157. DROP TABLE #tblIxs1;
  11158. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  11159. DROP TABLE #tblIxs2;
  11160. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  11161. DROP TABLE #tblIxs3;
  11162. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  11163. DROP TABLE #tblIxs4;
  11164. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  11165. DROP TABLE #tblIxs5;
  11166. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  11167. DROP TABLE #tblIxs6;
  11168. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  11169. DROP TABLE #tblFK;
  11170. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  11171. DROP TABLE #dbcc;
  11172. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  11173. DROP TABLE #avail_logs;
  11174. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  11175. DROP TABLE #log_info1;
  11176. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  11177. DROP TABLE #log_info2;
  11178. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  11179. DROP TABLE #tmpobjectnames;
  11180. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  11181. DROP TABLE #tmpfinalobjectnames;
  11182. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  11183. DROP TABLE #tblWaits;
  11184. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  11185. DROP TABLE #tblFinalWaits;
  11186. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  11187. DROP TABLE #tblLatches;
  11188. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  11189. DROP TABLE #tblFinalLatches;
  11190. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  11191. DROP TABLE #IndexCreation;
  11192. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  11193. DROP TABLE #IndexRedundant;
  11194. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  11195. DROP TABLE #tblBlkChains;
  11196. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  11197. DROP TABLE #tblStatsSamp;
  11198. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  11199. DROP TABLE #tblSpinlocksBefore;
  11200. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  11201. DROP TABLE #tblSpinlocksAfter;
  11202. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  11203. DROP TABLE #tblFinalSpinlocks;
  11204. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  11205. DROP TABLE #pagerepair;
  11206. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  11207. DROP TABLE #tmp_dm_io_virtual_file_stats;
  11208. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  11209. DROP TABLE #tmp_dm_exec_query_stats;
  11210. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  11211. DROP TABLE #dm_exec_query_stats;
  11212. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  11213. DROP TABLE #tblPendingIOReq;
  11214. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  11215. DROP TABLE #tblPendingIO;
  11216. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  11217. DROP TABLE #qpwarnings;
  11218. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  11219. DROP TABLE #tblStatsUpd;
  11220. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  11221. DROP TABLE #tblPerSku;
  11222. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  11223. DROP TABLE #tblColStoreIXs;
  11224. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11225. DROP TABLE #SystemHealthSessionData;
  11226. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  11227. DROP TABLE #tmpdbfiledetail;
  11228. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  11229. DROP TABLE #tblHints;
  11230. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  11231. DROP TABLE #tblTriggers;
  11232. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  11233. DROP TABLE #tmpIPS;
  11234. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  11235. DROP TABLE #tblCode;
  11236. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  11237. DROP TABLE #tblWorking;
  11238. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  11239. DROP TABLE #tmpdbs_userchoice;
  11240. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  11241. DROP TABLE #xp_cmdshell_CluNodesOutput;
  11242. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  11243. DROP TABLE #xp_cmdshell_CluOutput;
  11244. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  11245. DROP TABLE #xp_cmdshell_Nodes;
  11246. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  11247. DROP TABLE #xp_cmdshell_QFEOutput;
  11248. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  11249. DROP TABLE #xp_cmdshell_QFEFinal;
  11250. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#RegResult'))
  11251. DROP TABLE #RegResult;
  11252. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ServiceStatus'))
  11253. DROP TABLE #ServiceStatus;
  11254. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  11255. DROP TABLE #xp_cmdshell_AcctSPNoutput;
  11256. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  11257. DROP TABLE #xp_cmdshell_DupSPNoutput;
  11258. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  11259. DROP TABLE #FinalDupSPN;
  11260. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  11261. DROP TABLE #ScopedDupSPN;
  11262. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  11263. DROP TABLE #tblDRI;
  11264. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  11265. DROP TABLE #tblInMemDBs;
  11266. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  11267. DROP TABLE #tmpXIS;
  11268. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  11269. DROP TABLE #tmpXNCIS;
  11270. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  11271. DROP TABLE #tmpIPS_CI;
  11272. EXEC ('USE tempdb; IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID(''tempdb.dbo.fn_perfctr'')) DROP FUNCTION dbo.fn_perfctr')
  11273. EXEC ('USE tempdb; IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID(''tempdb.dbo.fn_createindex_allcols'')) DROP FUNCTION dbo.fn_createindex_allcols')
  11274. EXEC ('USE tempdb; IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID(''tempdb.dbo.fn_createindex_keycols'')) DROP FUNCTION dbo.fn_createindex_keycols')
  11275. EXEC ('USE tempdb; IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID(''tempdb.dbo.fn_createindex_includecols'')) DROP FUNCTION dbo.fn_createindex_includecols')
  11276. RAISERROR (N'All done!', 10, 1) WITH NOWAIT
  11277. GO