Check_BP_Servers.sql 778 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150
  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 SQL Server 2016 SP1 (Enterprise_features_usage, LPIM and IFI checks).
  374. v2.1.5.1 - 11/23/2016 - Fixed User DBs with non-default options subsection in SQL 2012.
  375. v2.1.5.2 - 2/23/2017 - Fixed conversion error in Service_Account_checks section.
  376. v2.1.5.3 - 2/26/2017 - Added SQL 2016 support for AlwaysOn_Replicas information section;
  377. Fixed conversion error when multiple TCP ports.
  378. v2.1.5.4 - 3/28/2017 - Fixed collation issues.
  379. v2.1.6 - 4/11/2017 - Changed port discovery method for SQL Server 2012 and above.
  380. v2.1.6.1 - 4/30/2017 - Enhanced wait and latches report section.
  381. PURPOSE: Checks SQL Server in scope for some of most common skewed Best Practices. Valid from SQL Server 2005 onwards.
  382. - Contains the following information:
  383. |- Uptime
  384. |- Windows Version and Architecture
  385. |- Disk space
  386. |- HA Information
  387. |- Linked servers info
  388. |- Instance info
  389. |- Resource Governor info
  390. |- Logon triggers
  391. |- Database Information
  392. |- Database file autogrows last 72h
  393. |- Database triggers
  394. |- Enterprise features usage
  395. |- Backups
  396. |- System Configuration
  397. - And performs the following checks (* means only when @ptochecks is ON):
  398. |- Processor
  399. |- Number of available Processors for this instance vs. MaxDOP setting
  400. |- Processor Affinity in NUMA architecture
  401. |- Additional Processor information
  402. |- Processor utilization rate in the last 2 hours *
  403. |- Memory
  404. |- Server Memory
  405. |- RM Task *
  406. |- Clock hands *
  407. |- Buffer Pool Consumers from Buffer Descriptors *
  408. |- Memory Allocations from Memory Clerks *
  409. |- Memory Consumers from In-Memory OLTP Engine *
  410. |- Memory Allocations from In-Memory OLTP Engine *
  411. |- OOM
  412. |- LPIM
  413. |- Pagefile
  414. |- Pagefile
  415. |- I/O
  416. |- I/O Stall subsection (wait for 5s) *
  417. |- Pending disk I/O Requests subsection (wait for a max of 5s) *
  418. |- Server
  419. |- Power plan
  420. |- NTFS block size in volumes that hold database files <> 64KB
  421. |- Disk Fragmentation Analysis (if enabled)
  422. |- Cluster Quorum Model
  423. |- Cluster QFE node equality
  424. |- Cluster NIC Binding order
  425. |- Service Accounts
  426. |- Service Accounts Status
  427. |- Service Accounts and SPN registration
  428. |- Instance
  429. |- Recommended build check
  430. |- Backups
  431. |- Global trace flags
  432. |- System configurations
  433. |- IFI
  434. |- Full Text Configurations
  435. |- Deprecated features *
  436. |- Default data collections (default trace, blackbox trace, SystemHealth xEvent session, sp_server_diagnostics xEvent session)
  437. |- Database and tempDB
  438. |- User objects in master
  439. |- DBs with collation <> master
  440. |- DBs with skewed compatibility level
  441. |- User DBs with non-default options
  442. |- DBs with Sparse files
  443. |- DBs Autogrow in percentage
  444. |- DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled)
  445. |- VLF
  446. |- Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware)
  447. |- tempDB data file configurations
  448. |- tempDB Files autogrow of equal size
  449. |- Performance
  450. |- Perf counters, Waits and Latches (wait for 90s) *
  451. |- Worker thread exhaustion *
  452. |- Blocking Chains *
  453. |- Plan use ratio *
  454. |- Hints usage *
  455. |- Cached Query Plans issues *
  456. |- Inefficient Query Plans *
  457. |- Declarative Referential Integrity - Untrusted Constraints *
  458. |- Indexes and Statistics
  459. |- Statistics update *
  460. |- Statistics sampling *
  461. |- Hypothetical objects *
  462. |- Row Index Fragmentation Analysis (if enabled) *
  463. |- CS Index Health Analysis (if enabled) *
  464. |- XTP Index Health Analysis (if enabled) *
  465. |- Duplicate or Redundant indexes *
  466. |- Unused and rarely used indexes *
  467. |- Indexes with large keys (> 900 bytes) *
  468. |- Indexes with fill factor < 80 pct *
  469. |- Disabled indexes *
  470. |- Non-unique clustered indexes *
  471. |- Clustered Indexes with GUIDs in key *
  472. |- Foreign Keys with no Index *
  473. |- Indexing per Table *
  474. |- Missing Indexes *
  475. |- Naming Convention
  476. |- Objects naming conventions
  477. |- Security
  478. |- Password check
  479. |- Maintenance and Monitoring
  480. |- SQL Agent alerts for severe errors
  481. |- DBCC CHECKDB, Direct Catalog Updates and Data Purity
  482. |- AlwaysOn/Mirroring automatic page repair
  483. |- Suspect pages
  484. |- Replication Errors
  485. |- Errorlog based checks
  486. |- System health checks
  487. DISCLAIMER:
  488. This code and information are provided "AS IS" without warranty of any kind, either expressed or implied.
  489. 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.
  490. IMPORTANT pre-requisites:
  491. - Only a sysadmin/local host admin will be able to perform all checks.
  492. - If you want to perform all checks under non-sysadmin credentials, then that login must be:
  493. Member of serveradmin server role or have the ALTER SETTINGS server permission;
  494. Member of MSDB SQLAgentOperatorRole role, or have SELECT permission on the sysalerts table in MSDB;
  495. Granted EXECUTE permissions on the following extended sprocs to run checks: sp_OACreate, sp_OADestroy, sp_OAGetErrorInfo, xp_enumerrorlogs, xp_fileexist and xp_regenumvalues;
  496. Granted EXECUTE permissions on xp_msver;
  497. Granted the VIEW SERVER STATE permission;
  498. Granted the VIEW DATABASE STATE permission;
  499. Granted EXECUTE permissions on xp_cmdshell or a xp_cmdshell proxy account should exist to run checks that access disk or OS security configurations.
  500. Member of securityadmin role, or have EXECUTE permissions on sp_readerrorlog.
  501. Otherwise some checks will be bypassed and warnings will be shown.
  502. - Powershell must be installed to run checks that access disk configurations, as well as allow execution of remote signed or unsigned scripts.
  503. */
  504. SET NOCOUNT ON;
  505. SET ANSI_WARNINGS ON;
  506. SET QUOTED_IDENTIFIER ON;
  507. SET DATEFORMAT mdy;
  508. RAISERROR (N'Starting Pre-requisites section', 10, 1) WITH NOWAIT
  509. --------------------------------------------------------------------------------------------------------------------------------
  510. -- Pre-requisites section
  511. --------------------------------------------------------------------------------------------------------------------------------
  512. DECLARE @sqlcmd NVARCHAR(max), @params NVARCHAR(500), @sqlmajorver int
  513. /*
  514. Reference: SERVERPROPERTY for sql major, minor and build versions supported after:
  515. @sqlmajorver >= 13 OR (@sqlmajorver = 12 AND @sqlbuild >= 2556 AND @sqlbuild < 4100) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427)
  516. */
  517. SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  518. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 0)
  519. BEGIN
  520. RAISERROR('[WARNING: Only a sysadmin can run ALL the checks]', 16, 1, N'sysadmin')
  521. --RETURN
  522. END;
  523. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 0)
  524. BEGIN
  525. DECLARE @pid int, @pname sysname, @msdbpid int, @masterpid int
  526. DECLARE @permstbl TABLE ([name] sysname);
  527. DECLARE @permstbl_msdb TABLE ([id] tinyint IDENTITY(1,1), [perm] tinyint)
  528. SET @params = '@msdbpid_in int'
  529. SELECT @pid = principal_id, @pname=name FROM master.sys.server_principals (NOLOCK) WHERE sid = SUSER_SID()
  530. SELECT @masterpid = principal_id FROM master.sys.database_principals (NOLOCK) WHERE sid = SUSER_SID()
  531. SELECT @msdbpid = principal_id FROM msdb.sys.database_principals (NOLOCK) WHERE sid = SUSER_SID()
  532. -- Perms 1
  533. IF (ISNULL(IS_SRVROLEMEMBER(N'serveradmin'), 0) <> 1) AND ((SELECT COUNT(l.name)
  534. FROM master.sys.server_permissions p (NOLOCK) INNER JOIN master.sys.server_principals l (NOLOCK)
  535. ON p.grantee_principal_id = l.principal_id
  536. AND p.class = 100 -- Server
  537. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  538. AND l.is_disabled = 0
  539. AND p.permission_name = 'ALTER SETTINGS'
  540. AND QUOTENAME(l.name) = QUOTENAME(@pname)) = 0)
  541. BEGIN
  542. 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')
  543. RETURN
  544. END
  545. ELSE IF (ISNULL(IS_SRVROLEMEMBER(N'serveradmin'), 0) <> 1) AND ((SELECT COUNT(l.name)
  546. FROM master.sys.server_permissions p (NOLOCK) INNER JOIN sys.server_principals l (NOLOCK)
  547. ON p.grantee_principal_id = l.principal_id
  548. AND p.class = 100 -- Server
  549. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  550. AND l.is_disabled = 0
  551. AND p.permission_name = 'VIEW SERVER STATE'
  552. AND QUOTENAME(l.name) = QUOTENAME(@pname)) = 0)
  553. BEGIN
  554. 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')
  555. RETURN
  556. END
  557. -- Perms 2
  558. INSERT INTO @permstbl
  559. SELECT a.name
  560. FROM master.sys.all_objects a (NOLOCK) INNER JOIN master.sys.database_permissions b (NOLOCK) ON a.[OBJECT_ID] = b.major_id
  561. WHERE a.type IN ('P', 'X') AND b.grantee_principal_id <>0
  562. AND b.grantee_principal_id <>2
  563. AND b.grantee_principal_id = @masterpid;
  564. INSERT INTO @permstbl_msdb ([perm])
  565. EXECUTE sp_executesql N'USE msdb; SELECT COUNT([name])
  566. FROM msdb.sys.sysusers (NOLOCK) WHERE [uid] IN (SELECT [groupuid]
  567. FROM msdb.sys.sysmembers (NOLOCK) WHERE [memberuid] = @msdbpid_in)
  568. AND [name] = ''SQLAgentOperatorRole''', @params, @msdbpid_in = @msdbpid;
  569. INSERT INTO @permstbl_msdb ([perm])
  570. EXECUTE sp_executesql N'USE msdb; SELECT COUNT(dp.grantee_principal_id)
  571. FROM msdb.sys.tables AS tbl (NOLOCK)
  572. INNER JOIN msdb.sys.database_permissions AS dp (NOLOCK) ON dp.major_id=tbl.object_id AND dp.class=1
  573. INNER JOIN msdb.sys.database_principals AS grantor_principal (NOLOCK) ON grantor_principal.principal_id = dp.grantor_principal_id
  574. INNER JOIN msdb.sys.database_principals AS grantee_principal (NOLOCK) ON grantee_principal.principal_id = dp.grantee_principal_id
  575. WHERE dp.state = ''G''
  576. AND dp.grantee_principal_id = @msdbpid_in
  577. AND dp.type = ''SL''', @params, @msdbpid_in = @msdbpid;
  578. IF (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 1) = 0 AND (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 2) = 0
  579. BEGIN
  580. 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')
  581. --RETURN
  582. END
  583. 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)
  584. BEGIN
  585. 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')
  586. --RETURN
  587. END
  588. 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
  589. BEGIN
  590. 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')
  591. --RETURN
  592. END
  593. ELSE IF (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') = 0 OR
  594. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') = 0 OR
  595. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') = 0 OR
  596. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') = 0 OR
  597. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') = 0 OR
  598. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 0 OR
  599. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 0 OR
  600. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_servicecontrol') = 0
  601. BEGIN
  602. 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')
  603. --RETURN
  604. END
  605. ELSE IF (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_msver') = 0 AND @sqlmajorver < 11
  606. BEGIN
  607. RAISERROR('[WARNING: Must be granted EXECUTE permissions on xp_msver to run full scope of checks]', 16, 1, N'extended_sprocs')
  608. --RETURN
  609. END
  610. END;
  611. -- Declare Global Variables
  612. DECLARE @UpTime VARCHAR(12),@StartDate DATETIME
  613. DECLARE @agt smallint, @ole smallint, @sao smallint, @xcmd smallint
  614. DECLARE @ErrorSeverity int, @ErrorState int, @ErrorMessage NVARCHAR(4000)
  615. DECLARE @CMD NVARCHAR(4000)
  616. DECLARE @path NVARCHAR(2048)
  617. DECLARE @sqlminorver int, @sqlbuild int, @clustered bit, @winver VARCHAR(5), @server VARCHAR(128), @instancename NVARCHAR(128), @arch smallint, @winsp VARCHAR(25), @SystemManufacturer VARCHAR(128)
  618. DECLARE @existout int, @FSO int, @FS int, @OLEResult int, @FileID int
  619. DECLARE @FileName VARCHAR(200), @Text1 VARCHAR(2000), @CMD2 VARCHAR(100)
  620. DECLARE @src VARCHAR(255), @desc VARCHAR(255), @psavail VARCHAR(20), @psver tinyint
  621. DECLARE @dbid int, @dbname VARCHAR(1000)
  622. SELECT @instancename = CONVERT(VARCHAR(128),SERVERPROPERTY('InstanceName'))
  623. SELECT @server = RTRIM(CONVERT(VARCHAR(128), SERVERPROPERTY('MachineName')))
  624. --SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  625. SELECT @sqlminorver = CONVERT(int, (@@microsoftversion / 0x10000) & 0xff);
  626. SELECT @sqlbuild = CONVERT(int, @@microsoftversion & 0xffff);
  627. SELECT @clustered = CONVERT(bit,ISNULL(SERVERPROPERTY('IsClustered'),0))
  628. -- Test Powershell policy
  629. IF @allow_xpcmdshell = 1
  630. BEGIN
  631. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  632. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  633. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  634. AND (SELECT COUNT(l.name)
  635. FROM sys.server_permissions p JOIN sys.server_principals l
  636. ON p.grantee_principal_id = l.principal_id
  637. AND p.class = 100 -- Server
  638. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  639. AND l.is_disabled = 0
  640. AND p.permission_name = 'ALTER SETTINGS'
  641. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  642. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  643. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  644. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0)))
  645. BEGIN
  646. DECLARE @pstbl_avail TABLE ([KeyExist] int)
  647. BEGIN TRY
  648. INSERT INTO @pstbl_avail
  649. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\PowerShell\1' -- check if Powershell is installed
  650. END TRY
  651. BEGIN CATCH
  652. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  653. SELECT @ErrorMessage = 'Could not determine if Powershell is installed - Error raised in TRY block. ' + ERROR_MESSAGE()
  654. RAISERROR (@ErrorMessage, 16, 1);
  655. END CATCH
  656. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  657. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  658. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  659. RAISERROR ('|-Configuration options set for Powershell enablement verification', 10, 1) WITH NOWAIT
  660. IF @sao = 0
  661. BEGIN
  662. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  663. END
  664. IF @xcmd = 0
  665. BEGIN
  666. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  667. END
  668. IF @ole = 0
  669. BEGIN
  670. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  671. END
  672. IF (SELECT [KeyExist] FROM @pstbl_avail) = 1
  673. BEGIN
  674. DECLARE @psavail_output TABLE ([PS_OUTPUT] VARCHAR(2048));
  675. INSERT INTO @psavail_output
  676. EXEC master.dbo.xp_cmdshell N'%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Get-ExecutionPolicy"'
  677. SELECT @psavail = [PS_OUTPUT] FROM @psavail_output WHERE [PS_OUTPUT] IS NOT NULL;
  678. END
  679. ELSE
  680. BEGIN
  681. RAISERROR (' [WARNING: Powershell is not installed. Install WinRM to proceed with PS based checks]',16,1);
  682. END
  683. IF (@psavail IS NOT NULL AND @psavail NOT IN ('RemoteSigned','Unrestricted'))
  684. RAISERROR (' [WARNING: Execution of Powershell scripts is disabled on this system.
  685. To change the execution policy, type the following command in Powershell console: Set-ExecutionPolicy RemoteSigned
  686. 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:
  687. Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  688. AllSigned - Only scripts signed by a trusted publisher can be run.
  689. RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  690. |- REQUIRED by BP Check
  691. Unrestricted - No restrictions; all Windows PowerShell scripts can be run.]',16,1);
  692. IF (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  693. BEGIN
  694. RAISERROR ('|- [INFORMATION: Powershell is installed and enabled for script execution]', 10, 1) WITH NOWAIT
  695. DECLARE @psver_output TABLE ([PS_OUTPUT] VARCHAR(1024));
  696. INSERT INTO @psver_output
  697. EXEC master.dbo.xp_cmdshell N'%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Get-Host | Format-Table -Property Version"'
  698. -- Gets PS version, as commands issued to PS v1 do not support -File
  699. SELECT @psver = ISNULL(LEFT([PS_OUTPUT],1),2) FROM @psver_output WHERE [PS_OUTPUT] IS NOT NULL AND ISNUMERIC(LEFT([PS_OUTPUT],1)) = 1;
  700. SET @ErrorMessage = '|- [INFORMATION: Installed Powershell is version ' + CONVERT(CHAR(1), @psver) + ']'
  701. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  702. END;
  703. IF @xcmd = 0
  704. BEGIN
  705. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  706. END
  707. IF @ole = 0
  708. BEGIN
  709. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  710. END
  711. IF @sao = 0
  712. BEGIN
  713. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  714. END;
  715. END
  716. ELSE
  717. BEGIN
  718. RAISERROR(' [WARNING: Missing permissions for Powershell enablement verification]', 16, 1, N'sysadmin')
  719. --RETURN
  720. END
  721. END;
  722. --------------------------------------------------------------------------------------------------------------------------------
  723. -- Information section
  724. --------------------------------------------------------------------------------------------------------------------------------
  725. RAISERROR (N'Starting Information section', 10, 1) WITH NOWAIT
  726. --------------------------------------------------------------------------------------------------------------------------------
  727. -- Uptime subsection
  728. --------------------------------------------------------------------------------------------------------------------------------
  729. RAISERROR (N'|-Starting Uptime', 10, 1) WITH NOWAIT
  730. IF @sqlmajorver < 10
  731. BEGIN
  732. SET @sqlcmd = N'SELECT @UpTimeOUT = DATEDIFF(mi, login_time, GETDATE()), @StartDateOUT = login_time FROM master..sysprocesses (NOLOCK) WHERE spid = 1';
  733. END
  734. ELSE
  735. BEGIN
  736. SET @sqlcmd = N'SELECT @UpTimeOUT = DATEDIFF(mi,sqlserver_start_time,GETDATE()), @StartDateOUT = sqlserver_start_time FROM sys.dm_os_sys_info (NOLOCK)';
  737. END
  738. SET @params = N'@UpTimeOUT VARCHAR(12) OUTPUT, @StartDateOUT DATETIME OUTPUT';
  739. EXECUTE sp_executesql @sqlcmd, @params, @UpTimeOUT=@UpTime OUTPUT, @StartDateOUT=@StartDate OUTPUT;
  740. 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
  741. --------------------------------------------------------------------------------------------------------------------------------
  742. -- Windows Version and Architecture subsection
  743. --------------------------------------------------------------------------------------------------------------------------------
  744. RAISERROR (N'|-Starting Windows Version and Architecture', 10, 1) WITH NOWAIT
  745. IF @sqlmajorver >= 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  746. BEGIN
  747. 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)';
  748. SET @params = N'@winverOUT VARCHAR(5) OUTPUT, @winspOUT VARCHAR(25) OUTPUT, @archOUT smallint OUTPUT';
  749. EXECUTE sp_executesql @sqlcmd, @params, @winverOUT=@winver OUTPUT, @winspOUT=@winsp OUTPUT, @archOUT=@arch OUTPUT;
  750. END
  751. ELSE
  752. BEGIN
  753. BEGIN TRY
  754. DECLARE @str VARCHAR(500), @str2 VARCHAR(500), @str3 VARCHAR(500)
  755. DECLARE @sysinfo TABLE (id int,
  756. [Name] NVARCHAR(256),
  757. Internal_Value bigint,
  758. Character_Value NVARCHAR(256));
  759. INSERT INTO @sysinfo
  760. EXEC xp_msver;
  761. 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
  762. FROM @sysinfo
  763. WHERE [Name] LIKE 'WindowsVersion%';
  764. SELECT @arch = CASE WHEN RTRIM(Character_Value) LIKE '%x64%' OR RTRIM(Character_Value) LIKE '%AMD64%' THEN 64
  765. WHEN RTRIM(Character_Value) LIKE '%x86%' OR RTRIM(Character_Value) LIKE '%32%' THEN 32
  766. WHEN RTRIM(Character_Value) LIKE '%IA64%' THEN 128 END
  767. FROM @sysinfo
  768. WHERE [Name] LIKE 'Platform%';
  769. SET @str = (SELECT @@VERSION)
  770. SELECT @str2 = RIGHT(@str, LEN(@str)-CHARINDEX('Windows',@str) + 1)
  771. SELECT @str3 = RIGHT(@str2, LEN(@str2)-CHARINDEX(': ',@str2))
  772. SELECT @winsp = LTRIM(LEFT(@str3, CHARINDEX(')',@str3) -1))
  773. END TRY
  774. BEGIN CATCH
  775. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  776. SELECT @ErrorMessage = 'Windows Version and Architecture subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  777. RAISERROR (@ErrorMessage, 16, 1);
  778. END CATCH
  779. END;
  780. DECLARE @machineinfo TABLE ([Value] NVARCHAR(256), [Data] NVARCHAR(256))
  781. INSERT INTO @machineinfo
  782. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemManufacturer';
  783. INSERT INTO @machineinfo
  784. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemProductName';
  785. INSERT INTO @machineinfo
  786. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemFamily';
  787. INSERT INTO @machineinfo
  788. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSVendor';
  789. INSERT INTO @machineinfo
  790. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSVersion';
  791. INSERT INTO @machineinfo
  792. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSReleaseDate';
  793. INSERT INTO @machineinfo
  794. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\CentralProcessor\0','ProcessorNameString';
  795. SELECT @SystemManufacturer = [Data] FROM @machineinfo WHERE [Value] = 'SystemManufacturer';
  796. SELECT 'Information' AS [Category], 'Machine' AS [Information],
  797. CASE @winver WHEN '5.2' THEN 'XP/WS2003'
  798. WHEN '6.0' THEN 'Vista/WS2008'
  799. WHEN '6.1' THEN 'W7/WS2008R2'
  800. WHEN '6.2' THEN 'W8/WS2012'
  801. WHEN '6.3' THEN 'W8.1/WS2012R2'
  802. WHEN '10.0' THEN 'W10/WS2016'
  803. END AS [Windows_Version],
  804. @winsp AS [Service_Pack_Level],
  805. @arch AS [Architecture],
  806. SERVERPROPERTY('MachineName') AS [Machine_Name],
  807. SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [NetBIOS_Name],
  808. @SystemManufacturer AS [System_Manufacturer],
  809. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'SystemFamily') AS [System_Family],
  810. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'SystemProductName') AS [System_ProductName],
  811. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSVendor') AS [BIOS_Vendor],
  812. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSVersion') AS [BIOS_Version],
  813. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSReleaseDate') AS [BIOS_Release_Date],
  814. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'ProcessorNameString') AS [Processor_Name];
  815. --------------------------------------------------------------------------------------------------------------------------------
  816. -- Disk space subsection
  817. --------------------------------------------------------------------------------------------------------------------------------
  818. RAISERROR (N'|-Starting Disk space', 10, 1) WITH NOWAIT
  819. SELECT DISTINCT 'Information' AS [Category], 'Disk_Space' AS [Information], vs.logical_volume_name,
  820. vs.volume_mount_point, vs.file_system_type, CONVERT(int,vs.total_bytes/1048576.0) AS TotalSpace_MB,
  821. CONVERT(int,vs.available_bytes/1048576.0) AS FreeSpace_MB, vs.is_compressed
  822. FROM sys.master_files mf
  823. CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) vs
  824. ORDER BY FreeSpace_MB ASC;
  825. --------------------------------------------------------------------------------------------------------------------------------
  826. -- HA Information subsection
  827. --------------------------------------------------------------------------------------------------------------------------------
  828. RAISERROR (N'|-Starting HA Information', 10, 1) WITH NOWAIT
  829. IF @clustered = 1
  830. BEGIN
  831. IF @sqlmajorver < 11
  832. BEGIN
  833. EXEC ('SELECT ''Information'' AS [Category], ''Cluster'' AS [Information], NodeName AS node_name FROM sys.dm_os_cluster_nodes (NOLOCK)')
  834. END
  835. ELSE
  836. BEGIN
  837. EXEC ('SELECT ''Information'' AS [Category], ''Cluster'' AS [Information], NodeName AS node_name, status_description, is_current_owner FROM sys.dm_os_cluster_nodes (NOLOCK)')
  838. END
  839. SELECT 'Information' AS [Category], 'Cluster' AS [Information], DriveName AS cluster_shared_drives FROM sys.dm_io_cluster_shared_drives (NOLOCK)
  840. END
  841. ELSE
  842. BEGIN
  843. SELECT 'Information' AS [Category], 'Cluster' AS [Information], 'NOT_CLUSTERED' AS [Status]
  844. END;
  845. IF @sqlmajorver > 10
  846. BEGIN
  847. DECLARE @IsHadrEnabled tinyint, @HadrManagerStatus tinyint
  848. SELECT @IsHadrEnabled = CONVERT(tinyint, SERVERPROPERTY('IsHadrEnabled'))
  849. SELECT @HadrManagerStatus = CONVERT(tinyint, SERVERPROPERTY('HadrManagerStatus'))
  850. SELECT 'Information' AS [Category], 'AlwaysOn_AG' AS [Information],
  851. CASE @IsHadrEnabled WHEN 0 THEN 'Disabled'
  852. WHEN 1 THEN 'Enabled' END AS [AlwaysOn_Availability_Groups],
  853. CASE WHEN @IsHadrEnabled = 1 THEN
  854. CASE @HadrManagerStatus WHEN 0 THEN '[Not started, pending communication]'
  855. WHEN 1 THEN '[Started and running]'
  856. WHEN 2 THEN '[Not started and failed]'
  857. END
  858. END AS [Status];
  859. IF @IsHadrEnabled = 1
  860. BEGIN
  861. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster)
  862. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster' AS [Information], cluster_name, quorum_type_desc, quorum_state_desc
  863. FROM sys.dm_hadr_cluster;
  864. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster_members)
  865. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster_Members' AS [Information], member_name, member_type_desc, member_state_desc, number_of_quorum_votes
  866. FROM sys.dm_hadr_cluster_members;
  867. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster_networks)
  868. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster_Networks' AS [Information], member_name, network_subnet_ip, network_subnet_ipv4_mask, is_public, is_ipv4
  869. FROM sys.dm_hadr_cluster_networks;
  870. END;
  871. IF @ptochecks = 1 AND @IsHadrEnabled = 1
  872. BEGIN
  873. -- Note: If low_water_mark_for_ghosts number is not increasing over time, it implies that ghost cleanup might not happen.
  874. SET @sqlcmd = 'SELECT ''Information'' AS [Category], ''AlwaysOn_Replicas'' AS [Information], database_id, group_id, replica_id, group_database_id, is_local, synchronization_state_desc,
  875. is_commit_participant, synchronization_health_desc, database_state_desc, is_suspended, suspend_reason_desc, last_sent_time, last_received_time, last_hardened_time,
  876. last_redone_time, log_send_queue_size, log_send_rate, redo_queue_size, redo_rate, filestream_send_rate, last_commit_time,
  877. low_water_mark_for_ghosts' + CASE WHEN @sqlmajorver > 12 THEN ', secondary_lag_seconds' ELSE '' END + '
  878. FROM sys.dm_hadr_database_replica_states'
  879. EXECUTE sp_executesql @sqlcmd
  880. SELECT 'Information' AS [Category], 'AlwaysOn_Replica_Cluster' AS [Information], replica_id, group_database_id, database_name, is_failover_ready, is_pending_secondary_suspend,
  881. is_database_joined, recovery_lsn, truncation_lsn
  882. FROM sys.dm_hadr_database_replica_cluster_states;
  883. END
  884. END;
  885. --------------------------------------------------------------------------------------------------------------------------------
  886. -- Linked servers info subsection
  887. --------------------------------------------------------------------------------------------------------------------------------
  888. RAISERROR (N'|-Starting Linked servers info', 10, 1) WITH NOWAIT
  889. 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
  890. BEGIN
  891. SET @sqlcmd = 'SELECT ''Information'' AS [Category], ''Linked_servers'' AS [Information], s.name, s.product,
  892. s.provider, s.data_source, s.location, s.provider_string, s.catalog, s.connect_timeout,
  893. s.query_timeout, s.is_linked, s.is_remote_login_enabled, s.is_rpc_out_enabled,
  894. s.is_data_access_enabled, s.is_collation_compatible, s.uses_remote_collation, s.collation_name,
  895. s.lazy_schema_validation, s.is_system, s.is_publisher, s.is_subscriber, s.is_distributor,
  896. s.is_nonsql_subscriber' + CASE WHEN @sqlmajorver > 9 THEN ', s.is_remote_proc_transaction_promotion_enabled' ELSE '' END + ',
  897. s.modify_date, CASE WHEN l.local_principal_id = 0 THEN ''local or wildcard'' ELSE p.name END AS [local_principal],
  898. CASE WHEN l.uses_self_credential = 0 THEN ''use own credentials'' ELSE ''use supplied username and pwd'' END AS uses_self_credential,
  899. l.remote_name, l.modify_date AS [linked_login_modify_date]
  900. FROM sys.servers AS s (NOLOCK)
  901. INNER JOIN sys.linked_logins AS l (NOLOCK) ON s.server_id = l.server_id
  902. INNER JOIN sys.server_principals AS p (NOLOCK) ON p.principal_id = l.local_principal_id
  903. WHERE s.is_linked = 1'
  904. EXECUTE sp_executesql @sqlcmd
  905. END
  906. ELSE
  907. BEGIN
  908. SELECT 'Information' AS [Category], 'Linked_servers' AS [Information], '[None]' AS [Status]
  909. END;
  910. --------------------------------------------------------------------------------------------------------------------------------
  911. -- Instance info subsection
  912. --------------------------------------------------------------------------------------------------------------------------------
  913. RAISERROR (N'|-Starting Instance info', 10, 1) WITH NOWAIT
  914. DECLARE @port VARCHAR(15), @replication int, @RegKey NVARCHAR(255), @cpuaffin VARCHAR(255), @cpucount int, @numa int
  915. DECLARE @i int, @cpuaffin_fixed VARCHAR(300)
  916. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild < 2500)
  917. BEGIN
  918. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  919. BEGIN
  920. BEGIN TRY
  921. SELECT @RegKey = CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) IS NULL THEN N'Software\Microsoft\MSSQLServer\MSSQLServer\SuperSocketNetLib\Tcp'
  922. ELSE N'Software\Microsoft\Microsoft SQL Server\' + CAST(SERVERPROPERTY('InstanceName') AS NVARCHAR(128)) + N'\MSSQLServer\SuperSocketNetLib\Tcp' END
  923. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'TcpPort', @port OUTPUT, NO_OUTPUT
  924. END TRY
  925. BEGIN CATCH
  926. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  927. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  928. RAISERROR (@ErrorMessage, 16, 1);
  929. END CATCH
  930. END
  931. ELSE
  932. BEGIN
  933. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing TCP port check]', 16, 1, N'sysadmin')
  934. --RETURN
  935. END
  936. END
  937. ELSE
  938. BEGIN
  939. BEGIN TRY
  940. /*
  941. SET @sqlcmd = N'SELECT @portOUT = MAX(CONVERT(VARCHAR(15),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;';
  942. SET @params = N'@portOUT VARCHAR(15) OUTPUT';
  943. EXECUTE sp_executesql @sqlcmd, @params, @portOUT = @port OUTPUT;
  944. IF @port IS NULL
  945. BEGIN
  946. SET @sqlcmd = N'SELECT @portOUT = CONVERT(VARCHAR(15),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;';
  947. SET @params = N'@portOUT VARCHAR(15) OUTPUT';
  948. EXECUTE sp_executesql @sqlcmd, @params, @portOUT = @port OUTPUT;
  949. END
  950. */
  951. SET @sqlcmd = N'SELECT @portOUT = MAX(CONVERT(VARCHAR(15),port)) FROM sys.dm_tcp_listener_states WHERE is_ipv4 = 1 AND [type] = 0 AND ip_address <> ''127.0.0.1'';';
  952. SET @params = N'@portOUT VARCHAR(15) OUTPUT';
  953. EXECUTE sp_executesql @sqlcmd, @params, @portOUT = @port OUTPUT;
  954. IF @port IS NULL
  955. BEGIN
  956. SET @sqlcmd = N'SELECT @portOUT = MAX(CONVERT(VARCHAR(15),port)) FROM sys.dm_tcp_listener_states WHERE is_ipv4 = 0 AND [type] = 0 AND ip_address <> ''127.0.0.1'';';
  957. SET @params = N'@portOUT VARCHAR(15) OUTPUT';
  958. EXECUTE sp_executesql @sqlcmd, @params, @portOUT = @port OUTPUT;
  959. END
  960. END TRY
  961. BEGIN CATCH
  962. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  963. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  964. RAISERROR (@ErrorMessage, 16, 1);
  965. END CATCH
  966. END
  967. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 1)
  968. BEGIN
  969. BEGIN TRY
  970. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Replication', N'IsInstalled', @replication OUTPUT, NO_OUTPUT
  971. END TRY
  972. BEGIN CATCH
  973. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  974. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  975. RAISERROR (@ErrorMessage, 16, 1);
  976. END CATCH
  977. END
  978. ELSE
  979. BEGIN
  980. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing replication check]', 16, 1, N'sysadmin')
  981. --RETURN
  982. END
  983. SELECT @cpucount = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64
  984. SELECT @numa = COUNT(DISTINCT parent_node_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64;
  985. ;WITH bits AS
  986. (SELECT 7 AS N, 128 AS E UNION ALL SELECT 6, 64 UNION ALL
  987. SELECT 5, 32 UNION ALL SELECT 4, 16 UNION ALL SELECT 3, 8 UNION ALL
  988. SELECT 2, 4 UNION ALL SELECT 1, 2 UNION ALL SELECT 0, 1),
  989. bytes AS
  990. (SELECT 1 M UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
  991. SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL
  992. SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9)
  993. -- CPU Affinity is shown highest to lowest CPU ID
  994. SELECT @cpuaffin = CASE WHEN [value] = 0 THEN REPLICATE('1', @cpucount)
  995. ELSE RIGHT((SELECT ((CONVERT(tinyint, SUBSTRING(CONVERT(binary(9), [value]), M, 1)) & E) / E) AS [text()]
  996. FROM bits CROSS JOIN bytes
  997. ORDER BY M, N DESC
  998. FOR XML PATH('')), @cpucount) END
  999. FROM sys.configurations (NOLOCK)
  1000. WHERE name = 'affinity mask';
  1001. SET @cpuaffin_fixed = @cpuaffin
  1002. IF @numa > 1
  1003. BEGIN
  1004. -- format binary mask by node for better reading
  1005. SET @i = @cpucount/@numa + 1
  1006. WHILE @i <= @cpucount
  1007. BEGIN
  1008. SELECT @cpuaffin_fixed = STUFF(@cpuaffin_fixed, @i, 1, '_' + SUBSTRING(@cpuaffin, @i, 1))
  1009. SET @i = @i + @cpucount/@numa + 1
  1010. END
  1011. END
  1012. SELECT 'Information' AS [Category], 'Instance' AS [Information],
  1013. (CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) IS NULL THEN 'DEFAULT_INSTANCE'
  1014. ELSE CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) END) AS Instance_Name,
  1015. (CASE WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'CLUSTERED'
  1016. WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'NOT_CLUSTERED'
  1017. ELSE 'INVALID INPUT/ERROR' END) AS Failover_Clustered,
  1018. /*The version of SQL Server instance in the form: major.minor.build*/
  1019. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductVersion')) AS Product_Version,
  1020. /*Level of the version of SQL Server Instance*/
  1021. 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
  1022. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductBuildType'))
  1023. ELSE 'NA' END AS Product_Build_Type,
  1024. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductLevel')) AS Product_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('ProductUpdateLevel'))
  1027. ELSE 'NA' END AS Product_Update_Level,
  1028. 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
  1029. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductUpdateReference'))
  1030. ELSE 'NA' END AS Product_Update_Ref_KB,
  1031. CONVERT(VARCHAR(128), SERVERPROPERTY('Edition')) AS Edition,
  1032. CONVERT(VARCHAR(128), SERVERPROPERTY('MachineName')) AS Machine_Name,
  1033. RTRIM(@port) AS TCP_Port,
  1034. @@SERVICENAME AS Service_Name,
  1035. /*To identify which sqlservr.exe belongs to this instance*/
  1036. SERVERPROPERTY('ProcessID') AS Process_ID,
  1037. CONVERT(VARCHAR(128), SERVERPROPERTY('ServerName')) AS Server_Name,
  1038. @cpuaffin_fixed AS Affinity_Mask_Bitmask,
  1039. CONVERT(VARCHAR(128), SERVERPROPERTY('Collation')) AS [Server_Collation],
  1040. (CASE WHEN @replication = 1 THEN 'Installed'
  1041. WHEN @replication = 0 THEN 'Not_Installed'
  1042. ELSE 'INVALID INPUT/ERROR' END) AS Replication_Components_Installation,
  1043. (CASE WHEN SERVERPROPERTY('IsFullTextInstalled') = 1 THEN 'Installed'
  1044. WHEN SERVERPROPERTY('IsFulltextInstalled') = 0 THEN 'Not_Installed'
  1045. ELSE 'INVALID INPUT/ERROR' END) AS Full_Text_Installation,
  1046. (CASE WHEN SERVERPROPERTY('IsIntegratedSecurityOnly') = 1 THEN 'Integrated_Security'
  1047. WHEN SERVERPROPERTY('IsIntegratedSecurityOnly') = 0 THEN 'SQL_Server_Security'
  1048. ELSE 'INVALID INPUT/ERROR' END) AS [Security],
  1049. (CASE WHEN SERVERPROPERTY('IsSingleUser') = 1 THEN 'Single_User'
  1050. WHEN SERVERPROPERTY('IsSingleUser') = 0 THEN 'Multi_User'
  1051. ELSE 'INVALID INPUT/ERROR' END) AS [Single_User],
  1052. (CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('LicenseType')) = 'PER_SEAT' THEN 'Per_Seat_Mode'
  1053. WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('LicenseType')) = 'PER_PROCESSOR' THEN 'Per_Processor_Mode'
  1054. ELSE 'Disabled' END) AS License_Type, -- From SQL Server 2008R2 always returns DISABLED.
  1055. CONVERT(NVARCHAR(128), SERVERPROPERTY('BuildClrVersion')) AS CLR_Version,
  1056. CASE WHEN @sqlmajorver >= 10 THEN
  1057. CASE WHEN SERVERPROPERTY('FilestreamConfiguredLevel') = 0 THEN 'Disabled'
  1058. WHEN SERVERPROPERTY('FilestreamConfiguredLevel') = 1 THEN 'Enabled_for_TSQL'
  1059. ELSE 'Enabled for TSQL and Win32' END
  1060. ELSE 'Not compatible' END AS Filestream_Configured_Level,
  1061. CASE WHEN @sqlmajorver >= 10 THEN
  1062. CASE WHEN SERVERPROPERTY('FilestreamEffectiveLevel') = 0 THEN 'Disabled'
  1063. WHEN SERVERPROPERTY('FilestreamEffectiveLevel') = 1 THEN 'Enabled_for_TSQL'
  1064. ELSE 'Enabled for TSQL and Win32' END
  1065. ELSE 'Not compatible' END AS Filestream_Effective_Level,
  1066. CASE WHEN @sqlmajorver >= 10 THEN
  1067. SERVERPROPERTY('FilestreamShareName')
  1068. ELSE 'Not compatible' END AS Filestream_Share_Name,
  1069. CASE WHEN @sqlmajorver >= 12 THEN
  1070. SERVERPROPERTY('IsXTPSupported')
  1071. ELSE 'Not compatible' END AS XTP_Compatible,
  1072. CASE WHEN @sqlmajorver >= 13 THEN
  1073. SERVERPROPERTY('IsPolybaseInstalled')
  1074. ELSE 'Not compatible' END AS Polybase_Installed,
  1075. CASE WHEN @sqlmajorver >= 13 THEN
  1076. SERVERPROPERTY('IsAdvancedAnalyticsInstalled')
  1077. ELSE 'Not compatible' END AS R_Services_Installed;
  1078. --------------------------------------------------------------------------------------------------------------------------------
  1079. -- Buffer Pool Extension info subsection
  1080. --------------------------------------------------------------------------------------------------------------------------------
  1081. RAISERROR (N'|-Starting Buffer Pool Extension info', 10, 1) WITH NOWAIT
  1082. IF @sqlmajorver > 11
  1083. BEGIN
  1084. SELECT 'Information' AS [Category], 'BP_Extension' AS [Information],
  1085. CASE WHEN state = 0 THEN 'BP_Extension_Disabled'
  1086. WHEN state = 1 THEN 'BP_Extension_is_Disabling'
  1087. WHEN state = 3 THEN 'BP_Extension_is_Enabling'
  1088. WHEN state = 5 THEN 'BP_Extension_Enabled'
  1089. END AS state,
  1090. [path], current_size_in_kb
  1091. FROM sys.dm_os_buffer_pool_extension_configuration
  1092. END
  1093. ELSE
  1094. BEGIN
  1095. SELECT 'Information' AS [Category], 'BP_Extension' AS [Information], '[NA]' AS state
  1096. END;
  1097. --------------------------------------------------------------------------------------------------------------------------------
  1098. -- Resource Governor info subsection
  1099. --------------------------------------------------------------------------------------------------------------------------------
  1100. RAISERROR (N'|-Starting Resource Governor info', 10, 1) WITH NOWAIT
  1101. IF @sqlmajorver > 9
  1102. BEGIN
  1103. 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
  1104. FROM sys.dm_resource_governor_configuration
  1105. 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,
  1106. 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,
  1107. 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 + '
  1108. 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
  1109. EXECUTE sp_executesql @sqlcmd
  1110. 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,
  1111. 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,
  1112. total_lock_wait_time_ms, total_query_optimization_count, total_suboptimal_plan_generation_count, total_reduced_memgrant_count, max_request_grant_memory_kb,
  1113. active_parallel_thread_count, importance, request_max_memory_grant_percent, request_max_cpu_time_sec, request_memory_grant_timeout_sec,
  1114. group_max_requests, max_dop' + CASE WHEN @sqlmajorver > 10 THEN ', effective_max_dop' ELSE '' END + '
  1115. FROM sys.dm_resource_governor_workload_groups'
  1116. EXECUTE sp_executesql @sqlcmd
  1117. END;
  1118. --------------------------------------------------------------------------------------------------------------------------------
  1119. -- Logon triggers subsection
  1120. --------------------------------------------------------------------------------------------------------------------------------
  1121. RAISERROR (N'|-Starting Logon triggers', 10, 1) WITH NOWAIT
  1122. IF (SELECT COUNT([name]) FROM sys.server_triggers WHERE is_disabled = 0 AND is_ms_shipped = 0) > 0
  1123. BEGIN
  1124. SELECT 'Information' AS [Category], 'Logon_Triggers' AS [Information], name AS [Trigger_Name], type_desc AS [Trigger_Type],create_date, modify_date
  1125. FROM sys.server_triggers WHERE is_disabled = 0 AND is_ms_shipped = 0
  1126. ORDER BY name;
  1127. END
  1128. ELSE
  1129. BEGIN
  1130. SELECT 'Information' AS [Category], 'Logon_Triggers' AS [Information], '[NA]' AS [Comment]
  1131. END;
  1132. --------------------------------------------------------------------------------------------------------------------------------
  1133. -- Database Information subsection
  1134. --------------------------------------------------------------------------------------------------------------------------------
  1135. RAISERROR (N'|-Starting Database Information', 10, 1) WITH NOWAIT
  1136. RAISERROR (N' |-Building DB list', 10, 1) WITH NOWAIT
  1137. DECLARE @curdbname VARCHAR(1000), @curdbid int, @currole tinyint, @cursecondary_role_allow_connections tinyint, @state tinyint
  1138. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  1139. DROP TABLE #tmpdbs0;
  1140. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  1141. 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);
  1142. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  1143. DROP TABLE #tmpdbfiledetail;
  1144. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  1145. 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)
  1146. IF @sqlmajorver < 11
  1147. BEGIN
  1148. INSERT INTO #tmpdbs0 ([dbid], [dbname], [compatibility_level], is_read_only, [state], is_distributor, [role], [secondary_role_allow_connections], [isdone])
  1149. SELECT database_id, name, [compatibility_level], is_read_only, [state], is_distributor, 1, 1, 0 FROM master.sys.databases (NOLOCK)
  1150. END;
  1151. IF @sqlmajorver > 10
  1152. BEGIN
  1153. 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])
  1154. 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
  1155. FROM master.sys.databases sd (NOLOCK)
  1156. LEFT JOIN sys.dm_hadr_database_replica_states d ON sd.database_id = d.database_id
  1157. LEFT JOIN sys.availability_replicas ar ON d.group_id = ar.group_id AND d.replica_id = ar.replica_id
  1158. LEFT JOIN sys.dm_hadr_availability_replica_states ars ON d.group_id = ars.group_id AND d.replica_id = ars.replica_id
  1159. LEFT JOIN sys.dm_hadr_database_replica_cluster_states rcs ON rcs.database_name = sd.name AND rcs.replica_id = ar.replica_id
  1160. 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;
  1161. END;
  1162. /* Validate if database scope is set */
  1163. IF @dbScope IS NOT NULL AND ISNUMERIC(@dbScope) <> 1 AND @dbScope NOT LIKE '%,%'
  1164. BEGIN
  1165. 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;
  1166. RETURN
  1167. END;
  1168. RAISERROR (N' |-Applying specific database scope list, if any', 10, 1) WITH NOWAIT
  1169. IF @dbScope IS NOT NULL
  1170. BEGIN
  1171. SELECT @sqlcmd = 'DELETE FROM #tmpdbs0 WHERE [dbid] > 4 AND [dbid] NOT IN (' + REPLACE(@dbScope,' ','') + ')'
  1172. EXEC sp_executesql @sqlcmd;
  1173. END;
  1174. IF @sqlmajorver < 11
  1175. BEGIN
  1176. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1177. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1178. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1179. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1180. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1181. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1182. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
  1183. db.is_auto_update_stats_async_on, db.is_parameterization_forced,
  1184. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1185. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on, ''NA'' AS [is_indirect_checkpoint_on],
  1186. db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1187. FROM master.sys.databases AS db (NOLOCK)
  1188. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1189. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1190. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1191. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1192. 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 + '
  1193. ORDER BY [Database_Name]
  1194. OPTION (RECOMPILE)'
  1195. END
  1196. ELSE IF @sqlmajorver = 11
  1197. BEGIN
  1198. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1199. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1200. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1201. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1202. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1203. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1204. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
  1205. db.is_auto_update_stats_async_on, db.is_parameterization_forced,
  1206. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1207. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1208. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1209. db.target_recovery_time_in_seconds, db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1210. FROM master.sys.databases AS db (NOLOCK)
  1211. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1212. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1213. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1214. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1215. 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 + '
  1216. ORDER BY [Database_Name]
  1217. OPTION (RECOMPILE)'
  1218. END
  1219. ELSE IF @sqlmajorver = 12
  1220. BEGIN
  1221. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1222. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1223. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1224. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1225. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1226. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1227. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_create_stats_incremental_on,
  1228. db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.delayed_durability_desc AS [delayed_durability_status],
  1229. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1230. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1231. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1232. db.target_recovery_time_in_seconds, db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1233. FROM master.sys.databases AS db (NOLOCK)
  1234. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1235. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1236. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1237. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1238. 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 + '
  1239. ORDER BY [Database_Name]
  1240. OPTION (RECOMPILE)'
  1241. END
  1242. ELSE IF @sqlmajorver >= 13
  1243. BEGIN
  1244. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1245. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1246. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1247. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1248. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1249. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1250. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_create_stats_incremental_on,
  1251. db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.delayed_durability_desc AS [delayed_durability_status],
  1252. db.is_query_store_on, db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1253. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1254. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1255. db.target_recovery_time_in_seconds, db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced,
  1256. db.is_memory_optimized_elevate_to_snapshot_on, db.is_remote_data_archive_enabled, db.is_mixed_page_allocation_on
  1257. FROM master.sys.databases AS db (NOLOCK)
  1258. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1259. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1260. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1261. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1262. 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 + '
  1263. ORDER BY [Database_Name]
  1264. OPTION (RECOMPILE)'
  1265. END
  1266. EXECUTE sp_executesql @sqlcmd;
  1267. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1268. BEGIN
  1269. SELECT TOP 1 @curdbname = [dbname], @curdbid = [dbid], @currole = [role], @state = [state], @cursecondary_role_allow_connections = secondary_role_allow_connections FROM #tmpdbs0 WHERE isdone = 0
  1270. IF (@currole = 2 AND @cursecondary_role_allow_connections = 0) OR @state <> 0
  1271. BEGIN
  1272. 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
  1273. FROM sys.master_files (NOLOCK) WHERE [database_id] = ' + CONVERT(VARCHAR(10), @curdbid)
  1274. END
  1275. ELSE
  1276. BEGIN
  1277. SET @sqlcmd = 'USE ' + QUOTENAME(@curdbname) + ';
  1278. 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
  1279. FROM sys.database_files (NOLOCK)'
  1280. END
  1281. BEGIN TRY
  1282. INSERT INTO #tmpdbfiledetail
  1283. EXECUTE sp_executesql @sqlcmd
  1284. END TRY
  1285. BEGIN CATCH
  1286. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1287. SELECT @ErrorMessage = 'Database Information subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1288. RAISERROR (@ErrorMessage, 16, 1);
  1289. END CATCH
  1290. UPDATE #tmpdbs0
  1291. SET isdone = 1
  1292. WHERE [dbid] = @curdbid
  1293. END;
  1294. 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,
  1295. 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,
  1296. 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,
  1297. is_media_read_only, is_read_only, is_sparse, is_name_reserved
  1298. FROM #tmpdbfiledetail
  1299. ORDER BY database_id, [file_id];
  1300. IF @sqlmajorver >= 12
  1301. BEGIN
  1302. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1303. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  1304. DROP TABLE #tblInMemDBs;
  1305. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  1306. CREATE TABLE #tblInMemDBs ([DBName] sysname, [Has_MemoryOptimizedObjects] bit, [MemoryAllocated_MemoryOptimizedObjects_KB] DECIMAL(18,2), [MemoryUsed_MemoryOptimizedObjects_KB] DECIMAL(18,2));
  1307. UPDATE #tmpdbs0
  1308. SET isdone = 0;
  1309. UPDATE #tmpdbs0
  1310. SET isdone = 1
  1311. WHERE [state] <> 0 OR [dbid] < 5;
  1312. UPDATE #tmpdbs0
  1313. SET isdone = 1
  1314. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1315. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1316. BEGIN
  1317. RAISERROR (N' |-Starting Storage analysis for In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  1318. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1319. BEGIN
  1320. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1321. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1322. SELECT ''' + @dbname + ''' AS [DBName], ISNULL((SELECT 1 FROM sys.filegroups FG WHERE FG.[type] = ''FX''), 0) AS [Has_MemoryOptimizedObjects],
  1323. 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],
  1324. 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];'
  1325. BEGIN TRY
  1326. INSERT INTO #tblInMemDBs
  1327. EXECUTE sp_executesql @sqlcmd
  1328. END TRY
  1329. BEGIN CATCH
  1330. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1331. SELECT @ErrorMessage = 'Storage analysis for In-Memory OLTP Engine subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1332. RAISERROR (@ErrorMessage, 16, 1);
  1333. END CATCH
  1334. UPDATE #tmpdbs0
  1335. SET isdone = 1
  1336. WHERE [dbid] = @dbid
  1337. END
  1338. END;
  1339. IF (SELECT COUNT([DBName]) FROM #tblInMemDBs WHERE [Has_MemoryOptimizedObjects] = 1) > 0
  1340. BEGIN
  1341. SELECT 'Information' AS [Category], 'InMem_Database_Storage' AS [Information], DBName AS [Database_Name],
  1342. [MemoryAllocated_MemoryOptimizedObjects_KB], [MemoryUsed_MemoryOptimizedObjects_KB]
  1343. FROM #tblInMemDBs WHERE Has_MemoryOptimizedObjects = 1
  1344. ORDER BY DBName;
  1345. END
  1346. ELSE
  1347. BEGIN
  1348. SELECT 'Information' AS [Category], 'InMem_Database_Storage' AS [Information], '[NA]' AS [Comment]
  1349. END
  1350. END;
  1351. -- http://support.microsoft.com/kb/2857849
  1352. IF @sqlmajorver > 10 AND @IsHadrEnabled = 1
  1353. BEGIN
  1354. SELECT 'Information' AS [Category], 'AlwaysOn_AG_Databases' AS [Information], dc.database_name AS [Database_Name],
  1355. d.synchronization_health_desc, d.synchronization_state_desc, d.database_state_desc
  1356. FROM sys.dm_hadr_database_replica_states d
  1357. INNER JOIN sys.availability_databases_cluster dc ON d.group_database_id=dc.group_database_id
  1358. WHERE d.is_local=1
  1359. END;
  1360. --------------------------------------------------------------------------------------------------------------------------------
  1361. -- Database file autogrows last 72h subsection
  1362. --------------------------------------------------------------------------------------------------------------------------------
  1363. RAISERROR (N' |-Starting database file autogrows last 72h', 10, 1) WITH NOWAIT
  1364. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE is_default = 1)
  1365. BEGIN
  1366. DECLARE @tracefilename VARCHAR(500)
  1367. SELECT @tracefilename = LEFT([path],LEN([path]) - PATINDEX('%\%', REVERSE([path]))) + '\log.trc' FROM sys.traces WHERE is_default = 1;
  1368. WITH AutoGrow_CTE (databaseid, [filename], Growth, Duration, StartTime, EndTime)
  1369. AS
  1370. (
  1371. SELECT databaseid, [filename], SUM(IntegerData*8) AS Growth, Duration, StartTime, EndTime--, CASE WHEN EventClass =
  1372. FROM ::fn_trace_gettable(@tracefilename, default)
  1373. WHERE EventClass >= 92 AND EventClass <= 95 AND DATEDIFF(hh,StartTime,GETDATE()) < 72 -- Last 24h
  1374. GROUP BY databaseid, [filename], IntegerData, Duration, StartTime, EndTime
  1375. )
  1376. SELECT 'Information' AS [Category], 'Recorded_Autogrows_Lst72H' AS [Information], DB_NAME(database_id) AS Database_Name,
  1377. mf.name AS logical_file_name, mf.size*8 / 1024 AS size_MB, mf.type_desc,
  1378. ag.Growth AS [growth_KB], CASE WHEN is_percent_growth = 1 THEN 'Pct' ELSE 'MB' END AS growth_type,
  1379. Duration/1000 AS Growth_Duration_ms, ag.StartTime, ag.EndTime
  1380. FROM sys.master_files mf
  1381. LEFT OUTER JOIN AutoGrow_CTE ag ON mf.database_id=ag.databaseid AND mf.name=ag.[filename]
  1382. WHERE ag.Growth > 0 --Only where growth occurred
  1383. GROUP BY database_id, mf.name, mf.size, ag.Growth, ag.Duration, ag.StartTime, ag.EndTime, is_percent_growth, mf.growth, mf.type_desc
  1384. ORDER BY Database_Name, logical_file_name, ag.StartTime;
  1385. END
  1386. ELSE
  1387. BEGIN
  1388. SELECT 'Information' AS [Category], 'Recorded_Autogrows_Lst72H' AS [Information], '[WARNING: Could not gather information on autogrow times]' AS [Comment]
  1389. END;
  1390. --------------------------------------------------------------------------------------------------------------------------------
  1391. -- Database triggers subsection
  1392. --------------------------------------------------------------------------------------------------------------------------------
  1393. IF @ptochecks = 1
  1394. BEGIN
  1395. RAISERROR (N' |-Starting database triggers', 10, 1) WITH NOWAIT
  1396. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1397. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  1398. DROP TABLE #tblTriggers;
  1399. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  1400. 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);
  1401. UPDATE #tmpdbs0
  1402. SET isdone = 0;
  1403. UPDATE #tmpdbs0
  1404. SET isdone = 1
  1405. WHERE [state] <> 0 OR [dbid] < 5;
  1406. UPDATE #tmpdbs0
  1407. SET isdone = 1
  1408. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1409. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1410. BEGIN
  1411. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1412. BEGIN
  1413. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1414. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1415. 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
  1416. FROM sys.triggers AS st
  1417. INNER JOIN sys.tables stb ON st.parent_id = stb.[object_id]
  1418. INNER JOIN sys.schemas ss ON stb.[schema_id] = ss.[schema_id]
  1419. WHERE st.is_ms_shipped = 0
  1420. ORDER BY stb.name, st.name;'
  1421. BEGIN TRY
  1422. INSERT INTO #tblTriggers
  1423. EXECUTE sp_executesql @sqlcmd
  1424. END TRY
  1425. BEGIN CATCH
  1426. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1427. SELECT @ErrorMessage = 'Database triggers subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1428. RAISERROR (@ErrorMessage, 16, 1);
  1429. END CATCH
  1430. UPDATE #tmpdbs0
  1431. SET isdone = 1
  1432. WHERE [dbid] = @dbid
  1433. END
  1434. END;
  1435. IF (SELECT COUNT([triggerName]) FROM #tblTriggers) > 0
  1436. BEGIN
  1437. SELECT 'Information' AS [Category], 'Database_Triggers' AS [Information], DBName AS [Database_Name],
  1438. triggerName AS [Trigger_Name], schemaName AS [Schema_Name], tableName AS [Table_Name],
  1439. type_desc AS [Trigger_Type], parent_class_desc AS [Trigger_Parent],
  1440. CASE is_instead_of_trigger WHEN 1 THEN 'INSTEAD_OF' ELSE 'AFTER' END AS [Trigger_Behavior],
  1441. create_date, modify_date,
  1442. CASE WHEN is_disabled = 1 THEN 'YES' ELSE 'NO' END AS [is_disabled],
  1443. CASE WHEN is_not_for_replication = 1 THEN 'YES' ELSE 'NO' END AS [is_not_for_replication]
  1444. FROM #tblTriggers
  1445. ORDER BY DBName, tableName, triggerName;
  1446. END
  1447. ELSE
  1448. BEGIN
  1449. SELECT 'Information' AS [Category], 'Database_Triggers' AS [Information], '[NA]' AS [Comment]
  1450. END
  1451. END;
  1452. --------------------------------------------------------------------------------------------------------------------------------
  1453. -- Enterprise features usage subsection
  1454. --------------------------------------------------------------------------------------------------------------------------------
  1455. IF @sqlmajorver > 9
  1456. BEGIN
  1457. RAISERROR (N'|-Starting Enterprise features usage', 10, 1) WITH NOWAIT
  1458. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1459. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  1460. DROP TABLE #tblPerSku;
  1461. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  1462. CREATE TABLE #tblPerSku ([DBName] sysname NULL, [Feature_Name] VARCHAR(100));
  1463. UPDATE #tmpdbs0
  1464. SET isdone = 0;
  1465. UPDATE #tmpdbs0
  1466. SET isdone = 1
  1467. WHERE [state] <> 0 OR [dbid] < 5;
  1468. UPDATE #tmpdbs0
  1469. SET isdone = 1
  1470. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1471. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1472. BEGIN
  1473. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1474. BEGIN
  1475. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1476. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1477. SELECT ''' + @dbname + ''' AS [DBName], feature_name FROM sys.dm_db_persisted_sku_features (NOLOCK);'
  1478. BEGIN TRY
  1479. INSERT INTO #tblPerSku
  1480. EXECUTE sp_executesql @sqlcmd
  1481. END TRY
  1482. BEGIN CATCH
  1483. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1484. SELECT @ErrorMessage = 'Enterprise features usage subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1485. RAISERROR (@ErrorMessage, 16, 1);
  1486. END CATCH
  1487. UPDATE #tmpdbs0
  1488. SET isdone = 1
  1489. WHERE [dbid] = @dbid
  1490. END
  1491. END;
  1492. IF @sqlmajorver > 10 AND ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13) AND @IsHadrEnabled = 1
  1493. BEGIN
  1494. INSERT INTO #tblPerSku
  1495. SELECT NULL, 'Always_On' AS feature_name
  1496. END;
  1497. 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
  1498. BEGIN
  1499. INSERT INTO #tblPerSku
  1500. 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
  1501. END;
  1502. IF (@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13
  1503. BEGIN
  1504. DELETE FROM #tblPerSku
  1505. WHERE Feature_Name IN ('ColumnStoreIndex','InMemoryOLTP')
  1506. END;
  1507. IF (SELECT COUNT([Feature_Name]) FROM #tblPerSku) > 0
  1508. BEGIN
  1509. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Check], '[INFORMATION: Some databases are using Enterprise only features]' AS [Comment]
  1510. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Information], DBName AS [Database_Name], [Feature_Name]
  1511. FROM #tblPerSku
  1512. ORDER BY 2, 3
  1513. END
  1514. ELSE
  1515. BEGIN
  1516. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Check], '[NA]' AS [Comment]
  1517. END
  1518. END;
  1519. --------------------------------------------------------------------------------------------------------------------------------
  1520. -- Backups since last Full Information subsection
  1521. --------------------------------------------------------------------------------------------------------------------------------
  1522. RAISERROR (N'|-Starting Backups', 10, 1) WITH NOWAIT
  1523. IF @sqlmajorver > 10
  1524. BEGIN
  1525. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Backups_since_last_Full'' AS [Information],
  1526. [database_name] AS [Database_Name], CASE WHEN type = ''D'' THEN ''Database''
  1527. WHEN type = ''I'' THEN ''Diff_Database''
  1528. WHEN type = ''L'' THEN ''Log''
  1529. WHEN type = ''F'' THEN ''File''
  1530. WHEN type = ''G'' THEN ''Diff_file''
  1531. WHEN type = ''P'' THEN ''Partial''
  1532. WHEN type = ''Q'' THEN ''Diff_partial''
  1533. ELSE NULL END AS [bck_type],
  1534. [backup_start_date], [backup_finish_date],
  1535. CONVERT(decimal(20,2),backup_size/1024.00/1024.00) AS [backup_size_MB],
  1536. CONVERT(decimal(20,2),compressed_backup_size/1024.00/1024.00) AS [compressed_backup_size_MB],
  1537. [recovery_model], [user_name],
  1538. database_backup_lsn AS [full_base_lsn], [differential_base_lsn], [expiration_date],
  1539. [is_password_protected], [has_backup_checksums], [is_readonly], is_copy_only, [has_incomplete_metadata] AS [Tail_log]
  1540. FROM msdb.dbo.backupset bck1 (NOLOCK)
  1541. WHERE is_copy_only = 0 -- No COPY_ONLY backups
  1542. 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)
  1543. ORDER BY database_name, backup_start_date DESC'
  1544. END
  1545. ELSE
  1546. BEGIN
  1547. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Backups_since_last_Full'' AS [Information],
  1548. [database_name] AS [Database_Name], CASE WHEN type = ''D'' THEN ''Database''
  1549. WHEN type = ''I'' THEN ''Diff_Database''
  1550. WHEN type = ''L'' THEN ''Log''
  1551. WHEN type = ''F'' THEN ''File''
  1552. WHEN type = ''G'' THEN ''Diff_file''
  1553. WHEN type = ''P'' THEN ''Partial''
  1554. WHEN type = ''Q'' THEN ''Diff_partial''
  1555. ELSE NULL END AS [bck_type],
  1556. [backup_start_date], [backup_finish_date],
  1557. CONVERT(decimal(20,2),backup_size/1024.00/1024.00) AS [backup_size_MB],
  1558. ''[NA]'' AS [compressed_backup_size_MB],
  1559. [recovery_model], [user_name],
  1560. database_backup_lsn AS [full_base_lsn], [differential_base_lsn], [expiration_date],
  1561. [is_password_protected], [has_backup_checksums], [is_readonly], is_copy_only, [has_incomplete_metadata] AS [Tail_log]
  1562. FROM msdb.dbo.backupset bck1 (NOLOCK)
  1563. WHERE is_copy_only = 0 -- No COPY_ONLY backups
  1564. 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)
  1565. ORDER BY database_name, backup_start_date DESC'
  1566. END;
  1567. EXECUTE sp_executesql @sqlcmd;
  1568. --------------------------------------------------------------------------------------------------------------------------------
  1569. -- System Configuration subsection
  1570. --------------------------------------------------------------------------------------------------------------------------------
  1571. RAISERROR (N'|-Starting System Configuration', 10, 1) WITH NOWAIT
  1572. SELECT 'Information' AS [Category], 'All_System_Configurations' AS [Information],
  1573. name AS [Name],
  1574. configuration_id AS [Number],
  1575. minimum AS [Minimum],
  1576. maximum AS [Maximum],
  1577. is_dynamic AS [Dynamic],
  1578. is_advanced AS [Advanced],
  1579. value AS [ConfigValue],
  1580. value_in_use AS [RunValue],
  1581. description AS [Description]
  1582. FROM sys.configurations (NOLOCK)
  1583. ORDER BY name OPTION (RECOMPILE);
  1584. --------------------------------------------------------------------------------------------------------------------------------
  1585. -- Pre-checks section
  1586. --------------------------------------------------------------------------------------------------------------------------------
  1587. RAISERROR (N'Starting Pre-Checks - Building DB list excluding MS shipped', 10, 1) WITH NOWAIT
  1588. DECLARE @MSdb int
  1589. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  1590. DROP TABLE #tmpdbs1;
  1591. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  1592. CREATE TABLE #tmpdbs1 (id int IDENTITY(1,1), [dbid] int, [dbname] VARCHAR(1000), [role] tinyint, [secondary_role_allow_connections] tinyint, isdone bit)
  1593. RAISERROR (N'|-Excluding MS shipped by standard names and databases belonging to non-readable AG secondary replicas (if available)', 10, 1) WITH NOWAIT
  1594. -- Ignore MS shipped databases and databases belonging to non-readable AG secondary replicas
  1595. INSERT INTO #tmpdbs1 ([dbid], [dbname], [role], [secondary_role_allow_connections], [isdone])
  1596. SELECT [dbid], [dbname], [role], [secondary_role_allow_connections], 0
  1597. FROM #tmpdbs0 (NOLOCK)
  1598. WHERE is_read_only = 0 AND [state] = 0 AND [dbid] > 4 AND is_distributor = 0
  1599. AND [role] <> 2 AND (secondary_role_allow_connections <> 0 OR secondary_role_allow_connections IS NULL)
  1600. AND lower([dbname]) NOT IN ('virtualmanagerdb', --Virtual Machine Manager
  1601. 'scspfdb', --Service Provider Foundation
  1602. 'semanticsdb', --Semantic Search
  1603. 'servicemanager','service manager','dwstagingandconfig','dwrepository','dwdatamart','dwasdatabase','omdwdatamart','cmdwdatamart', --SCSM
  1604. 'ssodb','bamanalysis','bamarchive','bamalertsapplication','bamalertsnsmain','bamprimaryimport','bamstarschema','biztalkmgmtdb','biztalkmsgboxdb','biztalkdtadb','biztalkruleenginedb','bamprimaryimport','biztalkedidb','biztalkhwsdb','tpm','biztalkanalysisdb','bamprimaryimportsuccessfully', --BizTalk
  1605. 'aspstate','aspnet', --ASP.NET
  1606. 'mscrm_config', --Dynamics CRM
  1607. 'cpsdyn','lcslog','lcscdr','lis','lyss','mgc','qoemetrics','rgsconfig','rgsdyn','rtc','rtcab','rtcab1','rtcdyn','rtcshared','rtcxds','xds', --Lync
  1608. 'activitylog','branchdb','clienttracelog','eventlog','listingssettings','servicegroupdb','tservercontroller','vodbackend', --MediaRoom
  1609. 'operationsmanager','operationsmanagerdw','operationsmanagerac', --SCOM
  1610. 'orchestrator', --Orchestrator
  1611. 'sso','wss_search','wss_search_config','sharedservices_db','sharedservices_search_db','wss_content','profiledb', 'social db','sync db', --Sharepoint
  1612. 'susdb', --WSUS
  1613. 'projectserver_archive','projectserver_draft','projectserver_published','projectserver_reporting', --Project Server
  1614. 'reportserver','reportservertempdb','rsdb','rstempdb', --SSRS
  1615. 'fastsearchadmindatabase', --Fast Search
  1616. 'ppsmonitoring','ppsplanningservice','ppsplanningsystem', --PerformancePoint Services
  1617. 'dynamics', --Dynamics GP
  1618. 'microsoftdynamicsax','microsoftdynamicsaxbaseline', --Dynamics AX
  1619. 'fimservice','fimsynchronizationservice', --Forefront Identity Manager
  1620. 'sbgatewaydatabase','sbmanagementdb', --Service Bus
  1621. 'wfinstancemanagementdb','wfmanagementdb','wfresourcemanagementdb' --Workflow Manager
  1622. )
  1623. AND [dbname] NOT LIKE 'repANDtingservice[_]%' --SSRS
  1624. AND [dbname] NOT LIKE 'tfs[_]%' --TFS
  1625. AND [dbname] NOT LIKE 'defaultpowerpivotserviceapplicationdb%' --PowerPivot
  1626. AND [dbname] NOT LIKE 'perfANDmancepoint service[_]%' --PerfANDmancePoint Services
  1627. AND [dbname] NOT LIKE '%database nav%' --Dynamics NAV
  1628. AND [dbname] NOT LIKE '%[_]mscrm' --Dynamics CRM
  1629. AND [dbname] NOT LIKE 'dpmdb[_]%' --DPM
  1630. AND [dbname] NOT LIKE 'sbmessagecontainer%' --Service Bus
  1631. AND [dbname] NOT LIKE 'sma%' --SCSMA
  1632. AND [dbname] NOT LIKE 'releasemanagement%' --TFS Release Management
  1633. AND [dbname] NOT LIKE 'projectwebapp%' --Project Server
  1634. AND [dbname] NOT LIKE 'sms[_]%' AND [dbname] NOT LIKE 'cm[_]%' --SCCM
  1635. AND [dbname] NOT LIKE 'fepdw%' AND [dbname] NOT LIKE 'FEPDB[_]%' --Forefront Endpoint Protection
  1636. --Sharepoint
  1637. AND [dbname] NOT LIKE 'sharepoint[_]admincontent%' AND [dbname] NOT LIKE 'sharepoint[_]config%' AND [dbname] NOT LIKE 'wss[_]content%' AND [dbname] NOT LIKE 'wss[_]search%'
  1638. 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%'
  1639. AND [dbname] NOT LIKE 'sharedservicescontent%' AND [dbname] NOT LIKE 'application[_]registry[_]service[_]db%' AND [dbname] NOT LIKE 'search[_]service[_]application[_]propertystANDedb[_]%'
  1640. AND [dbname] NOT LIKE 'subscriptionsettings[_]%' AND [dbname] NOT LIKE 'webanalyticsserviceapplication[_]stagingdb[_]%' AND [dbname] NOT LIKE 'webanalyticsserviceapplication[_]repANDtingdb[_]%'
  1641. AND [dbname] NOT LIKE 'bdc[_]service[_]db[_]%' AND [dbname] NOT LIKE 'managed metadata service[_]%' AND [dbname] NOT LIKE 'perfANDmancepoint service application[_]%'
  1642. 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%'
  1643. 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[_]%'
  1644. AND [dbname] NOT LIKE 'wANDdautomationservices[_]%' AND [dbname] NOT LIKE 'wss[_]logging%' AND [dbname] NOT LIKE 'wss[_]usageapplication%' AND [dbname] NOT LIKE 'appmng[_]service[_]db%'
  1645. AND [dbname] NOT LIKE 'search[_]service[_]application[_]analyticsrepANDtingstANDedb[_]%' AND [dbname] NOT LIKE 'search[_]service[_]application[_]linksstANDedb[_]%' AND [dbname] NOT LIKE 'sharepoint[_]logging[_]%'
  1646. 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%'
  1647. IF EXISTS (SELECT name FROM msdb.sys.objects (NOLOCK) WHERE name='MSdistributiondbs' AND is_ms_shipped = 1)
  1648. BEGIN
  1649. DELETE FROM #tmpdbs1 WHERE [dbid] IN (SELECT DB_ID(name) FROM msdb.dbo.MSdistributiondbs)
  1650. END;
  1651. RAISERROR (N'|-Excluding MS shipped by notable object names', 10, 1) WITH NOWAIT
  1652. -- Removing other noticeable MS shipped DBs
  1653. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  1654. BEGIN
  1655. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  1656. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1657. 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)
  1658. OR (OBJECT_ID(''dbo.Versions'',''U'') IS NOT NULL
  1659. 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)
  1660. 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)
  1661. 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)
  1662. 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)
  1663. 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)
  1664. 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)
  1665. 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)
  1666. 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)
  1667. 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)
  1668. 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)
  1669. 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)
  1670. 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)
  1671. )
  1672. 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)
  1673. 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)
  1674. 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)
  1675. 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)
  1676. -- End Sharepoint
  1677. 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)
  1678. 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)
  1679. -- End ASP.NET
  1680. 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)
  1681. -- End PowerPivot
  1682. 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)
  1683. -- End Orchestrator
  1684. 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)
  1685. -- End VMM
  1686. 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)
  1687. -- End Service Provider Foundation
  1688. 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)
  1689. 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))
  1690. -- End BizTalk
  1691. 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)
  1692. -- End Dynamics AX
  1693. OR (OBJECT_ID(''dbo.Notification'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SystemUserRoles'',''U'') IS NOT NULL
  1694. AND (OBJECT_ID(''dbo.p_GetCrmUserId'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.p_GetPrivilegesInRole'',''P'') IS NOT NULL)
  1695. OR (OBJECT_ID(''dbo.p_AccountOVRollup'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.p_GetDbSize'',''P'') IS NOT NULL))
  1696. -- End Dynamics CRM
  1697. 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'')))
  1698. -- End Dynamics NAV
  1699. 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)
  1700. -- End Dynamics GP
  1701. 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)
  1702. -- End SCCM
  1703. 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)
  1704. -- End Forefront Endpoint Protection
  1705. 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)
  1706. -- End Fast Search
  1707. OR (OBJECT_ID(''fim.Objects'',''U'') IS NOT NULL AND SCHEMA_ID(''debug'') IS NOT NULL)
  1708. 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)
  1709. -- End Forefront Identity Manager
  1710. 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)
  1711. 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)
  1712. -- End PerformancePoint Services
  1713. 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))
  1714. -- End Project Server
  1715. OR (OBJECT_ID(''apm.MESSAGES'',''U'') IS NOT NULL AND SCHEMA_ID(''CS'') IS NOT NULL OR SCHEMA_ID(''CM'') IS NOT NULL)
  1716. 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)
  1717. 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)
  1718. 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)
  1719. -- End SCOM
  1720. OR (OBJECT_ID(''dbo.version'',''U'') IS NOT NULL AND EXISTS(SELECT 1 FROM sys.internal_tables (NOLOCK) WHERE name LIKE ''language[_]model[_]%''))
  1721. -- End Semantic Search
  1722. 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)
  1723. -- End WSUS
  1724. 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)
  1725. -- End DPM
  1726. OR ((OBJECT_ID(''dbo.DomainTable'',''U'') IS NOT NULL AND OBJECT_ID(''etl.Source'',''U'') IS NOT NULL)
  1727. 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)
  1728. 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))
  1729. -- End SCSM
  1730. 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)
  1731. -- End SSRS
  1732. OR (OBJECT_ID(''dbo.prc_ChangeHostId'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.prc_EnablePrefixCompression'',''P'') IS NOT NULL
  1733. 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)
  1734. 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))
  1735. 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)
  1736. -- End TFS
  1737. 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)
  1738. -- End TFS Release Management
  1739. 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)
  1740. 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)
  1741. 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)
  1742. -- End Service Bus
  1743. 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)
  1744. 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)
  1745. 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)
  1746. -- End Workflow Manager
  1747. 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)
  1748. -- End SCSMA
  1749. BEGIN
  1750. SELECT @MSdbOUT = ' + CONVERT(VARCHAR(10), @dbid) + '
  1751. END'
  1752. SET @params = N'@MSdbOUT int OUTPUT';
  1753. EXECUTE sp_executesql @sqlcmd, @params, @MSdbOUT=@MSdb OUTPUT
  1754. IF @MSdb = @dbid
  1755. BEGIN
  1756. DELETE FROM #tmpdbs1
  1757. WHERE [dbid] = @dbid;
  1758. END
  1759. ELSE
  1760. BEGIN
  1761. UPDATE #tmpdbs1
  1762. SET isdone = 1
  1763. WHERE [dbid] = @dbid
  1764. END
  1765. END;
  1766. UPDATE #tmpdbs1
  1767. SET isdone = 0;
  1768. RAISERROR (N'|-Applying 2nd layer of specific database scope, if any', 10, 1) WITH NOWAIT
  1769. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  1770. DROP TABLE #tmpdbs_userchoice;
  1771. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  1772. CREATE TABLE #tmpdbs_userchoice ([dbid] int PRIMARY KEY, [dbname] VARCHAR(1000))
  1773. IF @dbScope IS NOT NULL
  1774. BEGIN
  1775. SELECT @sqlcmd = 'SELECT [dbid], [dbname]
  1776. FROM #tmpdbs0 (NOLOCK)
  1777. WHERE is_read_only = 0 AND [state] = 0 AND [dbid] > 4 AND is_distributor = 0
  1778. AND [role] <> 2 AND (secondary_role_allow_connections <> 0 OR secondary_role_allow_connections IS NULL)
  1779. AND [dbid] IN (' + REPLACE(@dbScope,' ','') + ')'
  1780. INSERT INTO #tmpdbs_userchoice ([dbid], [dbname])
  1781. EXEC sp_executesql @sqlcmd;
  1782. SELECT @sqlcmd = 'DELETE FROM #tmpdbs1 WHERE [dbid] NOT IN (' + REPLACE(@dbScope,' ','') + ')'
  1783. EXEC sp_executesql @sqlcmd;
  1784. END;
  1785. --------------------------------------------------------------------------------------------------------------------------------
  1786. -- Checks section
  1787. --------------------------------------------------------------------------------------------------------------------------------
  1788. RAISERROR (N'Starting Checks section', 10, 1) WITH NOWAIT
  1789. RAISERROR (N'|-Starting Processor Checks', 10, 1) WITH NOWAIT
  1790. --------------------------------------------------------------------------------------------------------------------------------
  1791. -- Number of available Processors for this instance vs. MaxDOP setting subsection
  1792. --------------------------------------------------------------------------------------------------------------------------------
  1793. RAISERROR (N' |-Starting Number of available Processors for this instance vs. MaxDOP setting', 10, 1) WITH NOWAIT
  1794. DECLARE /*@cpucount int, @numa int, */@affined_cpus int
  1795. /*
  1796. DECLARE @i int, @cpuaffin_fixed VARCHAR(300)
  1797. SET @cpuaffin_fixed = @cpuaffin
  1798. SET @i = @cpucount/@numa + 1
  1799. WHILE @i <= @cpucount
  1800. BEGIN
  1801. SELECT @cpuaffin_fixed = STUFF(@cpuaffin_fixed, @i, 1, '_' + SUBSTRING(@cpuaffin, @i, 1))
  1802. SET @i = @i + @cpucount/@numa + 1
  1803. END
  1804. */
  1805. SELECT @affined_cpus = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE is_online = 1 AND scheduler_id < 255 AND parent_node_id < 64;
  1806. --SELECT @cpucount = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64
  1807. SELECT 'Processor_checks' AS [Category], 'Parallelism_MaxDOP' AS [Check],
  1808. CASE WHEN [value] > @affined_cpus THEN '[WARNING: MaxDOP setting exceeds available processor count (affinity)]'
  1809. 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)]'
  1810. 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]'
  1811. 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]'
  1812. ELSE '[OK]'
  1813. END AS [Deviation]
  1814. FROM sys.configurations (NOLOCK) WHERE name = 'max degree of parallelism';
  1815. SELECT 'Processor_checks' AS [Category], 'Parallelism_MaxDOP' AS [Information],
  1816. CASE WHEN [value] > @affined_cpus THEN @affined_cpus
  1817. WHEN @numa = 1 AND @affined_cpus > 8 AND ([value] = 0 OR [value] > 8) THEN 8
  1818. WHEN @numa > 1 AND (@cpucount/@numa) < 8 AND ([value] = 0 OR [value] > (@cpucount/@numa)) THEN @cpucount/@numa
  1819. WHEN @numa > 1 AND (@cpucount/@numa) >= 8 AND ([value] = 0 OR [value] > 8 OR [value] > (@cpucount/@numa)) THEN 8
  1820. ELSE 0
  1821. END AS [Recommended_MaxDOP],
  1822. [value] AS [Current_MaxDOP], @cpucount AS [Available_Processors], @affined_cpus AS [Affined_Processors],
  1823. -- Processor Affinity is shown highest to lowest CPU ID
  1824. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1825. FROM sys.configurations (NOLOCK) WHERE name = 'max degree of parallelism';
  1826. --------------------------------------------------------------------------------------------------------------------------------
  1827. -- Processor Affinity in NUMA architecture subsection
  1828. --------------------------------------------------------------------------------------------------------------------------------
  1829. RAISERROR (N' |-Starting Processor Affinity in NUMA architecture', 10, 1) WITH NOWAIT
  1830. IF @numa > 1
  1831. BEGIN
  1832. 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),
  1833. 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)
  1834. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Check],
  1835. CASE WHEN (SELECT COUNT(*) FROM ncpuCTE) > 0 THEN '[WARNING: Current NUMA configuration is not recommended. At least one node has a single assigned CPU]'
  1836. 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]'
  1837. ELSE '[OK]' END AS [Deviation]
  1838. FROM sys.dm_os_sys_info (NOLOCK)
  1839. OPTION (RECOMPILE);
  1840. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Information], cpu_count AS [Logical_CPU_Count],
  1841. (SELECT COUNT(DISTINCT parent_node_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64) AS [NUMA_Nodes],
  1842. -- Processor Affinity is shown highest to lowest CPU ID
  1843. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1844. FROM sys.dm_os_sys_info (NOLOCK)
  1845. OPTION (RECOMPILE);
  1846. END
  1847. ELSE
  1848. BEGIN
  1849. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Check], '[Not_NUMA]' AS [Deviation]
  1850. FROM sys.dm_os_sys_info (NOLOCK)
  1851. OPTION (RECOMPILE);
  1852. END;
  1853. --------------------------------------------------------------------------------------------------------------------------------
  1854. -- Additional Processor information subsection
  1855. --------------------------------------------------------------------------------------------------------------------------------
  1856. RAISERROR (N' |-Starting Additional Processor information', 10, 1) WITH NOWAIT
  1857. -- Processor Info
  1858. SELECT 'Processor_checks' AS [Category], 'Processor_Summary' AS [Information], cpu_count AS [Logical_CPU_Count], hyperthread_ratio AS [Cores2Socket_Ratio],
  1859. cpu_count/hyperthread_ratio AS [CPU_Sockets],
  1860. 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],
  1861. @affined_cpus AS [Affined_Processors],
  1862. -- Processor Affinity is shown highest to lowest Processor ID
  1863. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1864. FROM sys.dm_os_sys_info (NOLOCK)
  1865. OPTION (RECOMPILE);
  1866. IF @ptochecks = 1
  1867. BEGIN
  1868. RAISERROR (N' |-Starting Processor utilization rate in the last 2 hours', 10, 1) WITH NOWAIT
  1869. -- Processor utilization rate in the last 2 hours
  1870. DECLARE @ts_now bigint
  1871. DECLARE @tblAggCPU TABLE (SQLProc tinyint, SysIdle tinyint, OtherProc tinyint, Minutes tinyint)
  1872. SELECT @ts_now = ms_ticks FROM sys.dm_os_sys_info (NOLOCK);
  1873. WITH cteCPU (record_id, SystemIdle, SQLProcessUtilization, [timestamp]) AS (SELECT
  1874. record.value('(./Record/@id)[1]', 'int') AS record_id,
  1875. record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS SystemIdle,
  1876. record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS SQLProcessUtilization,
  1877. [TIMESTAMP] FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  1878. FROM sys.dm_os_ring_buffers (NOLOCK)
  1879. WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
  1880. AND record LIKE '%<SystemHealth>%') AS x
  1881. )
  1882. INSERT INTO @tblAggCPU
  1883. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 10
  1884. FROM cteCPU
  1885. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -10, GETDATE())
  1886. UNION ALL
  1887. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 20
  1888. FROM cteCPU
  1889. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -10, GETDATE()) AND
  1890. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -20, GETDATE())
  1891. UNION ALL
  1892. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 30
  1893. FROM cteCPU
  1894. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -20, GETDATE()) AND
  1895. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -30, GETDATE())
  1896. UNION ALL
  1897. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 40
  1898. FROM cteCPU
  1899. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -30, GETDATE()) AND
  1900. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -40, GETDATE())
  1901. UNION ALL
  1902. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 50
  1903. FROM cteCPU
  1904. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -40, GETDATE()) AND
  1905. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -50, GETDATE())
  1906. UNION ALL
  1907. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 60
  1908. FROM cteCPU
  1909. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -50, GETDATE()) AND
  1910. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -60, GETDATE())
  1911. UNION ALL
  1912. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 70
  1913. FROM cteCPU
  1914. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -60, GETDATE()) AND
  1915. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -70, GETDATE())
  1916. UNION ALL
  1917. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 80
  1918. FROM cteCPU
  1919. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -70, GETDATE()) AND
  1920. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -80, GETDATE())
  1921. UNION ALL
  1922. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 90
  1923. FROM cteCPU
  1924. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -80, GETDATE()) AND
  1925. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -90, GETDATE())
  1926. UNION ALL
  1927. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 100
  1928. FROM cteCPU
  1929. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -90, GETDATE()) AND
  1930. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -100, GETDATE())
  1931. UNION ALL
  1932. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 110
  1933. FROM cteCPU
  1934. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -100, GETDATE()) AND
  1935. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -110, GETDATE())
  1936. UNION ALL
  1937. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 120
  1938. FROM cteCPU
  1939. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -110, GETDATE()) AND
  1940. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -120, GETDATE())
  1941. IF (SELECT COUNT(SysIdle) FROM @tblAggCPU WHERE SysIdle < 30) > 0
  1942. BEGIN
  1943. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[WARNING: Detected CPU usage over 70 pct]' AS [Deviation];
  1944. END
  1945. ELSE IF (SELECT COUNT(SysIdle) FROM @tblAggCPU WHERE SysIdle < 10) > 0
  1946. BEGIN
  1947. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[WARNING: Detected CPU usage over 90 pct]' AS [Deviation];
  1948. END
  1949. ELSE
  1950. BEGIN
  1951. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[OK]' AS [Deviation];
  1952. END;
  1953. 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]
  1954. FROM @tblAggCPU;
  1955. END;
  1956. RAISERROR (N'|-Starting Memory Checks', 10, 1) WITH NOWAIT
  1957. --------------------------------------------------------------------------------------------------------------------------------
  1958. -- Server Memory subsection
  1959. --------------------------------------------------------------------------------------------------------------------------------
  1960. RAISERROR (N' |-Starting Server Memory', 10, 1) WITH NOWAIT
  1961. DECLARE @maxservermem bigint, @minservermem bigint, @systemmem bigint, @systemfreemem bigint, @numa_nodes_afinned tinyint, @LowMemoryThreshold int
  1962. DECLARE @commit_target bigint -- Includes stolen and reserved memory in the memory manager
  1963. DECLARE @committed bigint -- Does not include reserved memory in the memory manager
  1964. DECLARE @mwthreads_count int, @xtp int
  1965. IF @sqlmajorver = 9
  1966. BEGIN
  1967. SET @sqlcmd = N'SELECT @systemmemOUT = t1.record.value(''(./Record/MemoryRecord/TotalPhysicalMemory)[1]'', ''bigint'')/1024,
  1968. @systemfreememOUT = t1.record.value(''(./Record/MemoryRecord/AvailablePhysicalMemory)[1]'', ''bigint'')/1024
  1969. FROM (SELECT MAX([TIMESTAMP]) AS [TIMESTAMP], CONVERT(xml, record) AS record
  1970. FROM sys.dm_os_ring_buffers (NOLOCK)
  1971. WHERE ring_buffer_type = N''RING_BUFFER_RESOURCE_MONITOR''
  1972. AND record LIKE ''%RESOURCE_MEMPHYSICAL%''
  1973. GROUP BY record) AS t1';
  1974. END
  1975. ELSE
  1976. BEGIN
  1977. SET @sqlcmd = N'SELECT @systemmemOUT = total_physical_memory_kb/1024, @systemfreememOUT = available_physical_memory_kb/1024 FROM sys.dm_os_sys_memory';
  1978. END
  1979. SET @params = N'@systemmemOUT bigint OUTPUT, @systemfreememOUT bigint OUTPUT';
  1980. EXECUTE sp_executesql @sqlcmd, @params, @systemmemOUT=@systemmem OUTPUT, @systemfreememOUT=@systemfreemem OUTPUT;
  1981. IF @sqlmajorver >= 9 AND @sqlmajorver < 11
  1982. BEGIN
  1983. SET @sqlcmd = N'SELECT @commit_targetOUT=bpool_commit_target*8, @committedOUT=bpool_committed*8 FROM sys.dm_os_sys_info (NOLOCK)'
  1984. END
  1985. ELSE IF @sqlmajorver >= 11
  1986. BEGIN
  1987. SET @sqlcmd = N'SELECT @commit_targetOUT=committed_target_kb, @committedOUT=committed_kb FROM sys.dm_os_sys_info (NOLOCK)'
  1988. END
  1989. SET @params = N'@commit_targetOUT bigint OUTPUT, @committedOUT bigint OUTPUT';
  1990. EXECUTE sp_executesql @sqlcmd, @params, @commit_targetOUT=@commit_target OUTPUT, @committedOUT=@committed OUTPUT;
  1991. SELECT @minservermem = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE [Name] = 'min server memory (MB)';
  1992. SELECT @maxservermem = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE [Name] = 'max server memory (MB)';
  1993. SELECT @mwthreads_count = max_workers_count FROM sys.dm_os_sys_info;
  1994. 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
  1995. /*
  1996. From Windows Internals book by David Solomon and Mark Russinovich:
  1997. "The default level of available memory that signals a low-memory-resource notification event is approximately 32 MB per 4 GB,
  1998. 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."
  1999. */
  2000. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  2001. BEGIN
  2002. BEGIN TRY
  2003. SELECT @RegKey = N'System\CurrentControlSet\Control\SessionManager\MemoryManagement'
  2004. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'LowMemoryThreshold', @LowMemoryThreshold OUTPUT, NO_OUTPUT
  2005. IF @LowMemoryThreshold IS NULL
  2006. SELECT @LowMemoryThreshold = CASE WHEN @systemmem <= 4096 THEN 32 ELSE 64 END
  2007. END TRY
  2008. BEGIN CATCH
  2009. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2010. SELECT @ErrorMessage = 'Server Memory subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  2011. RAISERROR (@ErrorMessage, 16, 1);
  2012. END CATCH
  2013. END
  2014. ELSE
  2015. BEGIN
  2016. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing LowMemoryThreshold check]', 16, 1, N'sysadmin')
  2017. --RETURN
  2018. END;
  2019. SELECT 'Memory_checks' AS [Category], 'Memory_issues_MaxServerMem' AS [Check],
  2020. CASE WHEN @maxservermem = 2147483647 THEN '[WARNING: MaxMem setting is default. Please revise memory settings]'
  2021. WHEN @maxservermem > @systemmem THEN '[WARNING: MaxMem setting exceeds available system memory]'
  2022. WHEN @numa > 1 AND (@maxservermem/@numa) * @numa_nodes_afinned > (@systemmem/@numa) * @numa_nodes_afinned THEN '[WARNING: Current MaxMem setting will leverage node foreign memory.
  2023. Maximum value for MaxMem setting on this configuration is ' + CONVERT(NVARCHAR,(@systemmem/@numa) * @numa_nodes_afinned) + ' for a single instance]'
  2024. ELSE '[OK]'
  2025. END AS [Deviation], @maxservermem AS [sql_max_mem_MB];
  2026. SELECT 'Memory_checks' AS [Category], 'Memory_issues_MinServerMem' AS [Check],
  2027. 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]'
  2028. 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]'
  2029. 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]'
  2030. WHEN @numa > 1 AND (@minservermem/@numa) * @numa_nodes_afinned > (@systemmem/@numa) * @numa_nodes_afinned THEN '[WARNING: Current MinMem setting will leverage node foreign memory]'
  2031. ELSE '[OK]'
  2032. END AS [Deviation], @minservermem AS [sql_min_mem_MB];
  2033. SELECT 'Memory_checks' AS [Category], 'Memory_issues_FreeMem' AS [Check],
  2034. CASE WHEN (@systemfreemem*100)/@systemmem <= 5 THEN '[WARNING: Less than 5 percent of Free Memory available. Please revise memory settings]'
  2035. /* 64 is the default LowMemThreshold for windows on a system with 8GB of mem or more*/
  2036. WHEN @systemfreemem <= 64*3 THEN '[WARNING: System Free Memory is dangerously low. Please revise memory settings]'
  2037. ELSE '[OK]'
  2038. END AS [Deviation], @systemmem AS system_total_physical_memory_MB, @systemfreemem AS system_available_physical_memory_MB;
  2039. SELECT 'Memory_checks' AS [Category], 'Memory_issues_CommitedMem' AS [Check],
  2040. CASE WHEN @commit_target > @committed AND @sqlmajorver >= 11 THEN '[INFORMATION: Memory manager will try to obtain additional memory]'
  2041. WHEN @commit_target < @committed AND @sqlmajorver >= 11 THEN '[INFORMATION: Memory manager will try to shrink the amount of memory committed]'
  2042. WHEN @commit_target > @committed AND @sqlmajorver < 11 THEN '[INFORMATION: Buffer Pool will try to obtain additional memory]'
  2043. WHEN @commit_target < @committed AND @sqlmajorver < 11 THEN '[INFORMATION: Buffer Pool will try to shrink]'
  2044. ELSE '[OK]'
  2045. END AS [Deviation], @commit_target/1024 AS sql_commit_target_MB, @committed/1024 AS sql_commited_MB;
  2046. SELECT 'Memory_checks' AS [Category], 'Memory_reference' AS [Check],
  2047. CASE WHEN @arch IS NULL THEN '[WARNING: Could not determine architecture needed for check]'
  2048. 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
  2049. (@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
  2050. (@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
  2051. (@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
  2052. (@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
  2053. (@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
  2054. (@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]'
  2055. ELSE '[OK]'
  2056. END AS [Deviation],
  2057. 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))
  2058. 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))
  2059. 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))
  2060. 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))
  2061. 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))
  2062. 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))
  2063. 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))
  2064. END AS [Recommended_MaxMem_MB_SingleInstance],
  2065. CASE WHEN @systemmem <= 2048 THEN 512
  2066. WHEN @systemmem BETWEEN 2049 AND 4096 THEN 819
  2067. WHEN @systemmem BETWEEN 4097 AND 8192 THEN 1228
  2068. WHEN @systemmem BETWEEN 8193 AND 12288 THEN 2048
  2069. WHEN @systemmem BETWEEN 12289 AND 24576 THEN 2560
  2070. WHEN @systemmem BETWEEN 24577 AND 32768 THEN 3072
  2071. WHEN @systemmem > 32768 THEN 4096
  2072. END AS [Mem_MB_for_OS],
  2073. 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)
  2074. 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)
  2075. 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)
  2076. 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)
  2077. 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)
  2078. 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)
  2079. WHEN @systemmem > 32768 THEN @mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END)
  2080. END AS [Potential_threads_mem_MB],
  2081. @mwthreads_count AS [Configured_workers];
  2082. IF @sqlmajorver = 9
  2083. BEGIN
  2084. SELECT 'Memory_checks' AS [Category], 'Memory_Summary' AS [Information],
  2085. @maxservermem AS sql_max_mem_MB, @minservermem AS sql_min_mem_MB,
  2086. @commit_target/1024 AS sql_commit_target_MB, --BPool in SQL 2005 to 2008R2
  2087. @committed/1024 AS sql_commited_MB, --BPool in SQL 2005 to 2008R2
  2088. @systemmem AS system_total_physical_memory_MB,
  2089. @systemfreemem AS system_available_physical_memory_MB
  2090. END
  2091. ELSE
  2092. BEGIN
  2093. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Memory_Summary'' AS [Information],
  2094. @maxservermemIN AS sql_max_mem_MB, @minservermemIN AS sql_min_mem_MB,
  2095. @commit_targetIN/1024 AS sql_commit_target_MB, --BPool in SQL 2005 to 2008R2
  2096. @committedIN/1024 AS sql_commited_MB, --BPool in SQL 2005 to 2008R2
  2097. physical_memory_in_use_kb/1024 AS sql_physical_memory_in_use_MB,
  2098. large_page_allocations_kb/1024 AS sql_large_page_allocations_MB,
  2099. locked_page_allocations_kb/1024 AS sql_locked_page_allocations_MB,
  2100. @systemmemIN AS system_total_physical_memory_MB,
  2101. @systemfreememIN AS system_available_physical_memory_MB,
  2102. total_virtual_address_space_kb/1024 AS sql_total_VAS_MB,
  2103. virtual_address_space_reserved_kb/1024 AS sql_VAS_reserved_MB,
  2104. virtual_address_space_committed_kb/1024 AS sql_VAS_committed_MB,
  2105. virtual_address_space_available_kb/1024 AS sql_VAS_available_MB,
  2106. page_fault_count AS sql_page_fault_count,
  2107. memory_utilization_percentage AS sql_memory_utilization_percentage,
  2108. process_physical_memory_low AS sql_process_physical_memory_low,
  2109. process_virtual_memory_low AS sql_process_virtual_memory_low
  2110. FROM sys.dm_os_process_memory (NOLOCK)'
  2111. SET @params = N'@maxservermemIN bigint, @minservermemIN bigint, @systemmemIN bigint, @systemfreememIN bigint, @commit_targetIN bigint, @committedIN bigint';
  2112. EXECUTE sp_executesql @sqlcmd, @params, @maxservermemIN=@maxservermem, @minservermemIN=@minservermem,@systemmemIN=@systemmem, @systemfreememIN=@systemfreemem, @commit_targetIN=@commit_target, @committedIN=@committed
  2113. END;
  2114. IF @numa > 1 AND @sqlmajorver > 10
  2115. BEGIN
  2116. 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;')
  2117. END
  2118. ELSE IF @numa > 1 AND @sqlmajorver = 10
  2119. BEGIN
  2120. 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;')
  2121. END;
  2122. IF @ptochecks = 1
  2123. BEGIN
  2124. RAISERROR (N' |-Starting RM Task', 10, 1) WITH NOWAIT
  2125. IF @LowMemoryThreshold IS NOT NULL
  2126. SELECT 'Memory_checks' AS [Category], 'Memory_RM_Tresholds' AS [Information], @LowMemoryThreshold AS [MEMPHYSICAL_LOW_Threshold], @LowMemoryThreshold * 3 AS [MEMPHYSICAL_HIGH_Threshold]
  2127. SELECT 'Memory_checks' AS [Category], 'Memory_RM_Notifications' AS [Information],
  2128. 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())
  2129. ELSE DATEADD(s, ([TIMESTAMP]/1000) - (si.ms_ticks/1000), GETDATE()) END AS Event_Time,
  2130. record.value('(./Record/ResourceMonitor/Notification)[1]', 'VARCHAR(max)') AS [Notification],
  2131. record.value('(./Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint')/1024 AS [Total_Physical_Mem_MB],
  2132. record.value('(./Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint')/1024 AS [Avail_Physical_Mem_MB],
  2133. record.value('(./Record/MemoryRecord/AvailableVirtualAddressSpace)[1]', 'bigint')/1024 AS [Avail_VAS_MB],
  2134. record.value('(./Record/MemoryRecord/TotalPageFile)[1]', 'bigint')/1024 AS [Total_Pagefile_MB],
  2135. record.value('(./Record/MemoryRecord/AvailablePageFile)[1]', 'bigint')/1024 AS [Avail_Pagefile_MB]
  2136. FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  2137. FROM sys.dm_os_ring_buffers (NOLOCK)
  2138. WHERE ring_buffer_type = N'RING_BUFFER_RESOURCE_MONITOR') AS x
  2139. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2140. --WHERE CASE WHEN x.[timestamp] BETWEEN -2147483648 AND 2147483648 THEN DATEADD(ms, x.[timestamp] - si.ms_ticks, GETDATE())
  2141. -- ELSE DATEADD(s, (x.[timestamp]/1000) - (si.ms_ticks/1000), GETDATE()) END >= DATEADD(hh, -12, GETDATE())
  2142. ORDER BY 2 DESC;
  2143. RAISERROR (N' |-Starting Hand Movements from Cache Clock Hands', 10, 1) WITH NOWAIT
  2144. IF (SELECT COUNT(rounds_count) FROM sys.dm_os_memory_cache_clock_hands (NOLOCK) WHERE rounds_count > 0) > 0
  2145. BEGIN
  2146. IF @sqlmajorver >= 11
  2147. BEGIN
  2148. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Clock_Hand_Notifications'' AS [Information], mcch.name, mcch.[type],
  2149. mcch.clock_hand, mcch.clock_status, SUM(mcch.rounds_count) AS rounds_count,
  2150. SUM(mcch.removed_all_rounds_count) AS cache_entries_removed_all_rounds,
  2151. SUM(mcch.removed_last_round_count) AS cache_entries_removed_last_round,
  2152. SUM(mcch.updated_last_round_count) AS cache_entries_updated_last_round,
  2153. SUM(mcc.pages_kb) AS cache_pages_kb,
  2154. SUM(mcc.pages_in_use_kb) AS cache_pages_in_use_kb,
  2155. SUM(mcc.entries_count) AS cache_entries_count,
  2156. SUM(mcc.entries_in_use_count) AS cache_entries_in_use_count,
  2157. 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())
  2158. 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())
  2159. ELSE NULL END AS last_clock_hand_move
  2160. FROM sys.dm_os_memory_cache_counters mcc (NOLOCK)
  2161. INNER JOIN sys.dm_os_memory_cache_clock_hands mcch (NOLOCK) ON mcc.cache_address = mcch.cache_address
  2162. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2163. WHERE mcch.rounds_count > 0
  2164. 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
  2165. ORDER BY SUM(mcch.removed_all_rounds_count) DESC, mcch.[type];'
  2166. END
  2167. ELSE
  2168. BEGIN
  2169. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Clock_Hand_Notifications'' AS [Information], mcch.name, mcch.[type],
  2170. mcch.clock_hand, mcch.clock_status, SUM(mcch.rounds_count) AS rounds_count,
  2171. SUM(mcch.removed_all_rounds_count) AS cache_entries_removed_all_rounds,
  2172. SUM(mcch.removed_last_round_count) AS cache_entries_removed_last_round,
  2173. SUM(mcch.updated_last_round_count) AS cache_entries_updated_last_round,
  2174. SUM(mcc.single_pages_kb) AS cache_single_pages_kb,
  2175. SUM(mcc.multi_pages_kb) AS cache_multi_pages_kb,
  2176. SUM(mcc.single_pages_in_use_kb) AS cache_single_pages_in_use_kb,
  2177. SUM(mcc.multi_pages_in_use_kb) AS cache_multi_pages_in_use_kb,
  2178. SUM(mcc.entries_count) AS cache_entries_count,
  2179. SUM(mcc.entries_in_use_count) AS cache_entries_in_use_count,
  2180. 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())
  2181. 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())
  2182. ELSE NULL END AS last_clock_hand_move
  2183. FROM sys.dm_os_memory_cache_counters mcc (NOLOCK)
  2184. INNER JOIN sys.dm_os_memory_cache_clock_hands mcch (NOLOCK) ON mcc.cache_address = mcch.cache_address
  2185. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2186. WHERE mcch.rounds_count > 0
  2187. 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
  2188. ORDER BY SUM(mcch.removed_all_rounds_count) DESC, mcch.[type];'
  2189. END
  2190. EXECUTE sp_executesql @sqlcmd;
  2191. END
  2192. ELSE
  2193. BEGIN
  2194. SELECT 'Memory_checks' AS [Category], 'Clock_Hand_Notifications' AS [Information], '[OK]' AS Comment
  2195. END;
  2196. IF @bpool_consumer = 1
  2197. BEGIN
  2198. RAISERROR (N' |-Starting Buffer Pool Consumers from Buffer Descriptors', 10, 1) WITH NOWAIT
  2199. -- Note: in case of NUMA architecture, more than one entry per database is expected
  2200. SET @sqlcmd = 'SELECT ''Memory_checks'' AS [Category], ''Buffer_Pool_Consumers'' AS [Information],
  2201. COUNT_BIG(DISTINCT page_id)*8/1024 AS total_pages_MB,
  2202. CASE database_id WHEN 32767 THEN ''ResourceDB'' ELSE DB_NAME(database_id) END AS database_name,
  2203. SUM(row_count)/COUNT_BIG(DISTINCT page_id) AS avg_row_count_per_page,
  2204. SUM(CONVERT(BIGINT, free_space_in_bytes))/COUNT_BIG(DISTINCT page_id) AS avg_free_space_bytes_per_page
  2205. ' + CASE WHEN @sqlmajorver >= 12 THEN ',is_in_bpool_extension' ELSE '' END + '
  2206. ' + CASE WHEN @sqlmajorver = 10 THEN ',numa_node' ELSE '' END + '
  2207. ' + CASE WHEN @sqlmajorver >= 11 THEN ',AVG(read_microsec) AS avg_read_microsec' ELSE '' END + '
  2208. FROM sys.dm_os_buffer_descriptors
  2209. --WHERE bd.page_type IN (''DATA_PAGE'', ''INDEX_PAGE'')
  2210. GROUP BY database_id' + CASE WHEN @sqlmajorver >= 10 THEN ', numa_node' ELSE '' END + CASE WHEN @sqlmajorver >= 12 THEN ', is_in_bpool_extension' ELSE '' END + '
  2211. ORDER BY total_pages_MB DESC;'
  2212. EXECUTE sp_executesql @sqlcmd;
  2213. END
  2214. RAISERROR (N' |-Starting Memory Allocations from Memory Clerks', 10, 1) WITH NOWAIT
  2215. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], [type] AS Alloc_Type,
  2216. ' + 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'
  2217. ELSE 'SUM(pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb + awe_allocated_kb) AS Alloc_Mem_KB' END + '
  2218. FROM sys.dm_os_memory_clerks
  2219. WHERE type IN (''CACHESTORE_COLUMNSTOREOBJECTPOOL'',''CACHESTORE_CLRPROC'',''CACHESTORE_OBJCP'',''CACHESTORE_PHDR'',''CACHESTORE_SQLCP'',''CACHESTORE_TEMPTABLES'',
  2220. ''MEMORYCLERK_SQLBUFFERPOOL'',''MEMORYCLERK_SQLCLR'',''MEMORYCLERK_SQLGENERAL'',''MEMORYCLERK_SQLLOGPOOL'',''MEMORYCLERK_SQLOPTIMIZER'',
  2221. ''MEMORYCLERK_SQLQUERYCOMPILE'',''MEMORYCLERK_SQLQUERYEXEC'',''MEMORYCLERK_SQLQUERYPLAN'',''MEMORYCLERK_SQLSTORENG'',''MEMORYCLERK_XTP'',
  2222. ''OBJECTSTORE_LOCK_MANAGER'',''OBJECTSTORE_SNI_PACKET'',''USERSTORE_DBMETADATA'',''USERSTORE_OBJPERM'')
  2223. GROUP BY [type]
  2224. UNION ALL
  2225. SELECT ''Memory_checks'' AS [Category], ''Others'' AS Alloc_Type,
  2226. ' + CASE WHEN @sqlmajorver < 11 THEN 'SUM(single_pages_kb + multi_pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb) AS Alloc_Mem_KB'
  2227. ELSE 'SUM(pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb) AS Alloc_Mem_KB' END + '
  2228. FROM sys.dm_os_memory_clerks
  2229. WHERE type NOT IN (''CACHESTORE_COLUMNSTOREOBJECTPOOL'',''CACHESTORE_CLRPROC'',''CACHESTORE_OBJCP'',''CACHESTORE_PHDR'',''CACHESTORE_SQLCP'',''CACHESTORE_TEMPTABLES'',
  2230. ''MEMORYCLERK_SQLBUFFERPOOL'',''MEMORYCLERK_SQLCLR'',''MEMORYCLERK_SQLGENERAL'',''MEMORYCLERK_SQLLOGPOOL'',''MEMORYCLERK_SQLOPTIMIZER'',
  2231. ''MEMORYCLERK_SQLQUERYCOMPILE'',''MEMORYCLERK_SQLQUERYEXEC'',''MEMORYCLERK_SQLQUERYPLAN'',''MEMORYCLERK_SQLSTORENG'',''MEMORYCLERK_XTP'',
  2232. ''OBJECTSTORE_LOCK_MANAGER'',''OBJECTSTORE_SNI_PACKET'',''USERSTORE_DBMETADATA'',''USERSTORE_OBJPERM'')
  2233. ORDER BY Alloc_Mem_KB'
  2234. EXECUTE sp_executesql @sqlcmd;
  2235. IF @sqlmajorver >= 12
  2236. BEGIN
  2237. SET @sqlcmd = N'SELECT @xtpOUT = COUNT(*) FROM sys.dm_db_xtp_memory_consumers';
  2238. SET @params = N'@xtpOUT int OUTPUT';
  2239. EXECUTE sp_executesql @sqlcmd, @params, @xtpOUT = @xtp OUTPUT;
  2240. IF @xtp > 0
  2241. BEGIN
  2242. RAISERROR (N' |-Starting Memory Consumers from In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  2243. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''InMemory_Consumers'' AS Alloc_Type,
  2244. OBJECT_NAME([object_id]) AS [Object_Name], memory_consumer_type_desc, [object_id], index_id,
  2245. allocated_bytes/(1024*1024) AS Allocated_MB, used_bytes/(1024*1024) AS Used_MB,
  2246. CASE WHEN used_bytes IS NULL THEN ''used_bytes_is_varheap_only'' ELSE '''' END AS [Comment]
  2247. FROM sys.dm_db_xtp_memory_consumers
  2248. WHERE [object_id] > 0
  2249. ORDER BY Allocated_MB DESC' -- Only user objects; system objects are negative numbers
  2250. EXECUTE sp_executesql @sqlcmd;
  2251. RAISERROR (N' |-Starting Memory Allocations from In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  2252. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''InMemory_Alloc'' AS Alloc_Type,
  2253. SUM(allocated_bytes)/(1024*1024) AS total_allocated_MB, SUM(used_bytes)/(1024*1024) AS total_used_MB
  2254. FROM sys.dm_db_xtp_memory_consumers
  2255. ORDER BY total_allocated_MB DESC'
  2256. EXECUTE sp_executesql @sqlcmd;
  2257. END;
  2258. END;
  2259. END;
  2260. RAISERROR (N' |-Starting OOM', 10, 1) WITH NOWAIT
  2261. IF (SELECT COUNT([TIMESTAMP]) FROM sys.dm_os_ring_buffers (NOLOCK) WHERE ring_buffer_type = N'RING_BUFFER_OOM') > 0
  2262. BEGIN
  2263. SELECT 'Memory_checks' AS [Category], 'OOM_Notifications' AS [Information],
  2264. 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())
  2265. ELSE DATEADD(s, ([TIMESTAMP]/1000) - (si.ms_ticks/1000), GETDATE()) END AS Event_Time,
  2266. record.value('(./Record/OOM/Action)[1]', 'varchar(50)') AS [Action],
  2267. record.value('(./Record/OOM/Resources)[1]', 'int') AS [Resources],
  2268. record.value('(./Record/OOM/Task)[1]', 'varchar(20)') AS [Task],
  2269. record.value('(./Record/OOM/Pool)[1]', 'int') AS [PoolID],
  2270. rgrp.name AS [PoolName],
  2271. record.value('(./Record/MemoryRecord/MemoryUtilization)[1]', 'bigint') AS [MemoryUtilPct],
  2272. record.value('(./Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint')/1024 AS [Total_Physical_Mem_MB],
  2273. record.value('(./Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint')/1024 AS [Avail_Physical_Mem_MB],
  2274. record.value('(./Record/MemoryRecord/AvailableVirtualAddressSpace)[1]', 'bigint')/1024 AS [Avail_VAS_MB],
  2275. record.value('(./Record/MemoryRecord/TotalPageFile)[1]', 'bigint')/1024 AS [Total_Pagefile_MB],
  2276. record.value('(./Record/MemoryRecord/AvailablePageFile)[1]', 'bigint')/1024 AS [Avail_Pagefile_MB]
  2277. FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  2278. FROM sys.dm_os_ring_buffers (NOLOCK)
  2279. WHERE ring_buffer_type = N'RING_BUFFER_OOM') AS x
  2280. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2281. LEFT JOIN sys.resource_governor_resource_pools rgrp (NOLOCK) ON rgrp.pool_id = record.value('(./Record/OOM/Pool)[1]', 'int')
  2282. --WHERE CASE WHEN x.[timestamp] BETWEEN -2147483648 AND 2147483648 THEN DATEADD(ms, x.[timestamp] - si.ms_ticks, GETDATE())
  2283. -- ELSE DATEADD(s, (x.[timestamp]/1000) - (si.ms_ticks/1000), GETDATE()) END >= DATEADD(hh, -12, GETDATE())
  2284. ORDER BY 2 DESC;
  2285. END
  2286. ELSE
  2287. BEGIN
  2288. SELECT 'Memory_checks' AS [Category], 'OOM_Notifications' AS [Information], '[OK]' AS Comment
  2289. END;
  2290. --------------------------------------------------------------------------------------------------------------------------------
  2291. -- LPIM subsection
  2292. --------------------------------------------------------------------------------------------------------------------------------
  2293. RAISERROR (N' |-Starting LPIM', 10, 1) WITH NOWAIT
  2294. DECLARE @lpim bit, @lognumber int, @logcount int
  2295. IF ((@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13)
  2296. BEGIN
  2297. SET @sqlcmd = N'SELECT @lpimOUT = CASE WHEN sql_memory_model = 2 THEN 1 ELSE 0 END FROM sys.dm_os_sys_info';
  2298. SET @params = N'@lpimOUT bit OUTPUT';
  2299. EXECUTE sp_executesql @sqlcmd, @params, @lpimOUT=@lpim OUTPUT;
  2300. END
  2301. ELSE IF ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13)
  2302. BEGIN
  2303. SET @sqlcmd = N'SELECT @lpimOUT = CASE WHEN locked_page_allocations_kb > 0 THEN 1 ELSE 0 END FROM sys.dm_os_process_memory (NOLOCK)'
  2304. SET @params = N'@lpimOUT bit OUTPUT';
  2305. EXECUTE sp_executesql @sqlcmd, @params, @lpimOUT=@lpim OUTPUT
  2306. END
  2307. ELSE IF @sqlmajorver = 9
  2308. BEGIN
  2309. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2310. OR ISNULL(IS_SRVROLEMEMBER(N'securityadmin'), 0) = 1 -- Is securityadmin
  2311. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_readerrorlog') > 0
  2312. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_readerrorlog') > 0
  2313. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_enumerrorlogs') > 0)
  2314. BEGIN
  2315. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimdbcc'))
  2316. DROP TABLE #lpimdbcc;
  2317. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimdbcc'))
  2318. CREATE TABLE #lpimdbcc (logdate DATETIME, spid VARCHAR(50), logmsg VARCHAR(4000))
  2319. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimavail_logs'))
  2320. DROP TABLE #lpimavail_logs;
  2321. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimavail_logs'))
  2322. CREATE TABLE #lpimavail_logs (lognum int, logdate DATETIME, logsize int)
  2323. -- Get the number of available logs
  2324. INSERT INTO #lpimavail_logs
  2325. EXEC xp_enumerrorlogs
  2326. SELECT @lognumber = MIN(lognum) FROM #lpimavail_logs WHERE DATEADD(dd, DATEDIFF(dd, 0, logdate), 0) >= DATEADD(dd, DATEDIFF(dd, 0, @StartDate), 0)
  2327. SELECT @logcount = ISNULL(MAX(lognum),@lognumber) FROM #lpimavail_logs WHERE DATEADD(dd, DATEDIFF(dd, 0, logdate), 0) >= DATEADD(dd, DATEDIFF(dd, 0, @StartDate), 0)
  2328. IF @lognumber IS NULL
  2329. BEGIN
  2330. SELECT @ErrorMessage = '[WARNING: Could not retrieve information about Locked pages usage in SQL Server 2005]'
  2331. RAISERROR (@ErrorMessage, 16, 1);
  2332. END
  2333. ELSE
  2334. WHILE @lognumber < @logcount
  2335. BEGIN
  2336. -- Cycle through sql error logs (Cannot use Large Page Extensions: lock memory privilege was not granted)
  2337. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''Using locked pages for buffer pool'''
  2338. BEGIN TRY
  2339. INSERT INTO #lpimdbcc (logdate, spid, logmsg)
  2340. EXECUTE (@sqlcmd);
  2341. END TRY
  2342. BEGIN CATCH
  2343. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2344. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  2345. RAISERROR (@ErrorMessage, 16, 1);
  2346. END CATCH
  2347. -- Next log
  2348. --SET @lognumber = @lognumber + 1
  2349. SELECT @lognumber = MIN(lognum) FROM #lpimavail_logs WHERE lognum > @lognumber
  2350. END
  2351. IF (SELECT COUNT(*) FROM #lpimdbcc) > 0
  2352. BEGIN
  2353. SET @lpim = 1
  2354. END
  2355. ELSE IF (SELECT COUNT(*) FROM #lpimdbcc) = 0 AND @lognumber IS NOT NULL
  2356. BEGIN
  2357. SET @lpim = 0
  2358. END;
  2359. DROP TABLE #lpimavail_logs;
  2360. DROP TABLE #lpimdbcc;
  2361. END
  2362. ELSE
  2363. BEGIN
  2364. RAISERROR('[WARNING: Only a sysadmin or securityadmin can run the "Locked_pages" check. Bypassing check]', 16, 1, N'permissions')
  2365. 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')
  2366. --RETURN
  2367. END;
  2368. END
  2369. IF @lpim = 0 AND CONVERT(DECIMAL(3,1), @winver) < 6.0 AND @arch = 64
  2370. BEGIN
  2371. 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]
  2372. END
  2373. ELSE IF @lpim = 1 AND CONVERT(DECIMAL(3,1), @winver) < 6.0 AND @arch = 64
  2374. BEGIN
  2375. 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]
  2376. END
  2377. ELSE IF @lpim = 1 AND CONVERT(DECIMAL(3,1), @winver) >= 6.0 AND @arch = 64
  2378. BEGIN
  2379. 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]
  2380. END
  2381. ELSE IF @lpim IS NULL
  2382. BEGIN
  2383. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[Could_not_retrieve_information]' AS [Deviation]
  2384. END
  2385. ELSE
  2386. BEGIN
  2387. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[Not_used]' AS [Deviation]
  2388. END;
  2389. --------------------------------------------------------------------------------------------------------------------------------
  2390. -- Pagefile subsection
  2391. --------------------------------------------------------------------------------------------------------------------------------
  2392. RAISERROR (N'|-Starting Pagefile Checks', 10, 1) WITH NOWAIT
  2393. DECLARE @pf_value tinyint--, @RegKey NVARCHAR(255)
  2394. DECLARE @pagefile bigint, @freepagefile bigint, @paged bigint
  2395. DECLARE @tbl_pf_value TABLE (Value VARCHAR(25), Data VARCHAR(50))
  2396. IF @sqlmajorver = 9
  2397. BEGIN
  2398. SET @sqlcmd = N'SELECT @pagefileOUT = (t1.record.value(''(./Record/MemoryRecord/TotalPageFile)[1]'', ''bigint'')-t1.record.value(''(./Record/MemoryRecord/TotalPhysicalMemory)[1]'', ''bigint''))/1024,
  2399. @freepagefileOUT = (t1.record.value(''(./Record/MemoryRecord/AvailablePageFile)[1]'', ''bigint'')-t1.record.value(''(./Record/MemoryRecord/AvailablePhysicalMemory)[1]'', ''bigint''))/1024,
  2400. @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
  2401. FROM (SELECT MAX([TIMESTAMP]) AS [TIMESTAMP], CONVERT(xml, record) AS record
  2402. FROM sys.dm_os_ring_buffers (NOLOCK)
  2403. WHERE ring_buffer_type = N''RING_BUFFER_RESOURCE_MONITOR''
  2404. AND record LIKE ''%RESOURCE_MEMPHYSICAL%''
  2405. GROUP BY record) AS t1';
  2406. END
  2407. ELSE
  2408. BEGIN
  2409. SET @sqlcmd = N'SELECT @pagefileOUT = (total_page_file_kb-total_physical_memory_kb)/1024,
  2410. @freepagefileOUT = (available_page_file_kb-available_physical_memory_kb)/1024,
  2411. @pagedOUT = ((total_page_file_kb-available_page_file_kb)/total_page_file_kb)
  2412. FROM sys.dm_os_sys_memory (NOLOCK)';
  2413. END
  2414. SET @params = N'@pagefileOUT bigint OUTPUT, @freepagefileOUT bigint OUTPUT, @pagedOUT bigint OUTPUT';
  2415. EXECUTE sp_executesql @sqlcmd, @params, @pagefileOUT=@pagefile OUTPUT, @freepagefileOUT=@freepagefile OUTPUT, @pagedOUT=@paged OUTPUT;
  2416. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  2417. BEGIN
  2418. BEGIN TRY
  2419. SELECT @RegKey = N'System\CurrentControlSet\Control\Session Manager\Memory Management'
  2420. INSERT INTO @tbl_pf_value
  2421. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'PagingFiles', NO_OUTPUT
  2422. END TRY
  2423. BEGIN CATCH
  2424. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2425. SELECT @ErrorMessage = 'Pagefile subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  2426. RAISERROR (@ErrorMessage, 16, 1);
  2427. END CATCH
  2428. END
  2429. ELSE
  2430. BEGIN
  2431. RAISERROR('[WARNING: Missing permissions for full "Pagefile" checks. Bypassing System managed pagefile check]', 16, 1, N'sysadmin')
  2432. --RETURN
  2433. END;
  2434. IF (SELECT COUNT(*) FROM @tbl_pf_value) > 0
  2435. BEGIN
  2436. SELECT @pf_value = CASE WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data = '') > 0 THEN 1
  2437. WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data = '?:\pagefile.sys') > 0 THEN 2
  2438. WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data LIKE '%:\pagefile.sys 0 0%') > 0 THEN 3
  2439. ELSE 0 END
  2440. FROM @tbl_pf_value
  2441. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_management' AS [Check],
  2442. CASE WHEN @pf_value = 1 THEN '[WARNING: No pagefile is configured]'
  2443. WHEN @pf_value = 2 THEN '[WARNING: Pagefile is managed automatically on ALL drives]'
  2444. WHEN @pf_value = 3 THEN '[WARNING: Pagefile is managed automatically]'
  2445. ELSE '[OK]' END AS [Deviation]
  2446. END
  2447. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_free_space' AS [Check],
  2448. CASE WHEN @freepagefile <= 150 THEN '[WARNING: Pagefile free space is dangerously low. Please revise Pagefile settings]'
  2449. WHEN (@freepagefile*100)/@pagefile <= 10 THEN '[WARNING: Less than 10 percent of Pagefile is available. Please revise Pagefile settings]'
  2450. WHEN (@freepagefile*100)/@pagefile <= 30 THEN '[INFORMATION: Less than 30 percent of Pagefile is available]'
  2451. ELSE '[OK]' END AS [Deviation],
  2452. @pagefile AS total_pagefile_MB, @freepagefile AS available_pagefile_MB;
  2453. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_minimum_size' AS [Check],
  2454. 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]'
  2455. 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]'
  2456. WHEN @winver <> '5.2' THEN '[NA]'
  2457. ELSE '[OK]' END AS [Deviation],
  2458. @pagefile AS total_pagefile_MB;
  2459. SELECT 'Pagefile_checks' AS [Category], 'Process_paged_out' AS [Check],
  2460. CASE WHEN @paged > 0 THEN '[WARNING: Part of SQL Server process memory has been paged out. Please revise LPIM settings]'
  2461. ELSE '[OK]' END AS [Deviation],
  2462. @paged AS paged_out_MB;
  2463. IF @ptochecks = 1
  2464. RAISERROR (N'|-Starting I/O Checks', 10, 1) WITH NOWAIT
  2465. --------------------------------------------------------------------------------------------------------------------------------
  2466. -- I/O stall in database files over 50% of cumulative sampled time or I/O latencies over 20ms in the last 5s subsection
  2467. -- io_stall refers to user processes waited for I/O. This number can be much greater than the sample_ms.
  2468. -- Might indicate that your I/O has insufficient service capabilities (HBA queue depths, reduced throughput, etc).
  2469. --------------------------------------------------------------------------------------------------------------------------------
  2470. IF @ptochecks = 1
  2471. BEGIN
  2472. RAISERROR (N' |-Starting I/O Stall subsection (wait for 5s)', 10, 1) WITH NOWAIT
  2473. DECLARE @mincol DATETIME, @maxcol DATETIME
  2474. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  2475. DROP TABLE #tmp_dm_io_virtual_file_stats;
  2476. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  2477. 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),
  2478. [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,
  2479. [num_of_bytes_written] bigint,[io_stall_write_ms] bigint,[io_stall] bigint,[size_on_disk_bytes] bigint,
  2480. CONSTRAINT PK_dm_io_virtual_file_stats PRIMARY KEY CLUSTERED(database_id, [file_id], [retrieval_time]));
  2481. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  2482. DROP TABLE #tblIOStall;
  2483. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  2484. CREATE TABLE #tblIOStall (database_id int, [file_id] int, [DBName] sysname, [logical_file_name] NVARCHAR(255), [type_desc] NVARCHAR(60),
  2485. [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,
  2486. 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,
  2487. avg_io_stall_write_pct int, cumulative_io_stall_write_pct int, cumulative_sample_HH int, io_stall_pct_of_cumulative_sample int,
  2488. CONSTRAINT PK_IOStall PRIMARY KEY CLUSTERED(database_id, [file_id]));
  2489. SELECT @mincol = GETDATE()
  2490. INSERT INTO #tmp_dm_io_virtual_file_stats
  2491. SELECT @mincol, f.database_id, f.[file_id], DB_NAME(f.database_id), f.name AS logical_file_name, f.type_desc,
  2492. CAST (CASE
  2493. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2494. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2495. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2496. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2497. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2498. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2499. ELSE f.physical_name
  2500. END AS NVARCHAR(255)) AS physical_location,
  2501. fs.[sample_ms],fs.[num_of_reads],fs.[num_of_bytes_read],fs.[io_stall_read_ms],fs.[num_of_writes],
  2502. fs.[num_of_bytes_written],fs.[io_stall_write_ms],fs.[io_stall],fs.[size_on_disk_bytes]
  2503. FROM sys.dm_io_virtual_file_stats (default, default) AS fs
  2504. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id]
  2505. WAITFOR DELAY '00:00:05' -- wait 5s between pooling
  2506. SELECT @maxcol = GETDATE()
  2507. INSERT INTO #tmp_dm_io_virtual_file_stats
  2508. SELECT @maxcol, f.database_id, f.[file_id], DB_NAME(f.database_id), f.name AS logical_file_name, f.type_desc,
  2509. CAST (CASE
  2510. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2511. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2512. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2513. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2514. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2515. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2516. ELSE f.physical_name
  2517. END AS NVARCHAR(255)) AS physical_location,
  2518. fs.[sample_ms],fs.[num_of_reads],fs.[num_of_bytes_read],fs.[io_stall_read_ms],fs.[num_of_writes],
  2519. fs.[num_of_bytes_written],fs.[io_stall_write_ms],fs.[io_stall],fs.[size_on_disk_bytes]
  2520. FROM sys.dm_io_virtual_file_stats (default, default) AS fs
  2521. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id]
  2522. ;WITH cteFileStats1 AS (SELECT database_id,[file_id],[DBName],[logical_file_name],[type_desc],
  2523. [physical_location],[sample_ms],[num_of_reads],[num_of_bytes_read],[io_stall_read_ms],[num_of_writes],
  2524. [num_of_bytes_written],[io_stall_write_ms],[io_stall],[size_on_disk_bytes]
  2525. FROM #tmp_dm_io_virtual_file_stats WHERE [retrieval_time] = @mincol),
  2526. cteFileStats2 AS (SELECT database_id,[file_id],[DBName],[logical_file_name],[type_desc],
  2527. [physical_location],[sample_ms],[num_of_reads],[num_of_bytes_read],[io_stall_read_ms],[num_of_writes],
  2528. [num_of_bytes_written],[io_stall_write_ms],[io_stall],[size_on_disk_bytes]
  2529. FROM #tmp_dm_io_virtual_file_stats WHERE [retrieval_time] = @maxcol)
  2530. INSERT INTO #tblIOStall
  2531. SELECT t1.database_id, t1.[file_id], t1.[DBName], t1.logical_file_name, t1.type_desc, t1.physical_location,
  2532. t1.size_on_disk_bytes/1024/1024 AS size_on_disk_Mbytes,
  2533. (t2.num_of_reads-t1.num_of_reads) AS num_of_reads,
  2534. (t2.num_of_writes-t1.num_of_writes) AS num_of_writes,
  2535. (t2.num_of_bytes_read-t1.num_of_bytes_read)/1024 AS num_of_KBytes_read,
  2536. (t2.num_of_bytes_written-t1.num_of_bytes_written)/1024 AS num_of_KBytes_written,
  2537. (t2.io_stall-t1.io_stall) AS io_stall_ms,
  2538. (t2.io_stall_read_ms-t1.io_stall_read_ms) AS io_stall_read_ms,
  2539. (t2.io_stall_write_ms-t1.io_stall_write_ms) AS io_stall_write_ms,
  2540. ((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,
  2541. ((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,
  2542. ((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,
  2543. ((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,
  2544. ((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,
  2545. ((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,
  2546. ABS((t2.sample_ms/1000)/60/60) AS cumulative_sample_HH,
  2547. ((t2.io_stall/1000/60)*100)/(ABS((t2.sample_ms/1000)/60)) AS io_stall_pct_of_cumulative_sample
  2548. FROM cteFileStats1 t1 INNER JOIN cteFileStats2 t2 ON t1.database_id = t2.database_id AND t1.[file_id] = t2.[file_id]
  2549. IF (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE avg_read_latency_ms >= 20) > 0
  2550. OR (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE avg_write_latency_ms >= 20) > 0
  2551. BEGIN
  2552. 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]
  2553. 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,
  2554. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2555. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2556. 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
  2557. FROM #tblIOStall
  2558. WHERE avg_read_latency_ms >= 20 OR avg_write_latency_ms >= 20
  2559. ORDER BY avg_read_latency_ms DESC, avg_write_latency_ms DESC, [DBName], [type_desc], [logical_file_name]
  2560. END
  2561. ELSE IF (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE io_stall_pct_of_cumulative_sample > 50) > 0
  2562. BEGIN
  2563. 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]
  2564. 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,
  2565. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2566. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2567. 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
  2568. FROM #tblIOStall
  2569. WHERE io_stall_pct_of_cumulative_sample > 50
  2570. ORDER BY io_stall_pct_of_cumulative_sample DESC, [DBName], [type_desc], [logical_file_name]
  2571. END
  2572. ELSE
  2573. BEGIN
  2574. SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Check], '[OK]' AS [Deviation]
  2575. /*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,
  2576. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2577. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2578. 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
  2579. FROM #tblIOStall
  2580. ORDER BY [DBName], [type_desc], [logical_file_name]*/
  2581. END;
  2582. END;
  2583. --------------------------------------------------------------------------------------------------------------------------------
  2584. -- Pending disk I/O Requests subsection
  2585. -- Indicate that your I/O has insufficient service capabilities (HBA queue depths, reduced throughput, etc).
  2586. --------------------------------------------------------------------------------------------------------------------------------
  2587. IF @ptochecks = 1
  2588. BEGIN
  2589. RAISERROR (N' |-Starting Pending disk I/O Requests subsection (wait for a max of 5s)', 10, 1) WITH NOWAIT
  2590. DECLARE @IOCnt tinyint
  2591. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  2592. DROP TABLE #tblPendingIOReq;
  2593. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  2594. 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));
  2595. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  2596. DROP TABLE #tblPendingIO;
  2597. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  2598. CREATE TABLE #tblPendingIO (database_id int, [file_id] int, [DBName] sysname, [logical_file_name] NVARCHAR(255), [type_desc] NVARCHAR(60),
  2599. [physical_location] NVARCHAR(260), io_stall_min int, io_stall_read_min int, io_stall_write_min int, avg_read_latency_ms int,
  2600. avg_write_latency_ms int, io_stall_read_pct int, io_stall_write_pct int, sampled_HH int,
  2601. 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),
  2602. scheduler_id int, pending_disk_io_count int, work_queue_count bigint);
  2603. SET @IOCnt = 1
  2604. WHILE @IOCnt < 5
  2605. BEGIN
  2606. INSERT INTO #tblPendingIOReq
  2607. SELECT io_completion_request_address, io_handle, io_type, io_pending, io_pending_ms_ticks, scheduler_address
  2608. FROM sys.dm_io_pending_io_requests;
  2609. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 1
  2610. BREAK
  2611. WAITFOR DELAY '00:00:01' -- wait 1s between pooling
  2612. SET @IOCnt = @IOCnt + 1
  2613. END;
  2614. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 0
  2615. BEGIN
  2616. INSERT INTO #tblPendingIO
  2617. 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,
  2618. CAST (CASE
  2619. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2620. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2621. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2622. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2623. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2624. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2625. ELSE f.physical_name
  2626. END AS NVARCHAR(255)) AS physical_location,
  2627. fs.io_stall/1000/60 AS io_stall_min,
  2628. fs.io_stall_read_ms/1000/60 AS io_stall_read_min,
  2629. fs.io_stall_write_ms/1000/60 AS io_stall_write_min,
  2630. (fs.io_stall_read_ms / (1.0 + fs.num_of_reads)) AS avg_read_latency_ms,
  2631. (fs.io_stall_write_ms / (1.0 + fs.num_of_writes)) AS avg_write_latency_ms,
  2632. ((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,
  2633. ((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,
  2634. ABS((fs.sample_ms/1000)/60/60) AS 'sample_HH',
  2635. ((fs.io_stall/1000/60)*100)/(ABS((fs.sample_ms/1000)/60))AS 'io_stall_pct_of_overall_sample',
  2636. pio.io_completion_request_address, pio.io_handle, pio.io_type, pio.io_pending,
  2637. pio.io_pending_ms_ticks, pio.scheduler_address, os.scheduler_id, os.pending_disk_io_count, os.work_queue_count
  2638. FROM #tblPendingIOReq AS pio
  2639. INNER JOIN sys.dm_io_virtual_file_stats (NULL,NULL) AS fs ON fs.file_handle = pio.io_handle
  2640. INNER JOIN sys.dm_os_schedulers AS os ON pio.scheduler_address = os.scheduler_address
  2641. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id];
  2642. END;
  2643. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 0
  2644. BEGIN
  2645. 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]
  2646. 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,
  2647. 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,
  2648. io_completion_request_address, io_type, CASE WHEN io_pending = 1 THEN 'Pending_Context_Switching' ELSE 'Pending_WindowsOS' END AS io_pending_type,
  2649. io_pending_ms_ticks, scheduler_address, scheduler_id, pending_disk_io_count, work_queue_count
  2650. FROM #tblPendingIO
  2651. ORDER BY scheduler_address, [DBName], [type_desc], [logical_file_name]
  2652. END
  2653. ELSE
  2654. BEGIN
  2655. SELECT 'IO_checks' AS [Category], 'Pending_IO' AS [Check], '[OK]' AS [Deviation]
  2656. END;
  2657. END;
  2658. RAISERROR (N'|-Starting Server Checks', 10, 1) WITH NOWAIT
  2659. --------------------------------------------------------------------------------------------------------------------------------
  2660. -- Power plan subsection
  2661. --------------------------------------------------------------------------------------------------------------------------------
  2662. RAISERROR (N' |-Starting Power plan', 10, 1) WITH NOWAIT
  2663. DECLARE @planguid NVARCHAR(64), @powerkey NVARCHAR(255)
  2664. --SELECT @powerkey = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel\NameSpace\{025A5937-A6BE-4686-A844-36FE4BEC8B6D}'
  2665. --SELECT @powerkey = 'SYSTEM\CurrentControlSet\Control\Power\User\Default\PowerSchemes'
  2666. SELECT @powerkey = 'SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes'
  2667. IF CONVERT(DECIMAL(3,1), @winver) >= 6.0
  2668. BEGIN
  2669. BEGIN TRY
  2670. --EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @powerkey, 'PreferredPlan', @planguid OUTPUT, NO_OUTPUT
  2671. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @powerkey, 'ActivePowerScheme', @planguid OUTPUT, NO_OUTPUT
  2672. END TRY
  2673. BEGIN CATCH
  2674. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2675. SELECT @ErrorMessage = 'Power plan subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  2676. RAISERROR (@ErrorMessage, 16, 1);
  2677. END CATCH
  2678. END
  2679. -- http://support.microsoft.com/kb/935799/en-us
  2680. IF @winver IS NULL
  2681. BEGIN
  2682. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Check], '[WARNING: Could not determine Windows version for check]' AS [Deviation]
  2683. END
  2684. ELSE IF @planguid IS NOT NULL AND @planguid <> '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
  2685. BEGIN
  2686. 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]
  2687. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Information], CASE WHEN @planguid = '381b4222-f694-41f0-9685-ff5bb260df2e' THEN 'Balanced'
  2688. WHEN @planguid = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c' THEN 'High Performance'
  2689. WHEN @planguid = 'a1841308-3541-4fab-bc81-f71556f20b4a' THEN 'Power Saver'
  2690. ELSE 'Other' END AS [Power_Plan]
  2691. END
  2692. ELSE IF @planguid IS NOT NULL AND @planguid = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
  2693. BEGIN
  2694. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Check], '[OK]' AS [Deviation]
  2695. END;
  2696. --------------------------------------------------------------------------------------------------------------------------------
  2697. -- Disk Partition alignment offset < 64KB subsection
  2698. --------------------------------------------------------------------------------------------------------------------------------
  2699. RAISERROR (N' |-Starting Disk Partition alignment offset < 64KB', 10, 1) WITH NOWAIT
  2700. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  2701. BEGIN
  2702. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2703. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2704. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  2705. AND (SELECT COUNT(l.name)
  2706. FROM sys.server_permissions p JOIN sys.server_principals l
  2707. ON p.grantee_principal_id = l.principal_id
  2708. AND p.class = 100 -- Server
  2709. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  2710. AND l.is_disabled = 0
  2711. AND p.permission_name = 'ALTER SETTINGS'
  2712. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  2713. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2714. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  2715. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  2716. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  2717. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  2718. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  2719. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  2720. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  2721. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  2722. BEGIN
  2723. DECLARE @diskpart int
  2724. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  2725. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  2726. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  2727. RAISERROR (' |-Configuration options set for Disk partition alignment offset check', 10, 1) WITH NOWAIT
  2728. IF @sao = 0
  2729. BEGIN
  2730. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  2731. END
  2732. IF @xcmd = 0
  2733. BEGIN
  2734. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  2735. END
  2736. IF @ole = 0
  2737. BEGIN
  2738. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  2739. END
  2740. DECLARE @output_hw_tot_diskpart TABLE ([PS_OUTPUT] VARCHAR(2048));
  2741. DECLARE @output_hw_format_diskpart TABLE ([volid] smallint IDENTITY(1,1), [HD_Partition] VARCHAR(50) NULL, StartingOffset bigint NULL)
  2742. IF @custompath IS NULL
  2743. BEGIN
  2744. IF @sqlmajorver < 11
  2745. BEGIN
  2746. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  2747. SET @path = @path + '\LOG'
  2748. END
  2749. ELSE
  2750. BEGIN
  2751. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  2752. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  2753. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  2754. END
  2755. -- Create COM object with FSO
  2756. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  2757. IF @OLEResult <> 0
  2758. BEGIN
  2759. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2760. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2761. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2762. END
  2763. ELSE
  2764. BEGIN
  2765. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  2766. IF @OLEResult <> 0
  2767. BEGIN
  2768. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2769. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  2770. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2771. END
  2772. ELSE
  2773. BEGIN
  2774. IF @existout <> 1
  2775. BEGIN
  2776. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  2777. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  2778. END
  2779. END
  2780. EXEC @OLEResult = sp_OADestroy @FSO
  2781. END
  2782. END
  2783. ELSE
  2784. BEGIN
  2785. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  2786. END
  2787. SET @FileName = @path + '\checkbp_diskpart_' + RTRIM(@server) + '.ps1'
  2788. EXEC master.dbo.xp_fileexist @FileName, @existout out
  2789. IF @existout = 0
  2790. BEGIN -- Scan for local disks
  2791. SET @Text1 = '[string] $serverName = ''localhost''
  2792. $partitions = Get-WmiObject -computername $serverName -query "SELECT * FROM Win32_DiskPartition"
  2793. foreach ($partition in $partitions)
  2794. {
  2795. [string] $diskpart = "{0}_{1};{2}" -f $partition.DiskIndex,$partition.Index,$partition.StartingOffset
  2796. Write-Output $diskpart
  2797. }
  2798. '
  2799. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  2800. IF @OLEResult <> 0
  2801. BEGIN
  2802. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2803. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2804. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2805. END
  2806. --Open file
  2807. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  2808. IF @OLEResult <> 0
  2809. BEGIN
  2810. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2811. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  2812. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2813. END
  2814. ELSE
  2815. BEGIN
  2816. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  2817. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  2818. END
  2819. --Write Text1
  2820. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  2821. IF @OLEResult <> 0
  2822. BEGIN
  2823. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2824. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  2825. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2826. END
  2827. EXEC @OLEResult = sp_OADestroy @FileID
  2828. EXEC @OLEResult = sp_OADestroy @FS
  2829. END
  2830. ELSE
  2831. BEGIN
  2832. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  2833. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  2834. END
  2835. IF @psver = 1
  2836. BEGIN
  2837. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  2838. END
  2839. ELSE
  2840. BEGIN
  2841. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  2842. END;
  2843. INSERT INTO @output_hw_tot_diskpart
  2844. EXEC master.dbo.xp_cmdshell @CMD
  2845. SET @CMD = 'del /Q "' + @FileName + '"'
  2846. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  2847. INSERT INTO @output_hw_format_diskpart ([HD_Partition],StartingOffset)
  2848. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  2849. 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)
  2850. FROM @output_hw_tot_diskpart
  2851. WHERE [PS_OUTPUT] IS NOT NULL;
  2852. SET @CMD2 = 'del ' + @FileName
  2853. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  2854. IF @xcmd = 0
  2855. BEGIN
  2856. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  2857. END
  2858. IF @ole = 0
  2859. BEGIN
  2860. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  2861. END
  2862. IF @sao = 0
  2863. BEGIN
  2864. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  2865. END;
  2866. ;WITH diskpartcte (StartingOffset) AS (
  2867. SELECT StartingOffset
  2868. FROM @output_hw_format_diskpart
  2869. WHERE StartingOffset IS NOT NULL OR LEN(StartingOffset) > 0)
  2870. SELECT @diskpart = CASE WHEN (SELECT COUNT(*) FROM diskpartcte) = 0 THEN NULL ELSE COUNT(cte1.[StartingOffset]) END
  2871. FROM diskpartcte cte1
  2872. WHERE cte1.[StartingOffset] < 65536;
  2873. IF @diskpart > 0 AND @diskpart IS NOT NULL
  2874. BEGIN
  2875. 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]
  2876. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Information], LEFT(t1.[HD_Partition],LEN(t1.[HD_Partition])-CHARINDEX('_',t1.[HD_Partition])) AS HD_Volume,
  2877. RIGHT(t1.[HD_Partition],LEN(t1.[HD_Partition])-CHARINDEX('_',t1.[HD_Partition])) AS [HD_Partition],
  2878. (t1.StartingOffset/1024) AS [StartingOffset_KB]
  2879. FROM @output_hw_format_diskpart t1
  2880. WHERE t1.StartingOffset IS NOT NULL OR LEN(t1.StartingOffset) > 0
  2881. ORDER BY t1.[HD_Partition]
  2882. OPTION (RECOMPILE);
  2883. END
  2884. ELSE IF @diskpart IS NULL
  2885. BEGIN
  2886. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Check], '[WARNING: Could not gather information on disk partition offset size]' AS [Deviation]
  2887. END
  2888. ELSE
  2889. BEGIN
  2890. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Check], '[OK]' AS [Deviation]
  2891. END;
  2892. END
  2893. ELSE
  2894. BEGIN
  2895. 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')
  2896. 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')
  2897. --RETURN
  2898. END
  2899. END
  2900. ELSE
  2901. BEGIN
  2902. 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')
  2903. --RETURN
  2904. END;
  2905. --------------------------------------------------------------------------------------------------------------------------------
  2906. -- NTFS block size in volumes that hold database files <> 64KB subsection
  2907. --------------------------------------------------------------------------------------------------------------------------------
  2908. RAISERROR (N' |-Starting NTFS block size in volumes that hold database files <> 64KB', 10, 1) WITH NOWAIT
  2909. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  2910. BEGIN
  2911. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2912. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2913. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  2914. AND (SELECT COUNT(l.name)
  2915. FROM sys.server_permissions p JOIN sys.server_principals l
  2916. ON p.grantee_principal_id = l.principal_id
  2917. AND p.class = 100 -- Server
  2918. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  2919. AND l.is_disabled = 0
  2920. AND p.permission_name = 'ALTER SETTINGS'
  2921. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  2922. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2923. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  2924. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  2925. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  2926. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  2927. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  2928. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  2929. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  2930. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  2931. BEGIN
  2932. DECLARE @ntfs int
  2933. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  2934. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  2935. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  2936. RAISERROR (' |-Configuration options set for NTFS Block size check', 10, 1) WITH NOWAIT
  2937. IF @sao = 0
  2938. BEGIN
  2939. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  2940. END
  2941. IF @xcmd = 0
  2942. BEGIN
  2943. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  2944. END
  2945. IF @ole = 0
  2946. BEGIN
  2947. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  2948. END
  2949. DECLARE @output_hw_tot_ntfs TABLE ([PS_OUTPUT] VARCHAR(2048));
  2950. DECLARE @output_hw_format_ntfs TABLE ([volid] smallint IDENTITY(1,1), [HD_Volume] NVARCHAR(2048) NULL, [NTFS_Block] NVARCHAR(8) NULL)
  2951. IF @custompath IS NULL
  2952. BEGIN
  2953. IF @sqlmajorver < 11
  2954. BEGIN
  2955. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  2956. SET @path = @path + '\LOG'
  2957. END
  2958. ELSE
  2959. BEGIN
  2960. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  2961. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  2962. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  2963. END
  2964. -- Create COM object with FSO
  2965. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  2966. IF @OLEResult <> 0
  2967. BEGIN
  2968. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2969. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2970. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2971. END
  2972. ELSE
  2973. BEGIN
  2974. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  2975. IF @OLEResult <> 0
  2976. BEGIN
  2977. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2978. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  2979. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2980. END
  2981. ELSE
  2982. BEGIN
  2983. IF @existout <> 1
  2984. BEGIN
  2985. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  2986. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  2987. END
  2988. END
  2989. EXEC @OLEResult = sp_OADestroy @FSO
  2990. END
  2991. END
  2992. ELSE
  2993. BEGIN
  2994. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  2995. END
  2996. SET @FileName = @path + '\checkbp_ntfs_' + RTRIM(@server) + '.ps1'
  2997. EXEC master.dbo.xp_fileexist @FileName, @existout out
  2998. IF @existout = 0
  2999. BEGIN -- Scan for local disks
  3000. SET @Text1 = '[string] $serverName = ''localhost''
  3001. $vols = Get-WmiObject -computername $serverName -query "select name, blocksize from Win32_Volume where Capacity <> NULL and DriveType = 3"
  3002. foreach($vol in $vols)
  3003. {
  3004. [string] $drive = "{0};{1}" -f $vol.name,$vol.blocksize
  3005. Write-Output $drive
  3006. } '
  3007. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3008. IF @OLEResult <> 0
  3009. BEGIN
  3010. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3011. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3012. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3013. END
  3014. --Open file
  3015. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3016. IF @OLEResult <> 0
  3017. BEGIN
  3018. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3019. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3020. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3021. END
  3022. ELSE
  3023. BEGIN
  3024. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3025. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3026. END
  3027. --Write Text1
  3028. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3029. IF @OLEResult <> 0
  3030. BEGIN
  3031. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3032. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3033. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3034. END
  3035. EXEC @OLEResult = sp_OADestroy @FileID
  3036. EXEC @OLEResult = sp_OADestroy @FS
  3037. END
  3038. ELSE
  3039. BEGIN
  3040. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3041. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3042. END
  3043. IF @psver = 1
  3044. BEGIN
  3045. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3046. END
  3047. ELSE
  3048. BEGIN
  3049. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3050. END;
  3051. INSERT INTO @output_hw_tot_ntfs
  3052. EXEC master.dbo.xp_cmdshell @CMD
  3053. SET @CMD = 'del /Q "' + @FileName + '"'
  3054. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3055. INSERT INTO @output_hw_format_ntfs ([HD_Volume],[NTFS_Block])
  3056. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3057. 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)
  3058. FROM @output_hw_tot_ntfs
  3059. WHERE [PS_OUTPUT] IS NOT NULL;
  3060. SET @CMD2 = 'del ' + @FileName
  3061. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3062. IF @xcmd = 0
  3063. BEGIN
  3064. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3065. END
  3066. IF @ole = 0
  3067. BEGIN
  3068. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3069. END
  3070. IF @sao = 0
  3071. BEGIN
  3072. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3073. END;
  3074. WITH ntfscte (physical_name, ntfsblock) AS (
  3075. SELECT DISTINCT(LEFT(physical_name, LEN(t2.HD_Volume))), [NTFS_Block]
  3076. FROM sys.master_files t1 INNER JOIN @output_hw_format_ntfs t2
  3077. ON LEFT(physical_name, LEN(t2.HD_Volume)) = t2.HD_Volume
  3078. WHERE [database_id] <> 32767 AND (t2.[NTFS_Block] IS NOT NULL OR LEN(t2.[NTFS_Block]) > 0)
  3079. )
  3080. SELECT @ntfs = CASE WHEN (SELECT COUNT(*) FROM ntfscte) = 0 THEN NULL ELSE COUNT(cte1.[ntfsblock]) END
  3081. FROM ntfscte cte1
  3082. WHERE cte1.[ntfsblock] <> 65536;
  3083. IF @ntfs > 0 AND @ntfs IS NOT NULL
  3084. BEGIN
  3085. 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]
  3086. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Information], t1.HD_Volume, (t1.[NTFS_Block]/1024) AS [NTFS_Block_Size_KB]
  3087. FROM (SELECT DISTINCT(LEFT(physical_name, LEN(t2.HD_Volume))) AS [HD_Volume], [NTFS_Block]
  3088. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format_ntfs t2
  3089. ON LEFT(physical_name, LEN(t2.HD_Volume)) = t2.HD_Volume
  3090. WHERE [database_id] <> 32767 AND (t2.[NTFS_Block] IS NOT NULL OR LEN(t2.[NTFS_Block]) > 0)) t1
  3091. ORDER BY t1.HD_Volume OPTION (RECOMPILE);
  3092. END
  3093. ELSE IF @ntfs IS NULL
  3094. BEGIN
  3095. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Check], '[WARNING: Could not gather information on NTFS block size]' AS [Deviation]
  3096. END
  3097. ELSE
  3098. BEGIN
  3099. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Check], '[OK]' AS [Deviation]
  3100. END;
  3101. END
  3102. ELSE
  3103. BEGIN
  3104. 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')
  3105. 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')
  3106. --RETURN
  3107. END
  3108. END
  3109. ELSE
  3110. BEGIN
  3111. 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')
  3112. --RETURN
  3113. END;
  3114. --------------------------------------------------------------------------------------------------------------------------------
  3115. -- Disk Fragmentation Analysis subsection
  3116. --------------------------------------------------------------------------------------------------------------------------------
  3117. IF @diskfrag = 1
  3118. BEGIN
  3119. RAISERROR (N' |-Starting Disk Fragmentation Analysis', 10, 1) WITH NOWAIT
  3120. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  3121. BEGIN
  3122. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3123. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3124. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  3125. AND (SELECT COUNT(l.name)
  3126. FROM sys.server_permissions p JOIN sys.server_principals l
  3127. ON p.grantee_principal_id = l.principal_id
  3128. AND p.class = 100 -- Server
  3129. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  3130. AND l.is_disabled = 0
  3131. AND p.permission_name = 'ALTER SETTINGS'
  3132. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  3133. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3134. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  3135. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  3136. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  3137. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  3138. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  3139. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  3140. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  3141. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  3142. BEGIN
  3143. DECLARE @frag int
  3144. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3145. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3146. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  3147. RAISERROR (' |-Configuration options set for Disk Fragmentation Analysis', 10, 1) WITH NOWAIT
  3148. IF @sao = 0
  3149. BEGIN
  3150. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3151. END
  3152. IF @xcmd = 0
  3153. BEGIN
  3154. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3155. END
  3156. IF @ole = 0
  3157. BEGIN
  3158. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  3159. END
  3160. DECLARE @output_hw_frag TABLE ([PS_OUTPUT] VARCHAR(2048));
  3161. DECLARE @output_hw_format_frag TABLE ([volid] smallint IDENTITY(1,1), [volfrag] VARCHAR(255), [fragrec] VARCHAR(10) NULL)
  3162. IF @custompath IS NULL
  3163. BEGIN
  3164. IF @sqlmajorver < 11
  3165. BEGIN
  3166. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  3167. SET @path = @path + '\LOG'
  3168. END
  3169. ELSE
  3170. BEGIN
  3171. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  3172. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  3173. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  3174. END
  3175. -- Create COM object with FSO
  3176. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  3177. IF @OLEResult <> 0
  3178. BEGIN
  3179. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3180. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3181. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3182. END
  3183. ELSE
  3184. BEGIN
  3185. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  3186. IF @OLEResult <> 0
  3187. BEGIN
  3188. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3189. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  3190. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3191. END
  3192. ELSE
  3193. BEGIN
  3194. IF @existout <> 1
  3195. BEGIN
  3196. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  3197. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  3198. END
  3199. END
  3200. EXEC @OLEResult = sp_OADestroy @FSO
  3201. END
  3202. END
  3203. ELSE
  3204. BEGIN
  3205. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  3206. END
  3207. SET @FileName = @path + '\checkbp_frag_' + RTRIM(@server) + '.ps1'
  3208. EXEC master.dbo.xp_fileexist @FileName, @existout out
  3209. IF @existout = 0
  3210. BEGIN -- Scan for frag
  3211. SET @Text1 = '$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
  3212. $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
  3213. $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
  3214. if ($myWindowsPrincipal.IsInRole($adminRole))
  3215. {
  3216. [string] $serverName = ''localhost''
  3217. $DiskResults = @()
  3218. $objDisks = Get-WmiObject -Computername $serverName -Class Win32_Volume | Where-Object { $_.DriveType -eq 3 -and $_.Name -like "*:\"}
  3219. ForEach( $disk in $objDisks)
  3220. {
  3221. $objDefrag = $disk.DefragAnalysis()
  3222. $rec = $objDefrag.DefragRecommended
  3223. $objDefragDetail = $objDefrag.DefragAnalysis
  3224. $diskFragmentation = $objDefragDetail.TotalPercentFragmentation
  3225. $FreeFragmentation = $objDefragDetail.FreeSpacePercentFragmentation
  3226. $FileFragmentation = $objDefragDetail.FilePercentFragmentation
  3227. [string] $ThisVolume = "{0}TotalFragPct {1} :: FreeSpaceFragPct {2} :: FileFragPct {3};{4}" -f $($disk.Name),$diskFragmentation,$FreeFragmentation,$FileFragmentation,$rec
  3228. $DiskResults += $ThisVolume
  3229. }
  3230. $DiskResults
  3231. }
  3232. else
  3233. {
  3234. Write-Host "NotAdmin"
  3235. }
  3236. '
  3237. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3238. IF @OLEResult <> 0
  3239. BEGIN
  3240. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3241. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3242. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3243. END
  3244. --Open file
  3245. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3246. IF @OLEResult <> 0
  3247. BEGIN
  3248. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3249. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3250. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3251. END
  3252. ELSE
  3253. BEGIN
  3254. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3255. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3256. END
  3257. --Write Text1
  3258. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3259. IF @OLEResult <> 0
  3260. BEGIN
  3261. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3262. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3263. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3264. END
  3265. EXEC @OLEResult = sp_OADestroy @FileID
  3266. EXEC @OLEResult = sp_OADestroy @FS
  3267. END
  3268. ELSE
  3269. BEGIN
  3270. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3271. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3272. END
  3273. RAISERROR (' |-Getting Disk(s) Fragmentation. This may take some time...', 10, 1) WITH NOWAIT
  3274. IF @psver = 1
  3275. BEGIN
  3276. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3277. END
  3278. ELSE
  3279. BEGIN
  3280. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3281. END;
  3282. INSERT INTO @output_hw_frag
  3283. EXEC master.dbo.xp_cmdshell @CMD
  3284. SET @CMD = 'del /Q "' + @FileName + '"'
  3285. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3286. IF (SELECT COUNT([PS_OUTPUT]) FROM @output_hw_frag WHERE [PS_OUTPUT] LIKE '%NotAdmin%') = 1
  3287. BEGIN
  3288. RAISERROR ('[WARNING: Powershell not running under Elevated Privileges. Bypassing Disk Fragmentation Analysis]',16,1);
  3289. END
  3290. ELSE
  3291. BEGIN
  3292. INSERT INTO @output_hw_format_frag ([volfrag],fragrec)
  3293. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3294. 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)
  3295. FROM @output_hw_frag
  3296. WHERE [PS_OUTPUT] IS NOT NULL
  3297. END
  3298. SET @CMD2 = 'del ' + @FileName
  3299. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3300. IF @xcmd = 0
  3301. BEGIN
  3302. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3303. END
  3304. IF @ole = 0
  3305. BEGIN
  3306. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3307. END
  3308. IF @sao = 0
  3309. BEGIN
  3310. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3311. END;
  3312. ;WITH fragcte (fragrec) AS (
  3313. SELECT fragrec
  3314. FROM @output_hw_format_frag
  3315. WHERE fragrec IS NOT NULL OR LEN(fragrec) > 0)
  3316. SELECT @frag = CASE WHEN (SELECT COUNT(*) FROM fragcte) = 0 THEN NULL ELSE COUNT(cte1.[fragrec]) END
  3317. FROM fragcte cte1
  3318. WHERE cte1.[fragrec] = 'True';
  3319. IF @frag > 0 AND @frag IS NOT NULL
  3320. BEGIN
  3321. 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]
  3322. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Information],
  3323. LEFT(t1.[volfrag],1) AS HD_Volume,
  3324. RIGHT(t1.[volfrag],(LEN(t1.[volfrag])-3)) AS [Fragmentation_Percent],
  3325. t1.fragrec AS [Defragmentation_Recommended]
  3326. FROM @output_hw_format_frag t1
  3327. WHERE t1.fragrec = 'True'
  3328. ORDER BY t1.[volfrag]
  3329. OPTION (RECOMPILE);
  3330. END
  3331. ELSE IF @frag IS NULL
  3332. BEGIN
  3333. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Check], '[WARNING: Could not gather information on Disk Fragmentation Analysis]' AS [Deviation]
  3334. END
  3335. ELSE
  3336. BEGIN
  3337. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Check], '[OK]' AS [Deviation]
  3338. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Information],
  3339. LEFT(t1.[volfrag],1) AS HD_Volume,
  3340. RIGHT(t1.[volfrag],(LEN(t1.[volfrag])-3)) AS [Fragmentation_Percent],
  3341. t1.fragrec AS [Defragmentation_Recommended]
  3342. FROM @output_hw_format_frag t1
  3343. ORDER BY t1.[volfrag]
  3344. OPTION (RECOMPILE);
  3345. END;
  3346. END
  3347. ELSE
  3348. BEGIN
  3349. 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')
  3350. 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')
  3351. --RETURN
  3352. END
  3353. END
  3354. ELSE
  3355. BEGIN
  3356. 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')
  3357. --RETURN
  3358. END
  3359. END
  3360. ELSE
  3361. BEGIN
  3362. RAISERROR(' |- [INFORMATION: "Disk Fragmentation Analysis" check is disabled]', 10, 1, N'disallow_diskfrag')
  3363. --RETURN
  3364. END;
  3365. --------------------------------------------------------------------------------------------------------------------------------
  3366. -- Cluster Quorum Model subsection
  3367. --------------------------------------------------------------------------------------------------------------------------------
  3368. IF @clustered = 1 AND @winver <> '5.2'
  3369. BEGIN
  3370. RAISERROR (N' |-Starting Cluster Quorum Model', 10, 1) WITH NOWAIT
  3371. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted')) AND @psver > 1
  3372. BEGIN
  3373. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3374. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3375. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  3376. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3377. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  3378. BEGIN
  3379. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3380. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3381. RAISERROR (' |-Configuration options set for Cluster Quorum Model check', 10, 1) WITH NOWAIT
  3382. IF @sao = 0
  3383. BEGIN
  3384. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3385. END
  3386. IF @xcmd = 0
  3387. BEGIN
  3388. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3389. END
  3390. DECLARE /*@CMD NVARCHAR(4000), @line int, @linemax int, */ @CntNodes tinyint, @CntVotes tinyint
  3391. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  3392. DROP TABLE #xp_cmdshell_CluNodesOutput;
  3393. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  3394. CREATE TABLE #xp_cmdshell_CluNodesOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(50));
  3395. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  3396. DROP TABLE #xp_cmdshell_CluOutput;
  3397. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  3398. CREATE TABLE #xp_cmdshell_CluOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(50));
  3399. IF @winver <> '5.2'
  3400. BEGIN
  3401. SELECT @CMD = N'powershell -NoLogo -NoProfile "Import-Module FailoverClusters"; "Get-ClusterNode | Format-Table -Autosize -HideTableHeaders NodeWeight"'
  3402. INSERT INTO #xp_cmdshell_CluNodesOutput ([Output])
  3403. EXEC master.dbo.xp_cmdshell @CMD;
  3404. END
  3405. SELECT @CMD = N'powershell -NoLogo -NoProfile "Import-Module FailoverClusters"; "Get-ClusterQuorum | Format-Table -Autosize -HideTableHeaders QuorumType"'
  3406. INSERT INTO #xp_cmdshell_CluOutput ([Output])
  3407. EXEC master.dbo.xp_cmdshell @CMD;
  3408. IF (SELECT COUNT([Output]) FROM #xp_cmdshell_CluNodesOutput WHERE [Output] = '') > 0
  3409. BEGIN
  3410. SELECT @CntNodes = COUNT(NodeName) FROM sys.dm_os_cluster_nodes (NOLOCK)
  3411. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check],
  3412. CASE WHEN REPLACE([Output], CHAR(9), '') = 'DiskOnly' AND @winver <> '5.2' THEN '[WARNING: The current quorum model is not recommended since WS2003]'
  3413. 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]'
  3414. 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]'
  3415. WHEN REPLACE([Output], CHAR(9), '') = 'NodeAndFileShareMajority' THEN '[INFORMATION: The current quorum model is recommended for clusters with special configurations]'
  3416. ELSE '[OK]' END AS [Deviation],
  3417. QUOTENAME(REPLACE([Output], CHAR(9), '')) AS QuorumModel,
  3418. '[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
  3419. FROM #xp_cmdshell_CluOutput WHERE [Output] IS NOT NULL
  3420. END
  3421. ELSE
  3422. BEGIN
  3423. SELECT @CntVotes = SUM(CONVERT(int, [Output])) FROM #xp_cmdshell_CluNodesOutput WHERE [Output] IS NOT NULL
  3424. IF EXISTS (SELECT TOP 1 [Output] FROM #xp_cmdshell_CluOutput WHERE [Output] LIKE '%Majority%' OR [Output] LIKE '%Disk%')
  3425. BEGIN
  3426. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check],
  3427. CASE WHEN REPLACE([Output], CHAR(9), '') = 'DiskOnly' AND @winver <> '5.2' THEN '[WARNING: The current quorum model is not recommended since WS2003]'
  3428. 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]'
  3429. 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]'
  3430. WHEN REPLACE([Output], CHAR(9), '') = 'NodeAndFileShareMajority' THEN '[INFORMATION: The current quorum model is recommended for clusters with special configurations]'
  3431. ELSE '[OK]' END AS [Deviation],
  3432. QUOTENAME(REPLACE([Output], CHAR(9), '')) AS QuorumModel
  3433. FROM #xp_cmdshell_CluOutput WHERE [Output] IS NOT NULL
  3434. END
  3435. END
  3436. IF @xcmd = 0
  3437. BEGIN
  3438. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3439. END
  3440. IF @sao = 0
  3441. BEGIN
  3442. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3443. END
  3444. END
  3445. ELSE
  3446. BEGIN
  3447. 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')
  3448. 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')
  3449. --RETURN
  3450. END
  3451. END
  3452. ELSE IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted')) AND @psver = 1
  3453. BEGIN
  3454. RAISERROR(' |- [INFORMATION: "Cluster Quorum Model" check was skipped: cannot execute with PS v1]', 10, 1, N'disallow_ps')
  3455. --RETURN
  3456. END
  3457. ELSE
  3458. BEGIN
  3459. 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')
  3460. --RETURN
  3461. END
  3462. END
  3463. ELSE
  3464. BEGIN
  3465. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3466. END;
  3467. IF @IsHadrEnabled = 1
  3468. BEGIN
  3469. SET @sqlcmd = N'DECLARE @winver VARCHAR(5), @CntNodes tinyint
  3470. SELECT @winver = windows_release FROM sys.dm_os_windows_info (NOLOCK)
  3471. SELECT @CntNodes = SUM(number_of_quorum_votes) FROM sys.dm_hadr_cluster_members (NOLOCK)
  3472. SELECT ''Server_checks'' AS [Category], ''AlwaysOn_Cluster_Quorum'' AS [Check], cluster_name,
  3473. CASE WHEN quorum_type = 3 AND @winver <> ''5.2'' THEN ''[WARNING: The current quorum model is not recommended since WS2003]''
  3474. 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]''
  3475. 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]''
  3476. WHEN quorum_type = 2 THEN ''[INFORMATION: The current quorum model is recommended for clusters with special configurations]''
  3477. ELSE ''[OK]'' END AS [Deviation],
  3478. QUOTENAME(quorum_type_desc) AS QuorumModel
  3479. FROM sys.dm_hadr_cluster;'
  3480. EXECUTE sp_executesql @sqlcmd
  3481. END;
  3482. --------------------------------------------------------------------------------------------------------------------------------
  3483. -- Cluster NIC Binding order subsection
  3484. --------------------------------------------------------------------------------------------------------------------------------
  3485. IF @allow_xpcmdshell = 1 and @clustered = 1
  3486. BEGIN
  3487. RAISERROR (N' |-Starting Cluster NIC Binding order', 10, 1) WITH NOWAIT
  3488. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  3489. BEGIN
  3490. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3491. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3492. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  3493. AND (SELECT COUNT(l.name)
  3494. FROM sys.server_permissions p JOIN sys.server_principals l
  3495. ON p.grantee_principal_id = l.principal_id
  3496. AND p.class = 100 -- Server
  3497. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  3498. AND l.is_disabled = 0
  3499. AND p.permission_name = 'ALTER SETTINGS'
  3500. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  3501. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3502. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  3503. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  3504. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  3505. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  3506. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  3507. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  3508. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  3509. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  3510. BEGIN
  3511. DECLARE @clunic int, @maxnic int
  3512. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3513. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3514. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  3515. RAISERROR (' |-Configuration options set for Cluster NIC Binding Order check', 10, 1) WITH NOWAIT
  3516. IF @sao = 0
  3517. BEGIN
  3518. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3519. END
  3520. IF @xcmd = 0
  3521. BEGIN
  3522. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3523. END
  3524. IF @ole = 0
  3525. BEGIN
  3526. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  3527. END
  3528. DECLARE @output_hw_nics TABLE ([PS_OUTPUT] VARCHAR(2048));
  3529. DECLARE @output_hw_format_nics TABLE ([nicid] smallint, [nicname] VARCHAR(255) NULL)
  3530. IF @custompath IS NULL
  3531. BEGIN
  3532. IF @sqlmajorver < 11
  3533. BEGIN
  3534. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  3535. SET @path = @path + '\LOG'
  3536. END
  3537. ELSE
  3538. BEGIN
  3539. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  3540. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  3541. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  3542. END
  3543. -- Create COM object with FSO
  3544. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  3545. IF @OLEResult <> 0
  3546. BEGIN
  3547. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3548. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3549. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3550. END
  3551. ELSE
  3552. BEGIN
  3553. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  3554. IF @OLEResult <> 0
  3555. BEGIN
  3556. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3557. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  3558. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3559. END
  3560. ELSE
  3561. BEGIN
  3562. IF @existout <> 1
  3563. BEGIN
  3564. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  3565. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  3566. END
  3567. END
  3568. EXEC @OLEResult = sp_OADestroy @FSO
  3569. END
  3570. END
  3571. ELSE
  3572. BEGIN
  3573. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  3574. END
  3575. SET @FileName = @path + '\checkbp_nics_' + RTRIM(@server) + '.ps1'
  3576. EXEC master.dbo.xp_fileexist @FileName, @existout out
  3577. IF @existout = 0
  3578. BEGIN -- Scan for nics
  3579. SET @Text1 = '[string] $serverName = ''localhost''
  3580. $nics = Get-WmiObject -Computername $serverName -query "SELECT Description, Index FROM Win32_NetworkAdapterConfiguration"
  3581. foreach ($nic in $nics)
  3582. {
  3583. [string] $allnics = "{0};{1}" -f $nic.Index,$nic.Description
  3584. Write-Output $allnics
  3585. }
  3586. '
  3587. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3588. IF @OLEResult <> 0
  3589. BEGIN
  3590. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3591. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3592. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3593. END
  3594. --Open file
  3595. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3596. IF @OLEResult <> 0
  3597. BEGIN
  3598. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3599. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3600. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3601. END
  3602. ELSE
  3603. BEGIN
  3604. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3605. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3606. END
  3607. --Write Text1
  3608. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3609. IF @OLEResult <> 0
  3610. BEGIN
  3611. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3612. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3613. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3614. END
  3615. EXEC @OLEResult = sp_OADestroy @FileID
  3616. EXEC @OLEResult = sp_OADestroy @FS
  3617. END
  3618. ELSE
  3619. BEGIN
  3620. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3621. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3622. END
  3623. IF @psver = 1
  3624. BEGIN
  3625. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3626. END
  3627. ELSE
  3628. BEGIN
  3629. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3630. END;
  3631. INSERT INTO @output_hw_nics
  3632. EXEC master.dbo.xp_cmdshell @CMD
  3633. SET @CMD = 'del /Q "' + @FileName + '"'
  3634. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3635. INSERT INTO @output_hw_format_nics ([nicid],nicname)
  3636. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3637. 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)
  3638. FROM @output_hw_nics
  3639. WHERE [PS_OUTPUT] IS NOT NULL;
  3640. SET @CMD2 = 'del ' + @FileName
  3641. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3642. IF @xcmd = 0
  3643. BEGIN
  3644. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3645. END
  3646. IF @ole = 0
  3647. BEGIN
  3648. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3649. END
  3650. IF @sao = 0
  3651. BEGIN
  3652. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3653. END;
  3654. SELECT @maxnic = MAX(nicid) FROM @output_hw_format_nics;
  3655. SELECT TOP 1 @clunic = nicid FROM @output_hw_format_nics WHERE nicname LIKE '%Cluster Virtual Adapter%';
  3656. IF @clunic < @maxnic OR @clunic IS NULL --http://support2.microsoft.com/kb/955963
  3657. BEGIN
  3658. 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]
  3659. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Information], nicid AS NIC_ID, nicname AS NIC_Name
  3660. FROM @output_hw_format_nics t1
  3661. ORDER BY t1.[nicid]
  3662. OPTION (RECOMPILE);
  3663. END
  3664. ELSE IF @clunic = @maxnic
  3665. BEGIN
  3666. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], '[OK]' AS [Deviation]
  3667. END
  3668. ELSE
  3669. BEGIN
  3670. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], '[WARNING: Could not gather information on NIC binding order]' AS [Deviation]
  3671. END;
  3672. END
  3673. ELSE
  3674. BEGIN
  3675. 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')
  3676. 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')
  3677. --RETURN
  3678. END
  3679. END
  3680. ELSE
  3681. BEGIN
  3682. 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')
  3683. --RETURN
  3684. END
  3685. END
  3686. ELSE
  3687. BEGIN
  3688. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3689. END;
  3690. --------------------------------------------------------------------------------------------------------------------------------
  3691. -- Cluster QFE node equality subsection
  3692. --------------------------------------------------------------------------------------------------------------------------------
  3693. IF @clustered = 1
  3694. BEGIN
  3695. RAISERROR (N' |-Starting QFE node equality', 10, 1) WITH NOWAIT
  3696. IF @allow_xpcmdshell = 1
  3697. BEGIN
  3698. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3699. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3700. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  3701. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3702. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  3703. BEGIN
  3704. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3705. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3706. RAISERROR (' |-Configuration options set for QFE node equality check', 10, 1) WITH NOWAIT
  3707. IF @sao = 0
  3708. BEGIN
  3709. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3710. END
  3711. IF @xcmd = 0
  3712. BEGIN
  3713. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3714. END
  3715. DECLARE /* @CMD NVARCHAR(4000), @line int, @linemax int, */ @Node VARCHAR(50)
  3716. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  3717. DROP TABLE #xp_cmdshell_Nodes;
  3718. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  3719. CREATE TABLE #xp_cmdshell_Nodes (NodeName VARCHAR(50), isdone bit NOT NULL);
  3720. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  3721. DROP TABLE #xp_cmdshell_QFEOutput;
  3722. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  3723. CREATE TABLE #xp_cmdshell_QFEOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(150));
  3724. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  3725. DROP TABLE #xp_cmdshell_QFEFinal;
  3726. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  3727. CREATE TABLE #xp_cmdshell_QFEFinal (NodeName VARCHAR(50), [QFE] VARCHAR(150));
  3728. INSERT INTO #xp_cmdshell_Nodes
  3729. SELECT NodeName, 0 FROM sys.dm_os_cluster_nodes (NOLOCK);
  3730. WHILE (SELECT COUNT(NodeName) FROM #xp_cmdshell_Nodes WHERE isdone = 0) > 0
  3731. BEGIN
  3732. SELECT TOP 1 @Node = NodeName FROM #xp_cmdshell_Nodes WHERE isdone = 0;
  3733. SET @CMD = 'wmic /node:"' + @Node + '" qfe get hotfixid'
  3734. INSERT INTO #xp_cmdshell_QFEOutput ([Output])
  3735. EXEC master.dbo.xp_cmdshell @CMD;
  3736. IF (SELECT COUNT([Output]) FROM #xp_cmdshell_QFEOutput WHERE [Output] LIKE '%Access is denied%') = 0
  3737. BEGIN
  3738. INSERT INTO #xp_cmdshell_QFEFinal
  3739. SELECT @Node, RTRIM(REPLACE([Output],CHAR(13),'')) FROM #xp_cmdshell_QFEOutput WHERE RTRIM(REPLACE([Output],CHAR(13),'')) NOT IN ('','HotFixID');
  3740. END
  3741. ELSE
  3742. BEGIN
  3743. SET @ErrorMessage = '[WARNING: Access Denied error while trying to get updates from node ' + @Node + ']'
  3744. RAISERROR (@ErrorMessage,16,1);
  3745. END;
  3746. TRUNCATE TABLE #xp_cmdshell_QFEOutput;
  3747. UPDATE #xp_cmdshell_Nodes
  3748. SET isdone = 1
  3749. WHERE NodeName = @Node;
  3750. END;
  3751. IF (SELECT COUNT(DISTINCT NodeName) FROM #xp_cmdshell_QFEFinal) = (SELECT COUNT(DISTINCT NodeName) FROM #xp_cmdshell_Nodes)
  3752. BEGIN
  3753. 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
  3754. BEGIN
  3755. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], '[WARNING: Missing updates found in some of the nodes]' AS [Deviation]
  3756. SELECT t1.NodeName, t1.[QFE] AS MissingUpdates FROM #xp_cmdshell_QFEFinal t1
  3757. WHERE t1.[QFE] NOT IN (SELECT DISTINCT t2.[QFE] FROM #xp_cmdshell_QFEFinal t2 WHERE t2.NodeName <> t1.NodeName);
  3758. END
  3759. ELSE
  3760. BEGIN
  3761. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], '[OK]' AS [Deviation];
  3762. SELECT DISTINCT t1.[QFE] AS InstalledUpdates FROM #xp_cmdshell_QFEFinal t1;
  3763. END
  3764. END
  3765. ELSE
  3766. BEGIN
  3767. RAISERROR ('[WARNING: Could not collect data from all cluster nodes. Bypassing QFE node equality check]',16,1);
  3768. END
  3769. IF @xcmd = 0
  3770. BEGIN
  3771. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3772. END
  3773. IF @sao = 0
  3774. BEGIN
  3775. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3776. END
  3777. END
  3778. ELSE
  3779. BEGIN
  3780. 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')
  3781. 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')
  3782. --RETURN
  3783. END
  3784. END
  3785. ELSE
  3786. BEGIN
  3787. RAISERROR(' |- [INFORMATION: "QFE node equality" check was skipped because xp_cmdshell was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  3788. --RETURN
  3789. END
  3790. END
  3791. ELSE
  3792. BEGIN
  3793. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3794. END;
  3795. RAISERROR (N'|-Starting Service Accounts Checks', 10, 1) WITH NOWAIT
  3796. --------------------------------------------------------------------------------------------------------------------------------
  3797. -- Service Accounts Status subsection
  3798. --------------------------------------------------------------------------------------------------------------------------------
  3799. RAISERROR (N' |-Starting Service Accounts Status', 10, 1) WITH NOWAIT
  3800. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1)
  3801. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1 AND
  3802. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_servicecontrol') = 1)
  3803. BEGIN
  3804. DECLARE @rc int, @profile NVARCHAR(128)
  3805. DECLARE @sqlservice NVARCHAR(128), @sqlagentservice NVARCHAR(128), @dtsservice NVARCHAR(128), @ftservice NVARCHAR(128)
  3806. DECLARE @browservice NVARCHAR(128), @olapservice NVARCHAR(128), @rsservice NVARCHAR(128)
  3807. DECLARE @statussqlservice NVARCHAR(20), @statussqlagentservice NVARCHAR(20), @statusdtsservice NVARCHAR(20), @statusftservice NVARCHAR(20)
  3808. DECLARE @statusbrowservice NVARCHAR(20), @statusolapservice NVARCHAR(20), @statusrsservice NVARCHAR(20)
  3809. DECLARE @regkeysqlservice NVARCHAR(256), @regkeysqlagentservice NVARCHAR(256), @regkeydtsservice NVARCHAR(256), @regkeyftservice NVARCHAR(256)
  3810. DECLARE @regkeybrowservice NVARCHAR(256), @regkeyolapservice NVARCHAR(256), @regkeyrsservice NVARCHAR(256)
  3811. DECLARE @accntsqlservice NVARCHAR(128), @accntsqlagentservice NVARCHAR(128), @accntdtsservice NVARCHAR(128), @accntftservice NVARCHAR(128)
  3812. DECLARE @accntbrowservice NVARCHAR(128), @accntolapservice NVARCHAR(128), @accntrsservice NVARCHAR(128)
  3813. -- Get service names
  3814. IF (@instancename IS NULL)
  3815. BEGIN
  3816. IF @sqlmajorver < 11
  3817. BEGIN
  3818. SELECT @sqlservice = N'MSSQLServer'
  3819. SELECT @sqlagentservice = N'SQLServerAgent'
  3820. END
  3821. SELECT @olapservice = N'MSSQLServerOLAPService'
  3822. SELECT @rsservice = N'ReportServer'
  3823. END
  3824. ELSE
  3825. BEGIN
  3826. IF @sqlmajorver < 11
  3827. BEGIN
  3828. SELECT @sqlservice = N'MSSQL$' + @instancename
  3829. SELECT @sqlagentservice = N'SQLAgent$' + @instancename
  3830. END
  3831. SELECT @olapservice = N'MSOLAP$' + @instancename
  3832. SELECT @rsservice = N'ReportServer$' + @instancename
  3833. END
  3834. IF @sqlmajorver = 9
  3835. BEGIN
  3836. SELECT @dtsservice = N'MsDtsServer'
  3837. END
  3838. ELSE
  3839. BEGIN
  3840. SELECT @dtsservice = N'MsDtsServer' + CONVERT(VARCHAR, @sqlmajorver) + '0'
  3841. END
  3842. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3843. BEGIN
  3844. IF (@instancename IS NULL) AND @sqlmajorver = 10
  3845. BEGIN
  3846. SELECT @ftservice = N'MSSQLFDLauncher'
  3847. END
  3848. ELSE IF (@instancename IS NOT NULL) AND @sqlmajorver = 10
  3849. BEGIN
  3850. SELECT @ftservice = N'MSSQLFDLauncher$' + @instancename
  3851. END
  3852. ELSE IF (@instancename IS NULL) AND @sqlmajorver = 9
  3853. BEGIN
  3854. SELECT @ftservice = N'msftesql'
  3855. END
  3856. ELSE IF (@instancename IS NOT NULL) AND @sqlmajorver = 9
  3857. BEGIN
  3858. SELECT @ftservice = N'msftesql$' + @instancename
  3859. END
  3860. END
  3861. SELECT @browservice = N'SQLBrowser'
  3862. IF @sqlmajorver < 11
  3863. BEGIN
  3864. SELECT @regkeysqlservice = N'SYSTEM\CurrentControlSet\Services\' + @sqlservice
  3865. SELECT @regkeysqlagentservice = N'SYSTEM\CurrentControlSet\Services\' + @sqlagentservice
  3866. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3867. BEGIN
  3868. SELECT @regkeyftservice = N'SYSTEM\CurrentControlSet\Services\' + @ftservice
  3869. END
  3870. END
  3871. SELECT @regkeyolapservice = N'SYSTEM\CurrentControlSet\Services\' + @olapservice
  3872. SELECT @regkeyrsservice = N'SYSTEM\CurrentControlSet\Services\' + @rsservice
  3873. SELECT @regkeydtsservice = N'SYSTEM\CurrentControlSet\Services\' + @dtsservice
  3874. SELECT @regkeybrowservice = N'SYSTEM\CurrentControlSet\Services\' + @browservice
  3875. -- Service status
  3876. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#RegResult'))
  3877. CREATE TABLE #RegResult (ResultValue bit)
  3878. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ServiceStatus'))
  3879. CREATE TABLE #ServiceStatus (ServiceStatus VARCHAR(128))
  3880. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3881. BEGIN
  3882. BEGIN TRY
  3883. INSERT INTO #RegResult (ResultValue)
  3884. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlservice
  3885. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3886. BEGIN
  3887. INSERT INTO #ServiceStatus (ServiceStatus)
  3888. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @sqlservice
  3889. SELECT @statussqlservice = ServiceStatus FROM #ServiceStatus
  3890. TRUNCATE TABLE #ServiceStatus;
  3891. END
  3892. ELSE
  3893. BEGIN
  3894. SET @statussqlservice = 'Not Installed'
  3895. END
  3896. TRUNCATE TABLE #RegResult;
  3897. END TRY
  3898. BEGIN CATCH
  3899. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3900. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  3901. RAISERROR (@ErrorMessage, 16, 1);
  3902. END CATCH
  3903. END
  3904. ELSE
  3905. BEGIN
  3906. SET @sqlcmd = N'SELECT @statussqlserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server%'' AND servicename NOT LIKE ''SQL Server Agent%''';
  3907. SET @params = N'@statussqlserviceOUT NVARCHAR(20) OUTPUT';
  3908. EXECUTE sp_executesql @sqlcmd, @params, @statussqlserviceOUT=@statussqlservice OUTPUT;
  3909. IF @statussqlservice IS NULL
  3910. BEGIN
  3911. SET @statussqlservice = 'Not Installed'
  3912. END
  3913. END
  3914. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3915. BEGIN
  3916. BEGIN TRY
  3917. INSERT INTO #RegResult (ResultValue)
  3918. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlagentservice
  3919. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3920. BEGIN
  3921. INSERT INTO #ServiceStatus (ServiceStatus)
  3922. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @sqlagentservice
  3923. SELECT @statussqlagentservice = ServiceStatus FROM #ServiceStatus
  3924. TRUNCATE TABLE #ServiceStatus;
  3925. END
  3926. ELSE
  3927. BEGIN
  3928. SET @statussqlagentservice = 'Not Installed'
  3929. END
  3930. TRUNCATE TABLE #RegResult;
  3931. END TRY
  3932. BEGIN CATCH
  3933. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3934. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  3935. RAISERROR (@ErrorMessage, 16, 1);
  3936. END CATCH
  3937. END
  3938. ELSE
  3939. BEGIN
  3940. SET @sqlcmd = N'SELECT @statussqlagentserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server Agent%''';
  3941. SET @params = N'@statussqlagentserviceOUT NVARCHAR(20) OUTPUT';
  3942. EXECUTE sp_executesql @sqlcmd, @params, @statussqlagentserviceOUT=@statussqlagentservice OUTPUT;
  3943. IF @statussqlagentservice IS NULL
  3944. BEGIN
  3945. SET @statussqlagentservice = 'Not Installed'
  3946. END
  3947. END
  3948. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3949. BEGIN
  3950. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3951. BEGIN
  3952. BEGIN TRY
  3953. INSERT INTO #RegResult (ResultValue)
  3954. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyftservice
  3955. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3956. BEGIN
  3957. INSERT INTO #ServiceStatus (ServiceStatus)
  3958. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @ftservice
  3959. SELECT @statusftservice = ServiceStatus FROM #ServiceStatus
  3960. TRUNCATE TABLE #ServiceStatus;
  3961. END
  3962. ELSE
  3963. BEGIN
  3964. SET @statusftservice = '[INFORMATION: Service is not installed]'
  3965. END
  3966. TRUNCATE TABLE #RegResult;
  3967. END TRY
  3968. BEGIN CATCH
  3969. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3970. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  3971. RAISERROR (@ErrorMessage, 16, 1);
  3972. END CATCH
  3973. END
  3974. END
  3975. ELSE
  3976. BEGIN
  3977. SET @sqlcmd = N'SELECT @statusftserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Full-text Filter Daemon Launcher%''';
  3978. SET @params = N'@statusftserviceOUT NVARCHAR(20) OUTPUT';
  3979. EXECUTE sp_executesql @sqlcmd, @params, @statusftserviceOUT=@statusftservice OUTPUT;
  3980. IF @statusftservice IS NULL
  3981. BEGIN
  3982. SET @statusftservice = '[INFORMATION: Service is not installed]'
  3983. END
  3984. END
  3985. BEGIN TRY
  3986. INSERT INTO #RegResult (ResultValue)
  3987. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyolapservice
  3988. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3989. BEGIN
  3990. INSERT INTO #ServiceStatus (ServiceStatus)
  3991. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @olapservice
  3992. SELECT @statusolapservice = ServiceStatus FROM #ServiceStatus
  3993. TRUNCATE TABLE #ServiceStatus;
  3994. END
  3995. ELSE
  3996. BEGIN
  3997. SET @statusolapservice = 'Not Installed'
  3998. END
  3999. TRUNCATE TABLE #RegResult;
  4000. END TRY
  4001. BEGIN CATCH
  4002. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4003. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 4. ' + ERROR_MESSAGE()
  4004. RAISERROR (@ErrorMessage, 16, 1);
  4005. END CATCH
  4006. BEGIN TRY
  4007. INSERT INTO #RegResult (ResultValue)
  4008. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyrsservice
  4009. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4010. BEGIN
  4011. INSERT INTO #ServiceStatus (ServiceStatus)
  4012. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @rsservice
  4013. SELECT @statusrsservice = ServiceStatus FROM #ServiceStatus
  4014. TRUNCATE TABLE #ServiceStatus;
  4015. END
  4016. ELSE
  4017. BEGIN
  4018. SET @statusrsservice = 'Not Installed'
  4019. END
  4020. TRUNCATE TABLE #RegResult;
  4021. END TRY
  4022. BEGIN CATCH
  4023. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4024. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 5. ' + ERROR_MESSAGE()
  4025. RAISERROR (@ErrorMessage, 16, 1);
  4026. END CATCH
  4027. BEGIN TRY
  4028. INSERT INTO #RegResult (ResultValue)
  4029. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeydtsservice
  4030. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4031. BEGIN
  4032. INSERT INTO #ServiceStatus (ServiceStatus)
  4033. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @dtsservice
  4034. SELECT @statusdtsservice = ServiceStatus FROM #ServiceStatus
  4035. TRUNCATE TABLE #ServiceStatus;
  4036. END
  4037. ELSE
  4038. BEGIN
  4039. SET @statusdtsservice = 'Not Installed'
  4040. END
  4041. TRUNCATE TABLE #RegResult;
  4042. END TRY
  4043. BEGIN CATCH
  4044. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4045. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 6. ' + ERROR_MESSAGE()
  4046. RAISERROR (@ErrorMessage, 16, 1);
  4047. END CATCH
  4048. BEGIN TRY
  4049. INSERT INTO #RegResult (ResultValue)
  4050. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeybrowservice
  4051. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4052. BEGIN
  4053. INSERT INTO #ServiceStatus (ServiceStatus)
  4054. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @browservice
  4055. SELECT @statusbrowservice = ServiceStatus FROM #ServiceStatus
  4056. TRUNCATE TABLE #ServiceStatus;
  4057. END
  4058. ELSE
  4059. BEGIN
  4060. SET @statusbrowservice = 'Not Installed'
  4061. END
  4062. END TRY
  4063. BEGIN CATCH
  4064. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4065. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 7. ' + ERROR_MESSAGE()
  4066. RAISERROR (@ErrorMessage, 16, 1);
  4067. END CATCH
  4068. DROP TABLE #RegResult;
  4069. DROP TABLE #ServiceStatus;
  4070. -- Accounts
  4071. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  4072. BEGIN
  4073. BEGIN TRY
  4074. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlservice, N'ObjectName', @accntsqlservice OUTPUT, NO_OUTPUT
  4075. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlagentservice, N'ObjectName', @accntsqlagentservice OUTPUT, NO_OUTPUT
  4076. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyftservice, N'ObjectName', @accntftservice OUTPUT, NO_OUTPUT
  4077. END TRY
  4078. BEGIN CATCH
  4079. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4080. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 8. ' + ERROR_MESSAGE()
  4081. RAISERROR (@ErrorMessage, 16, 1);
  4082. END CATCH
  4083. END
  4084. ELSE
  4085. BEGIN
  4086. BEGIN TRY
  4087. SET @sqlcmd = N'SELECT @accntsqlserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server%'' AND servicename NOT LIKE ''SQL Server Agent%''';
  4088. SET @params = N'@accntsqlserviceOUT NVARCHAR(128) OUTPUT';
  4089. EXECUTE sp_executesql @sqlcmd, @params, @accntsqlserviceOUT=@accntsqlservice OUTPUT;
  4090. SET @sqlcmd = N'SELECT @accntsqlagentserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server Agent%''';
  4091. SET @params = N'@accntsqlagentserviceOUT NVARCHAR(128) OUTPUT';
  4092. EXECUTE sp_executesql @sqlcmd, @params, @accntsqlagentserviceOUT=@accntsqlagentservice OUTPUT;
  4093. SET @sqlcmd = N'SELECT @accntftserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Full-text Filter Daemon Launcher%''';
  4094. SET @params = N'@accntftserviceOUT NVARCHAR(128) OUTPUT';
  4095. EXECUTE sp_executesql @sqlcmd, @params, @accntftserviceOUT=@accntftservice OUTPUT;
  4096. END TRY
  4097. BEGIN CATCH
  4098. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4099. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 9. ' + ERROR_MESSAGE()
  4100. RAISERROR (@ErrorMessage, 16, 1);
  4101. END CATCH
  4102. END
  4103. BEGIN TRY
  4104. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyolapservice, N'ObjectName', @accntolapservice OUTPUT, NO_OUTPUT
  4105. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyrsservice, N'ObjectName', @accntrsservice OUTPUT, NO_OUTPUT
  4106. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeydtsservice, N'ObjectName', @accntdtsservice OUTPUT, NO_OUTPUT
  4107. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeybrowservice, N'ObjectName', @accntbrowservice OUTPUT, NO_OUTPUT
  4108. END TRY
  4109. BEGIN CATCH
  4110. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4111. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 10. ' + ERROR_MESSAGE()
  4112. RAISERROR (@ErrorMessage, 16, 1);
  4113. END CATCH
  4114. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server' AS [Service], @statussqlservice AS [Status], @accntsqlservice AS [Account],
  4115. CASE WHEN @statussqlservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4116. WHEN @statussqlservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4117. WHEN @accntsqlservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4118. WHEN @accntsqlservice = 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4119. WHEN @clustered = 1 AND @accntsqlservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4120. WHEN @clustered = 1 AND @accntsqlservice = 'LocalSystem' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4121. WHEN @clustered = 1 AND @accntsqlservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4122. WHEN @clustered = 0 AND @accntsqlservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4123. WHEN @clustered = 0 AND @accntsqlservice = 'LocalSystem' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4124. WHEN @clustered = 0 AND @accntsqlservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4125. -- 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)
  4126. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @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]'
  4127. ELSE '[OK]'
  4128. END AS [Deviation]
  4129. UNION ALL
  4130. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Agent' AS [Service], @statussqlagentservice AS [Status], @accntsqlagentservice AS [Account],
  4131. CASE WHEN @statussqlagentservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4132. WHEN @statussqlagentservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4133. WHEN @accntsqlagentservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4134. WHEN @accntsqlagentservice = 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4135. WHEN @accntsqlagentservice = @accntsqlservice THEN '[WARNING: Running SQL Server Agent under the same account as SQL Server is not recommended]'
  4136. WHEN @clustered = 1 AND @accntsqlagentservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4137. WHEN @clustered = 1 AND @accntsqlagentservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4138. WHEN @clustered = 0 AND @accntsqlagentservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server Agent under this account is not recommended]'
  4139. WHEN @clustered = 0 AND @accntsqlagentservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not recommended]'
  4140. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4141. -- 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)
  4142. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @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]'
  4143. ELSE '[OK]'
  4144. END AS [Deviation]
  4145. UNION ALL
  4146. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Analysis_Services' AS [Service], @statusolapservice AS [Status], @accntolapservice AS [Account],
  4147. CASE WHEN @statusolapservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4148. WHEN @statusolapservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4149. WHEN @accntolapservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4150. WHEN @accntolapservice = @accntsqlservice THEN '[WARNING: Running SQL Server Analysis Services under the same account as SQL Server is not recommended]'
  4151. 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]'
  4152. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4153. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) <= 6.0 AND @accntolapservice <> 'NT AUTHORITY\NETWORKSERVICE' THEN '[INFORMATION: SQL Server Analysis Services is not running with the default account]'
  4154. -- 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)
  4155. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @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]'
  4156. ELSE '[OK]'
  4157. END AS [Deviation]
  4158. UNION ALL
  4159. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Integration_Services' AS [Service], @statusdtsservice AS [Status], @accntdtsservice AS [Account],
  4160. CASE WHEN @statusdtsservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4161. WHEN @statusdtsservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4162. WHEN @accntdtsservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4163. WHEN @accntdtsservice = @accntsqlservice THEN '[WARNING: Running SQL Server Integration Services under the same account as SQL Server is not recommended]'
  4164. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4165. WHEN CONVERT(DECIMAL(3,1), @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]'
  4166. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4167. WHEN @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @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]'
  4168. ELSE '[OK]'
  4169. END AS [Deviation]
  4170. UNION ALL
  4171. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Reporting_Services' AS [Service], @statusrsservice AS [Status], @accntrsservice AS [Account],
  4172. CASE WHEN @statusrsservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4173. WHEN @statusrsservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4174. WHEN @accntrsservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4175. WHEN @accntrsservice = @accntsqlservice THEN '[WARNING: Running SQL Server Reporting Services under the same account as SQL Server is not recommended]'
  4176. 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]'
  4177. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4178. WHEN @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) <= 6.0 AND @accntrsservice <> 'NT AUTHORITY\NETWORKSERVICE' THEN '[INFORMATION: SQL Server Reporting Services is not running with the default account]'
  4179. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4180. WHEN @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @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]'
  4181. ELSE '[OK]'
  4182. END AS [Deviation]
  4183. UNION ALL
  4184. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'Full-Text' AS [Service], ISNULL(@statusftservice, 'Not Installed') AS [Status], ISNULL(@accntftservice,'') AS [Account],
  4185. CASE WHEN (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1 THEN
  4186. CASE WHEN @statusftservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4187. WHEN @statusftservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4188. WHEN @accntftservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4189. WHEN @accntftservice = @accntsqlservice THEN '[WARNING: Running Full-Text Daemon under the same account as SQL Server is not recommended]'
  4190. WHEN @accntftservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running Full-Text Service under this account is not recommended]'
  4191. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4192. WHEN @sqlmajorver <= 10 AND @accntftservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running Full-Text Service under this account is not recommended]'
  4193. WHEN @sqlmajorver <= 10 AND @accntftservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4194. WHEN @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) <= 6.0 AND @accntftservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4195. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4196. WHEN @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @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]'
  4197. ELSE '[OK]' END
  4198. ELSE '[INFORMATION: Service is not installed]'
  4199. END AS [Deviation]
  4200. UNION ALL
  4201. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Browser' AS [Service], @statusbrowservice AS [Status], @accntbrowservice AS [Account],
  4202. CASE WHEN @statusbrowservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4203. WHEN @statusbrowservice LIKE 'Stopped%' AND @instancename IS NOT NULL THEN '[WARNING: Service is stopped on a named instance]'
  4204. WHEN @statusbrowservice LIKE 'Stopped%' AND @instancename IS NULL THEN '[WARNING: Service is stopped]'
  4205. WHEN @accntbrowservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4206. WHEN @accntbrowservice = @accntsqlservice THEN '[WARNING: Running SQL Server Browser under the same account as SQL Server is not recommended]'
  4207. WHEN @accntbrowservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: SQL Server Browser is not running with the default account]'
  4208. ELSE '[OK]'
  4209. END AS [Deviation];
  4210. END
  4211. ELSE
  4212. BEGIN
  4213. 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')
  4214. --RETURN
  4215. END;
  4216. --------------------------------------------------------------------------------------------------------------------------------
  4217. -- Service Accounts and SPN registration subsection
  4218. --------------------------------------------------------------------------------------------------------------------------------
  4219. RAISERROR (N' |-Starting Service Accounts and SPN registration', 10, 1) WITH NOWAIT
  4220. 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
  4221. BEGIN
  4222. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  4223. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  4224. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  4225. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  4226. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  4227. BEGIN
  4228. RAISERROR (' |-Configuration options set for SPN check', 10, 1) WITH NOWAIT
  4229. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  4230. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  4231. IF @sao = 0
  4232. BEGIN
  4233. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  4234. END
  4235. IF @xcmd = 0
  4236. BEGIN
  4237. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  4238. END
  4239. BEGIN TRY
  4240. DECLARE /*@CMD NVARCHAR(4000),*/ @line int, @linemax int, @SPN VARCHAR(8000), @SPNMachine VARCHAR(8000)
  4241. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  4242. DROP TABLE #xp_cmdshell_AcctSPNoutput;
  4243. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  4244. CREATE TABLE #xp_cmdshell_AcctSPNoutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR (8000));
  4245. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  4246. DROP TABLE #xp_cmdshell_DupSPNoutput;
  4247. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  4248. CREATE TABLE #xp_cmdshell_DupSPNoutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR (8000));
  4249. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  4250. DROP TABLE #FinalDupSPN;
  4251. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  4252. CREATE TABLE #FinalDupSPN ([SPN] VARCHAR (8000), [Accounts] VARCHAR (8000));
  4253. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  4254. DROP TABLE #ScopedDupSPN;
  4255. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  4256. CREATE TABLE #ScopedDupSPN ([SPN] VARCHAR (8000), [Accounts] VARCHAR (8000));
  4257. SELECT @CMD = N'SETSPN -P -L ' + @accntsqlservice
  4258. INSERT INTO #xp_cmdshell_AcctSPNoutput ([Output])
  4259. EXEC master.dbo.xp_cmdshell @CMD;
  4260. SET @CMD = N'SETSPN -P -X'
  4261. INSERT INTO #xp_cmdshell_DupSPNoutput ([Output])
  4262. EXEC master.dbo.xp_cmdshell @CMD;
  4263. SELECT @SPNMachine = '%MSSQLSvc/' + CONVERT(NVARCHAR(100),SERVERPROPERTY('MachineName')) + '%';
  4264. 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]),' ', ''))))
  4265. BEGIN
  4266. 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%'
  4267. OPEN curSPN
  4268. FETCH NEXT FROM curSPN INTO @line, @SPN
  4269. WHILE @@FETCH_STATUS = 0
  4270. BEGIN
  4271. SELECT TOP 1 @linemax = line FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND [Output] IS NULL;
  4272. INSERT INTO #FinalDupSPN
  4273. SELECT QUOTENAME(@SPN), QUOTENAME(REPLACE([Output], CHAR(9), '')) FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND line < @linemax;
  4274. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_DupSPNoutput WHERE line = @line AND [Output] LIKE @SPNMachine)
  4275. BEGIN
  4276. INSERT INTO #ScopedDupSPN
  4277. SELECT QUOTENAME(@SPN), QUOTENAME(REPLACE([Output], CHAR(9), '')) FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND line < @linemax;
  4278. END
  4279. FETCH NEXT FROM curSPN INTO @line, @SPN
  4280. END
  4281. CLOSE curSPN
  4282. DEALLOCATE curSPN
  4283. END
  4284. IF EXISTS (SELECT TOP 1 [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%')
  4285. BEGIN
  4286. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%' AND [Output] LIKE @SPNMachine)
  4287. BEGIN
  4288. 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
  4289. END
  4290. ELSE
  4291. BEGIN
  4292. 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];
  4293. END
  4294. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%' AND [Output] NOT LIKE @SPNMachine)
  4295. BEGIN
  4296. 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
  4297. END
  4298. END
  4299. ELSE
  4300. BEGIN
  4301. 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];
  4302. END
  4303. IF (SELECT COUNT(*) FROM #ScopedDupSPN) > 0
  4304. BEGIN
  4305. 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
  4306. END
  4307. ELSE
  4308. BEGIN
  4309. SELECT 'Service_Account_checks' AS [Category], 'Dup_MSSQLSvc_SPNs_Acct_CurrServer' AS [Check], '[OK]' AS [Deviation];
  4310. END
  4311. IF (SELECT COUNT(*) FROM #FinalDupSPN) > 0
  4312. BEGIN
  4313. 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
  4314. END
  4315. ELSE
  4316. BEGIN
  4317. SELECT 'Service_Account_checks' AS [Category], 'Dup_MSSQLSvc_SPNs_Acct' AS [Check], '[OK]' AS [Deviation];
  4318. END
  4319. END TRY
  4320. BEGIN CATCH
  4321. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4322. SELECT @ErrorMessage = 'Service Accounts and SPN registration subsection - Error raised in TRY block 9. ' + ERROR_MESSAGE()
  4323. RAISERROR (@ErrorMessage, 16, 1);
  4324. END CATCH
  4325. IF @xcmd = 0
  4326. BEGIN
  4327. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  4328. END
  4329. IF @sao = 0
  4330. BEGIN
  4331. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  4332. END
  4333. END
  4334. ELSE
  4335. BEGIN
  4336. 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')
  4337. 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')
  4338. --RETURN
  4339. END
  4340. END
  4341. ELSE
  4342. BEGIN
  4343. 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')
  4344. --RETURN
  4345. END;
  4346. RAISERROR (N'|-Starting Instance Checks', 10, 1) WITH NOWAIT
  4347. --------------------------------------------------------------------------------------------------------------------------------
  4348. -- Recommended build check subsection
  4349. --------------------------------------------------------------------------------------------------------------------------------
  4350. RAISERROR (N' |-Starting Recommended build check', 10, 1) WITH NOWAIT
  4351. SELECT 'Instance_checks' AS [Category], 'Recommended_Build' AS [Check],
  4352. CASE WHEN (@sqlmajorver = 9 AND @sqlbuild < 5000)
  4353. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild < 6000)
  4354. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild < 6000)
  4355. OR (@sqlmajorver = 11 AND @sqlbuild < 6020)
  4356. OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  4357. OR (@sqlmajorver = 13 AND @sqlbuild < 4000)
  4358. THEN '[WARNING: current service pack has been superseded in the current SQL Server version. Install the latest service pack as soon as possible.]'
  4359. ELSE '[OK]'
  4360. END AS [Deviation],
  4361. CASE WHEN @sqlmajorver = 9 THEN '2005'
  4362. WHEN @sqlmajorver = 10 AND @sqlminorver = 0 THEN '2008'
  4363. WHEN @sqlmajorver = 10 AND @sqlminorver = 50 THEN '2008R2'
  4364. WHEN @sqlmajorver = 11 THEN '2012'
  4365. WHEN @sqlmajorver = 12 THEN '2014'
  4366. WHEN @sqlmajorver = 13 THEN '2016'
  4367. END AS [Product_Major_Version],
  4368. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductLevel')) AS Product_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('ProductBuildType')) ELSE 'NA' END AS Product_Build_Type,
  4370. 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,
  4371. 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;
  4372. --------------------------------------------------------------------------------------------------------------------------------
  4373. -- Backup checks subsection
  4374. --------------------------------------------------------------------------------------------------------------------------------
  4375. RAISERROR (N' |-Starting Backup checks', 10, 1) WITH NOWAIT
  4376. DECLARE @nolog int, @nobck int, @nolog24h int, @neverlog int, @neverbck int
  4377. -- No Full backups
  4378. SELECT @neverbck = COUNT(DISTINCT d.name)
  4379. FROM master.sys.databases d (NOLOCK)
  4380. INNER JOIN #tmpdbs_userchoice tuc ON d.database_id = tuc.[dbid]
  4381. WHERE database_id NOT IN (2,3)
  4382. AND source_database_id IS NULL -- no snapshots
  4383. 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
  4384. -- No Full backups in last 7 days
  4385. ;WITH cteFullBcks (cnt) AS (SELECT DISTINCT database_name AS cnt
  4386. FROM msdb.dbo.backupset b (NOLOCK)
  4387. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4388. WHERE b.type = 'D' -- Full backup
  4389. AND b.is_copy_only = 0 -- No COPY_ONLY backups
  4390. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4391. WHERE database_id NOT IN (2,3)
  4392. AND source_database_id IS NULL) -- no snapshots
  4393. GROUP BY database_name
  4394. HAVING MAX(backup_finish_date) <= DATEADD(dd, -7, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) + 1, 0)))
  4395. SELECT @nobck = COUNT(cnt)
  4396. FROM cteFullBcks;
  4397. -- Last Log backup precedes last full or diff backup, and DB in Full or Bulk-logged RM
  4398. ;WITH cteLogBcks (cnt) AS (SELECT DISTINCT database_name
  4399. FROM msdb.dbo.backupset b (NOLOCK)
  4400. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4401. WHERE b.type = 'L' -- Log backup
  4402. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4403. WHERE database_id NOT IN (2,3)
  4404. AND source_database_id IS NULL -- no snapshots
  4405. AND recovery_model < 3) -- not SIMPLE recovery model
  4406. GROUP BY [database_name]
  4407. 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
  4408. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4409. AND c.database_name = b.database_name))
  4410. SELECT @nolog = COUNT(cnt)
  4411. FROM cteLogBcks;
  4412. -- No Log backup since last full or diff backup, and DB in Full or Bulk-logged RM
  4413. SELECT @neverlog = COUNT(DISTINCT database_name)
  4414. FROM msdb.dbo.backupset b (NOLOCK)
  4415. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4416. WHERE database_name IN (SELECT name
  4417. FROM master.sys.databases (NOLOCK)
  4418. WHERE database_id NOT IN (2,3)
  4419. AND source_database_id IS NULL -- no snapshots
  4420. AND recovery_model < 3) -- not SIMPLE recovery model
  4421. AND EXISTS (SELECT DISTINCT database_name
  4422. FROM msdb.dbo.backupset c (NOLOCK)
  4423. WHERE c.type IN ('D','I') -- Full or Differential backup
  4424. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4425. AND c.database_name = b.database_name) -- Log backup
  4426. AND NOT EXISTS (SELECT DISTINCT database_name
  4427. FROM msdb.dbo.backupset c (NOLOCK)
  4428. WHERE c.type = 'L' -- Log Backup
  4429. AND c.database_name = b.database_name);
  4430. -- Log backup since last full or diff backup is older than 24h, and DB in Full ar Bulk-logged RM
  4431. ;WITH cteLogBcks2 (cnt) AS (SELECT DISTINCT database_name
  4432. FROM msdb.dbo.backupset b (NOLOCK)
  4433. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4434. WHERE b.type = 'L' -- Log backup
  4435. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4436. WHERE database_id NOT IN (2,3)
  4437. AND source_database_id IS NULL -- no snapshots
  4438. AND recovery_model < 3) -- not SIMPLE recovery model
  4439. GROUP BY database_name
  4440. 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
  4441. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4442. AND c.database_name = b.database_name)
  4443. AND MAX(backup_finish_date) <= DATEADD(hh, -24, GETDATE()))
  4444. SELECT @nolog24h = COUNT(cnt)
  4445. FROM cteLogBcks2;
  4446. IF @nobck > 0 OR @neverbck > 0
  4447. BEGIN
  4448. 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]
  4449. -- No full backups in last 7 days
  4450. SELECT DISTINCT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Information], database_name AS [Database_Name], MAX(backup_finish_date) AS Lst_Full_Backup
  4451. FROM msdb.dbo.backupset b (NOLOCK)
  4452. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4453. WHERE b.type = 'D' -- Full backup
  4454. AND b.is_copy_only = 0 -- No COPY_ONLY backups
  4455. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4456. WHERE database_id NOT IN (2,3)
  4457. AND source_database_id IS NULL) -- no snapshots
  4458. GROUP BY database_name
  4459. HAVING MAX(backup_finish_date) <= DATEADD(dd, -7, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) + 1, 0))
  4460. UNION ALL
  4461. -- No full backups in history
  4462. SELECT DISTINCT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Information], d.name AS [Database_Name], NULL AS Lst_Full_Backup
  4463. FROM master.sys.databases d (NOLOCK)
  4464. INNER JOIN #tmpdbs_userchoice tuc ON d.database_id = tuc.[dbid]
  4465. WHERE database_id NOT IN (2,3)
  4466. AND source_database_id IS NULL -- no snapshots
  4467. AND recovery_model < 3 -- not SIMPLE recovery model
  4468. 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
  4469. AND d.name NOT IN (SELECT b.database_name FROM msdb.dbo.backupset b WHERE b.type = 'L') -- Log backup
  4470. ORDER BY [Database_Name]
  4471. END
  4472. ELSE
  4473. BEGIN
  4474. SELECT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Check], '[OK]' AS [Deviation]
  4475. END;
  4476. IF @nolog > 0 OR @neverlog > 0
  4477. BEGIN
  4478. 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]
  4479. ;WITH Bck AS (SELECT database_name, MAX(backup_finish_date) AS backup_finish_date
  4480. FROM msdb.dbo.backupset (NOLOCK) b
  4481. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4482. WHERE [type] IN ('D','I') -- Full or Differential backup
  4483. GROUP BY database_name)
  4484. -- Log backups since last full or diff is older than 24h
  4485. 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,
  4486. (SELECT backup_finish_date FROM Bck c WHERE c.database_name = b.database_name) AS Lst_FullDiff_Backup
  4487. FROM msdb.dbo.backupset b (NOLOCK)
  4488. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4489. WHERE b.type = 'L' -- Log backup
  4490. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4491. WHERE database_id NOT IN (2,3)
  4492. AND source_database_id IS NULL -- no snapshots
  4493. AND recovery_model < 3) -- not SIMPLE recovery model
  4494. GROUP BY [database_name]
  4495. HAVING MAX(backup_finish_date) < (SELECT backup_finish_date FROM Bck c WHERE c.database_name = b.database_name)
  4496. UNION ALL
  4497. -- No log backup in history but full backup exists
  4498. 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
  4499. FROM msdb.dbo.backupset b (NOLOCK)
  4500. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4501. WHERE database_name IN (SELECT name
  4502. FROM master.sys.databases (NOLOCK)
  4503. WHERE database_id NOT IN (2,3)
  4504. AND source_database_id IS NULL -- no snapshots
  4505. AND recovery_model < 3) -- not SIMPLE recovery model
  4506. AND EXISTS (SELECT DISTINCT database_name
  4507. FROM msdb.dbo.backupset c (NOLOCK)
  4508. WHERE c.type IN ('D','I') -- Full or Differential backup
  4509. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4510. AND c.database_name = b.database_name) -- Log backup
  4511. AND NOT EXISTS (SELECT DISTINCT database_name
  4512. FROM msdb.dbo.backupset c (NOLOCK)
  4513. WHERE c.type = 'L' -- Log Backup
  4514. AND c.database_name = b.database_name)
  4515. GROUP BY database_name
  4516. ORDER BY database_name;
  4517. END
  4518. ELSE
  4519. BEGIN
  4520. SELECT 'Instance_checks' AS [Category], 'No_Log_Bcks_since_LstFullorDiff' AS [Check], '[OK]' AS [Deviation]
  4521. END;
  4522. IF @nolog24h > 0
  4523. BEGIN
  4524. 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]
  4525. 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
  4526. FROM msdb.dbo.backupset b (NOLOCK)
  4527. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4528. WHERE b.type = 'L' -- Log backup
  4529. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4530. WHERE database_id NOT IN (2,3)
  4531. AND recovery_model < 3) -- not SIMPLE recovery model
  4532. GROUP BY database_name
  4533. 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
  4534. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4535. AND c.database_name = b.database_name)
  4536. AND MAX(backup_finish_date) <= DATEADD(hh, -24, GETDATE())
  4537. ORDER BY [database_name];
  4538. END
  4539. ELSE
  4540. BEGIN
  4541. SELECT 'Instance_checks' AS [Category], 'Log_Bcks_since_LstFullorDiff_are_older_than_24H' AS [Check], '[OK]' AS [Deviation]
  4542. END;
  4543. --------------------------------------------------------------------------------------------------------------------------------
  4544. -- Global trace flags subsection
  4545. --------------------------------------------------------------------------------------------------------------------------------
  4546. RAISERROR (N' |-Starting Global trace flags', 10, 1) WITH NOWAIT
  4547. DECLARE @tracestatus TABLE (TraceFlag NVARCHAR(40), [Status] tinyint, [Global] tinyint, [Session] tinyint);
  4548. INSERT INTO @tracestatus
  4549. EXEC ('DBCC TRACESTATUS WITH NO_INFOMSGS')
  4550. IF @sqlmajorver >= 11
  4551. BEGIN
  4552. DECLARE @dbname0 VARCHAR(1000), @dbid0 int, @sqlcmd0 NVARCHAR(4000), @has_colstrix int
  4553. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  4554. DROP TABLE #tblColStoreIXs;
  4555. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  4556. CREATE TABLE #tblColStoreIXs ([DBName] VARCHAR(1000), [Schema] VARCHAR(100), [Table] VARCHAR(255), [Object] VARCHAR(255));
  4557. UPDATE #tmpdbs0
  4558. SET isdone = 0;
  4559. UPDATE #tmpdbs0
  4560. SET isdone = 1
  4561. WHERE [state] <> 0 OR [dbid] < 5;
  4562. UPDATE #tmpdbs0
  4563. SET isdone = 1
  4564. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  4565. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  4566. BEGIN
  4567. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  4568. BEGIN
  4569. SELECT TOP 1 @dbname0 = [dbname], @dbid0 = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  4570. SET @sqlcmd0 = 'USE ' + QUOTENAME(@dbname0) + ';
  4571. SELECT ''' + @dbname0 + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), i.name
  4572. FROM sys.indexes AS i (NOLOCK)
  4573. INNER JOIN sys.objects AS o (NOLOCK) ON o.[object_id] = i.[object_id]
  4574. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = i.[object_id]
  4575. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  4576. WHERE i.[type] IN (5,6,7)' -- 5 = Clustered columnstore; 6 = Nonclustered columnstore; 7 = Nonclustered hash
  4577. BEGIN TRY
  4578. INSERT INTO #tblColStoreIXs
  4579. EXECUTE sp_executesql @sqlcmd0
  4580. END TRY
  4581. BEGIN CATCH
  4582. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4583. SELECT @ErrorMessage = 'Global trace flags subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  4584. RAISERROR (@ErrorMessage, 16, 1);
  4585. END CATCH
  4586. UPDATE #tmpdbs0
  4587. SET isdone = 1
  4588. WHERE [dbid] = @dbid0
  4589. END
  4590. END;
  4591. SELECT @has_colstrix = COUNT(*) FROM #tblColStoreIXs
  4592. END;
  4593. IF (SELECT COUNT(TraceFlag) FROM @tracestatus WHERE [Global]=1) = 0
  4594. BEGIN
  4595. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check], '[There are no Global Trace Flags active]' AS [Deviation]
  4596. END;
  4597. -- Plan affecting TFs: http://support.microsoft.com/kb/2801413 and https://support.microsoft.com/en-us/kb/2964518
  4598. -- All supported TFs: http://msdn.microsoft.com/library/ms188396.aspx
  4599. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1)
  4600. BEGIN
  4601. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 634)
  4602. BEGIN
  4603. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4604. '[INFORMATION: TF634 disables the background columnstore compression task]'
  4605. AS [Deviation], TraceFlag
  4606. FROM @tracestatus
  4607. WHERE [Global] = 1 AND TraceFlag = 634
  4608. END;
  4609. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 652)
  4610. BEGIN
  4611. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4612. '[INFORMATION: TF652 disables read-aheads during scans]' --http://support.microsoft.com/en-us/kb/920093
  4613. AS [Deviation], TraceFlag
  4614. FROM @tracestatus
  4615. WHERE [Global] = 1 AND TraceFlag = 634
  4616. END;
  4617. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 661)
  4618. BEGIN
  4619. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4620. '[INFORMATION: TF661 disables the ghost cleanup background task]'
  4621. AS [Deviation], TraceFlag
  4622. FROM @tracestatus
  4623. WHERE [Global] = 1 AND TraceFlag = 661
  4624. END;
  4625. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 834)
  4626. BEGIN
  4627. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4628. CASE WHEN @sqlmajorver >= 11
  4629. AND @has_colstrix > 0
  4630. THEN '[WARNING: TF834 (Large Page Support for BP) is discouraged when Columnstore Indexes are used]'
  4631. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4632. END AS [Deviation], TraceFlag
  4633. FROM @tracestatus
  4634. WHERE [Global] = 1 AND TraceFlag = 834
  4635. END;
  4636. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 845)
  4637. BEGIN
  4638. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4639. CASE WHEN SERVERPROPERTY('EngineEdition') = 2 --Standard SKU
  4640. AND ((@sqlmajorver = 10 AND ((@sqlminorver = 0 AND @sqlbuild >= 2714) OR @sqlminorver = 50))
  4641. OR (@sqlmajorver = 9 AND @sqlbuild >= 4226))
  4642. THEN '[INFORMATION: TF845 supports locking pages in memory in SQL Server Standard Editions]'
  4643. WHEN SERVERPROPERTY('EngineEdition') = 2 --Standard SKU
  4644. AND @sqlmajorver = 11
  4645. THEN '[WARNING: TF845 is not needed in SQL 2012 and above]'
  4646. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4647. END AS [Deviation], TraceFlag
  4648. FROM @tracestatus
  4649. WHERE [Global] = 1 AND TraceFlag = 845
  4650. END;
  4651. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 902)
  4652. BEGIN
  4653. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4654. '[WARNING: TF902 Bypasses execution of database upgrade script when installing a Cumulative Update or Service Pack]'
  4655. AS [Deviation], TraceFlag
  4656. FROM @tracestatus
  4657. WHERE [Global] = 1 AND TraceFlag = 902
  4658. END;
  4659. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1117)
  4660. BEGIN
  4661. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4662. '[INFORMATION: TF1117 autogrows all files at the same time and affects all databases]'
  4663. AS [Deviation], TraceFlag
  4664. FROM @tracestatus
  4665. WHERE [Global] = 1 AND TraceFlag = 1117
  4666. END;
  4667. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1118)
  4668. BEGIN
  4669. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4670. '[INFORMATION: TF1118 forces uniform extent allocations instead of mixed page allocations]'
  4671. AS [Deviation], TraceFlag
  4672. FROM @tracestatus
  4673. WHERE [Global] = 1 AND TraceFlag = 1118
  4674. END;
  4675. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1204)
  4676. BEGIN
  4677. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4678. '[INFORMATION: TF1204 returns the resources and types of locks participating in a deadlock and also the current command affected]'
  4679. AS [Deviation], TraceFlag
  4680. FROM @tracestatus
  4681. WHERE [Global] = 1 AND TraceFlag = 1204
  4682. END;
  4683. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1211)
  4684. BEGIN
  4685. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4686. '[WARNING: TF1211 disables lock escalation based on memory pressure, or based on number of locks, increasing the amount of locks held]'
  4687. AS [Deviation], TraceFlag
  4688. FROM @tracestatus
  4689. WHERE [Global] = 1 AND TraceFlag = 1211
  4690. END;
  4691. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1222)
  4692. BEGIN
  4693. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4694. '[INFORMATION: TF1222 returns the resources and types of locks participating in a deadlock and also the current command affected]'
  4695. AS [Deviation], TraceFlag
  4696. FROM @tracestatus
  4697. WHERE [Global] = 1 AND TraceFlag = 1222
  4698. END;
  4699. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1224)
  4700. BEGIN
  4701. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4702. '[WARNING: TF1224 disables lock escalation based on the number of locks, and only escalates locks under memory pressure, increasing the amount of locks held]'
  4703. AS [Deviation], TraceFlag
  4704. FROM @tracestatus
  4705. WHERE [Global] = 1 AND TraceFlag = 1224
  4706. END;
  4707. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1229)
  4708. BEGIN
  4709. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4710. '[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
  4711. AS [Deviation], TraceFlag
  4712. FROM @tracestatus
  4713. WHERE [Global] = 1 AND TraceFlag = 1229
  4714. END;
  4715. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1236)
  4716. BEGIN
  4717. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4718. CASE WHEN @sqlmajorver = 9 OR @sqlmajorver = 10 OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 4100)
  4719. THEN '[INFORMATION: TF1236 enables database lock partitioning]'
  4720. WHEN (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 4100) OR @sqlmajorver = 13
  4721. THEN '[WARNING: TF1236 is not needed in SQL 2012 SP3, SQL Server 2014 SP1 and above]'
  4722. END AS [Deviation], TraceFlag
  4723. FROM @tracestatus
  4724. WHERE [Global] = 1 AND TraceFlag = 1236
  4725. END;
  4726. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1462)
  4727. BEGIN
  4728. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4729. '[WARNING: TF1462 disables log stream compression for asynchronous availability groups]'
  4730. AS [Deviation], TraceFlag
  4731. FROM @tracestatus
  4732. WHERE [Global] = 1 AND TraceFlag = 1462
  4733. END;
  4734. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2312)
  4735. BEGIN
  4736. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4737. CASE WHEN @sqlmajorver = 12
  4738. THEN '[INFORMATION: TF2312 enables New CE model, SQL Server 2014 version]'
  4739. WHEN @sqlmajorver = 13
  4740. THEN '[INFORMATION: TF2312 enables New CE model to SQL Server 2014 or SQL Server 2016 versions, dependent of the compatibility level of the database]'
  4741. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4742. END AS [Deviation], TraceFlag
  4743. FROM @tracestatus
  4744. WHERE [Global] = 1 AND TraceFlag = 2312
  4745. END;
  4746. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2330)
  4747. BEGIN
  4748. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4749. CASE WHEN @sqlmajorver = 9
  4750. 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
  4751. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4752. END AS [Deviation], TraceFlag
  4753. FROM @tracestatus
  4754. WHERE [Global] = 1 AND TraceFlag = 2330
  4755. END;
  4756. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2335)
  4757. BEGIN
  4758. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4759. CASE WHEN @sqlmajorver >= 9
  4760. AND @maxservermem >= 100000 * 1024 -- 100GB
  4761. AND @maxservermem <> 2147483647
  4762. THEN '[INFORMATION: TF2335 assumes a fixed amount of memory is available during query optimization. Recommended when server has more than 100GB of memory]'
  4763. WHEN @sqlmajorver >= 9
  4764. AND @maxservermem < 100000 * 1024 -- 100GB
  4765. AND @maxservermem <> 2147483647
  4766. THEN '[WARNING: TF2335 should not be set on servers with less than 100GB of memory]'
  4767. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4768. END AS [Deviation], TraceFlag
  4769. FROM @tracestatus
  4770. WHERE [Global] = 1 AND TraceFlag = 2335
  4771. END;
  4772. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2335)
  4773. AND @sqlmajorver >= 9
  4774. AND @maxservermem >= 100000 * 1024 -- 100GB
  4775. AND @maxservermem <> 2147483647
  4776. BEGIN
  4777. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4778. '[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
  4779. AS [Deviation]
  4780. END;
  4781. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2340)
  4782. BEGIN
  4783. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4784. '[INFORMATION: TF2340 causes SQL Server not to use a sort operation (batch sort) for optimized nested loop joins when generating a plan]'
  4785. AS [Deviation], TraceFlag
  4786. FROM @tracestatus
  4787. WHERE [Global] = 1 AND TraceFlag = 2340
  4788. END;
  4789. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2371)
  4790. BEGIN
  4791. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4792. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500) OR @sqlmajorver >= 11
  4793. THEN '[INFORMATION: TF2371 changes the fixed rate of the 20pct threshold for update statistics into a dynamic percentage rate]'
  4794. WHEN @sqlmajorver = 13
  4795. THEN '[WARNING: TF2371 is not needed in SQL 2016 and above]'
  4796. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4797. END AS [Deviation], TraceFlag
  4798. FROM @tracestatus
  4799. WHERE [Global] = 1 AND TraceFlag = 2371
  4800. END;
  4801. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2371)
  4802. AND ((@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500) OR @sqlmajorver >= 11)
  4803. BEGIN
  4804. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4805. '[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
  4806. AS [Deviation]
  4807. END;
  4808. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2389)
  4809. BEGIN
  4810. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4811. '[INFORMATION: TF2389 enables automatically generated quick statistics for ascending keys (histogram amendment)]'
  4812. AS [Deviation], TraceFlag
  4813. FROM @tracestatus
  4814. WHERE [Global] = 1 AND TraceFlag = 2389
  4815. END;
  4816. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2528)
  4817. BEGIN
  4818. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4819. '[INFORMATION: TF2528 disables parallel checking of objects by DBCC CHECKDB, DBCC CHECKFILEGROUP, and DBCC CHECKTABLE]'
  4820. AS [Deviation], TraceFlag
  4821. FROM @tracestatus
  4822. WHERE [Global] = 1 AND TraceFlag = 2528
  4823. END;
  4824. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2549)
  4825. BEGIN
  4826. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4827. '[INFORMATION: TF2549 runs the DBCC CHECKDB command assuming each database file is on a unique disk drive]'
  4828. AS [Deviation], TraceFlag
  4829. FROM @tracestatus
  4830. WHERE [Global] = 1 AND TraceFlag = 2549
  4831. END;
  4832. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2562)
  4833. BEGIN
  4834. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4835. '[INFORMATION: TF2562 runs the DBCC CHECKDB command in a single batch regardless of the number of indexes in the database]'
  4836. AS [Deviation], TraceFlag
  4837. FROM @tracestatus
  4838. WHERE [Global] = 1 AND TraceFlag = 2562
  4839. END;
  4840. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2566)
  4841. BEGIN
  4842. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4843. '[INFORMATION: TF2566 runs the DBCC CHECKDB command without data purity check unless DATA_PURITY option is specified]'
  4844. AS [Deviation], TraceFlag
  4845. FROM @tracestatus
  4846. WHERE [Global] = 1 AND TraceFlag = 2566
  4847. END;
  4848. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3023)
  4849. BEGIN
  4850. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4851. '[INFORMATION: TF3023 enables CHECKSUM option as default for BACKUP command]'
  4852. AS [Deviation], TraceFlag
  4853. FROM @tracestatus
  4854. WHERE [Global] = 1 AND TraceFlag = 3023
  4855. END;
  4856. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3042)
  4857. BEGIN
  4858. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4859. '[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]'
  4860. AS [Deviation], TraceFlag
  4861. FROM @tracestatus
  4862. WHERE [Global] = 1 AND TraceFlag = 3042
  4863. END;
  4864. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3226)
  4865. BEGIN
  4866. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4867. '[INFORMATION: TF3226 prevents SQL Server from recording an entry to Errorlog on every successful backup operation]'
  4868. AS [Deviation], TraceFlag
  4869. FROM @tracestatus
  4870. WHERE [Global] = 1 AND TraceFlag = 3226
  4871. END;
  4872. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4135)
  4873. BEGIN
  4874. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4875. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1818 AND 1835)
  4876. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1702)
  4877. THEN '[WARNING: TF4199 should be used instead of TF4135 in this SQL build]'
  4878. ELSE '[INFORMATION: TF4135 enables query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  4879. END AS [Deviation], TraceFlag
  4880. FROM @tracestatus
  4881. WHERE [Global] = 1 AND TraceFlag = 4135
  4882. END;
  4883. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4136)
  4884. BEGIN
  4885. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4886. CASE WHEN (@sqlmajorver = 9 AND @sqlbuild >= 4294)
  4887. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 2766)
  4888. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1720)
  4889. OR (@sqlmajorver = 11 AND @sqlbuild >= 2316)
  4890. OR @sqlmajorver >= 12
  4891. THEN '[INFORMATION: TF4136 disables parameter sniffing unless OPTION(RECOMPILE), WITH RECOMPILE or OPTIMIZE FOR value is used]'
  4892. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4893. END AS [Deviation], TraceFlag
  4894. FROM @tracestatus
  4895. WHERE [Global] = 1 AND TraceFlag = 4136
  4896. END;
  4897. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4137)
  4898. BEGIN
  4899. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4900. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 5794)
  4901. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 4326 AND 4371)
  4902. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2806)
  4903. OR (@sqlmajorver = 11 AND @sqlbuild >= 2316)
  4904. OR @sqlmajorver >= 12
  4905. 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]'
  4906. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4907. END AS [Deviation], TraceFlag
  4908. FROM @tracestatus
  4909. WHERE [Global] = 1 AND TraceFlag = 4137
  4910. END;
  4911. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4138)
  4912. BEGIN
  4913. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4914. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4260)
  4915. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 2817 AND 2881)
  4916. OR (@sqlmajorver = 11 AND @sqlbuild >= 2325)
  4917. OR @sqlmajorver >= 12
  4918. 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]'
  4919. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4920. END AS [Deviation], TraceFlag
  4921. FROM @tracestatus
  4922. WHERE [Global] = 1 AND TraceFlag = 4138
  4923. END;
  4924. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4139)
  4925. BEGIN
  4926. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4927. CASE WHEN (@sqlmajorver = 11 AND @sqlbuild >= 5532)
  4928. OR (@sqlmajorver = 11 AND @sqlbuild >= 3431 AND @sqlbuild < 5058)
  4929. OR @sqlmajorver >= 12
  4930. THEN '[INFORMATION: TF4139 enables automatically generated quick statistics (histogram amendment) regardless of key column status]'
  4931. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4932. END AS [Deviation], TraceFlag
  4933. FROM @tracestatus
  4934. WHERE [Global] = 1 AND TraceFlag = 4139
  4935. END;
  4936. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4199)
  4937. BEGIN
  4938. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4939. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1787 AND 1812)
  4940. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 2531 AND 2757)
  4941. OR (@sqlmajorver >= 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 1600 AND 1617)
  4942. THEN '[WARNING: TF4135 should be used instead of TF4199 in this SQL build]'
  4943. ELSE '[INFORMATION: TF4199 enables query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  4944. END AS [Deviation], TraceFlag
  4945. FROM @tracestatus
  4946. WHERE [Global] = 1 AND TraceFlag = 4199
  4947. END;
  4948. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 6498)
  4949. BEGIN
  4950. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4951. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 4416)
  4952. OR (@sqlmajorver = 12 AND @sqlbuild BETWEEN 2480 AND 2474)
  4953. THEN '[INFORMATION: TF6498 enables more than one large query compilation to gain access to the big gateway when there is sufficient memory available]'
  4954. WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver >= 13
  4955. THEN '[WARNING: TF6498 is not needed in SQL 2014 SP2, SQL Server 2016 and above]'
  4956. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4957. END AS [Deviation], TraceFlag
  4958. FROM @tracestatus
  4959. WHERE [Global] = 1 AND TraceFlag = 6498
  4960. END;
  4961. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag IN (6532,6533))
  4962. BEGIN
  4963. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4964. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000)
  4965. OR (@sqlmajorver = 11 AND @sqlbuild >= 6020)
  4966. THEN '[INFORMATION: TF6532 and TF 6533 enable performance improvement of query operations with spatial data types]'
  4967. WHEN @sqlmajorver = 13
  4968. THEN '[WARNING: TF6532 and TF 6533 are not needed in SQL Server 2016 and above]'
  4969. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4970. END AS [Deviation], TraceFlag
  4971. FROM @tracestatus
  4972. WHERE [Global] = 1 AND TraceFlag IN (6532,6533)
  4973. END;
  4974. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 6534)
  4975. BEGIN
  4976. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4977. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000)
  4978. OR (@sqlmajorver = 11 AND @sqlbuild >= 6020)
  4979. OR @sqlmajorver = 13
  4980. THEN '[INFORMATION: TF6534 enables performance improvement of query operations with spatial data types]'
  4981. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4982. END AS [Deviation], TraceFlag
  4983. FROM @tracestatus
  4984. WHERE [Global] = 1 AND TraceFlag = 6534
  4985. END;
  4986. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8015)
  4987. BEGIN
  4988. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4989. CASE WHEN (@sqlmajorver = 11 AND @sqlbuild >= 3349)
  4990. OR @sqlmajorver >= 12
  4991. 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
  4992. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4993. END AS [Deviation], TraceFlag
  4994. FROM @tracestatus
  4995. WHERE [Global] = 1 AND TraceFlag = 8015
  4996. END;
  4997. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8032)
  4998. BEGIN
  4999. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5000. CASE WHEN @sqlmajorver >= 10
  5001. 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]'
  5002. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5003. END AS [Deviation], TraceFlag
  5004. FROM @tracestatus
  5005. WHERE [Global] = 1 AND TraceFlag = 8032
  5006. END;
  5007. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8048)
  5008. BEGIN
  5009. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5010. CASE WHEN ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5011. OR (@sqlmajorver BETWEEN 9 AND 11))
  5012. AND (@cpucount/@numa) > 8
  5013. 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
  5014. WHEN (@sqlmajorver = 12 AND @sqlbuild >= 4100) OR @sqlmajorver >= 13
  5015. THEN '[WARNING: TF8048 is not needed in SQL Server 2014 SP2, SQL Server 2016 and above]'
  5016. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5017. END AS [Deviation], TraceFlag
  5018. FROM @tracestatus
  5019. WHERE [Global] = 1 AND TraceFlag = 8048
  5020. END;
  5021. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8048)
  5022. AND ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5023. OR (@sqlmajorver BETWEEN 9 AND 11))
  5024. AND (@cpucount/@numa) > 8
  5025. BEGIN
  5026. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5027. '[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
  5028. AS [Deviation];
  5029. -- If the top consumers are partitioned by Node, then use startup trace flag 8048 to further partition by CPU.
  5030. IF @sqlmajorver < 11
  5031. BEGIN
  5032. SELECT 'Instance_checks' AS [Category], 'Is_TF8048_Applicable' AS [Check], [type],
  5033. SUM(page_size_in_bytes)/8192 AS [pages],
  5034. SUM(page_size_in_bytes)/1024 AS pages_in_KB,
  5035. CASE WHEN (0x20 = creation_options & 0x20) THEN 'Global PMO. Cannot be partitioned by CPU/NUMA Node. TF8048 not applicable.'
  5036. WHEN (0x40 = creation_options & 0x40) THEN 'Partitioned by CPU. TF8048 not applicable.'
  5037. WHEN (0x80 = creation_options & 0x80) THEN 'Partitioned by Node. Use TF8048 to further partition by CPU'
  5038. ELSE 'Unknown' END AS [Comment]
  5039. FROM sys.dm_os_memory_objects
  5040. GROUP BY [type], creation_options
  5041. ORDER BY SUM(page_size_in_bytes) DESC;
  5042. END
  5043. ELSE
  5044. BEGIN
  5045. SET @sqlcmd = N'SELECT ''Instance_checks'' AS [Category], ''Is_TF8048_Applicable'' AS [Check], [type],
  5046. SUM(pages_in_bytes)/8192 AS [pages],
  5047. SUM(pages_in_bytes)/1024 AS pages_in_KB,
  5048. CASE WHEN (0x20 = creation_options & 0x20) THEN ''Global PMO. Cannot be partitioned by CPU/NUMA Node. TF8048 not applicable.''
  5049. WHEN (0x40 = creation_options & 0x40) THEN ''Partitioned by CPU. TF8048 not applicable.''
  5050. WHEN (0x80 = creation_options & 0x80) THEN ''Partitioned by Node. Use TF8048 to further partition by CPU''
  5051. ELSE ''Unknown'' END AS [Comment]
  5052. FROM sys.dm_os_memory_objects
  5053. GROUP BY [type], creation_options
  5054. ORDER BY SUM(pages_in_bytes) DESC;'
  5055. EXECUTE sp_executesql @sqlcmd
  5056. END;
  5057. END;
  5058. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8744)
  5059. BEGIN
  5060. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5061. CASE WHEN @sqlmajorver >= 12 THEN
  5062. '[INFORMATION: TF8744 disables pre-fetching for the Nested Loop operator]'
  5063. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5064. END AS [Deviation], TraceFlag
  5065. FROM @tracestatus
  5066. WHERE [Global] = 1 AND TraceFlag = 8744
  5067. END;
  5068. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9024)
  5069. BEGIN
  5070. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5071. CASE WHEN ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5072. OR (@sqlmajorver = 11 AND @sqlbuild >= 3349 AND @sqlbuild < 6020))
  5073. AND (@cpucount/@numa) > 8
  5074. THEN '[INFORMATION: TF9024 converts a global log pool memory object into NUMA node partitioned memory object]'
  5075. WHEN (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427) OR @sqlmajorver > 12
  5076. THEN '[WARNING: TF9024 is not needed in SQL Server 2012 SP3, SQL Server 2014 SP1 and above]'
  5077. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5078. END AS [Deviation], TraceFlag
  5079. FROM @tracestatus
  5080. WHERE [Global] = 1 AND TraceFlag = 9024
  5081. END;
  5082. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9347)
  5083. BEGIN
  5084. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5085. CASE WHEN @sqlmajorver >= 13 THEN
  5086. '[INFORMATION: TF9347 disables batch mode for sort operator]'
  5087. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5088. END AS [Deviation], TraceFlag
  5089. FROM @tracestatus
  5090. WHERE [Global] = 1 AND TraceFlag = 9347
  5091. END;
  5092. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9349)
  5093. BEGIN
  5094. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5095. CASE WHEN @sqlmajorver >= 13 THEN
  5096. '[INFORMATION: TF9349 disables batch mode for top N sort operator]'
  5097. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5098. END AS [Deviation], TraceFlag
  5099. FROM @tracestatus
  5100. WHERE [Global] = 1 AND TraceFlag = 9349
  5101. END;
  5102. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9389)
  5103. BEGIN
  5104. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5105. CASE WHEN @sqlmajorver >= 13 THEN
  5106. '[INFORMATION: TF9389 enables dynamic memory grant for batch mode operators]'
  5107. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5108. END AS [Deviation], TraceFlag
  5109. FROM @tracestatus
  5110. WHERE [Global] = 1 AND TraceFlag = 9389
  5111. END;
  5112. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9476)
  5113. BEGIN
  5114. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5115. CASE WHEN @sqlmajorver >= 13 THEN
  5116. '[INFORMATION: TF9476 causes SQL Server to generate a plan using the Simple Containment instead of the default Base Containment under New CE]'
  5117. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5118. END AS [Deviation], TraceFlag
  5119. FROM @tracestatus
  5120. WHERE [Global] = 1 AND TraceFlag = 9476
  5121. END;
  5122. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9481)
  5123. BEGIN
  5124. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5125. CASE WHEN @sqlmajorver >= 12
  5126. THEN '[INFORMATION: TF9481 enables Legacy CE model, irrespective of the compatibility level of the database]'
  5127. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5128. END AS [Deviation], TraceFlag
  5129. FROM @tracestatus
  5130. WHERE [Global] = 1 AND TraceFlag = 9481
  5131. END;
  5132. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 10204)
  5133. BEGIN
  5134. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5135. CASE WHEN @sqlmajorver >= 13
  5136. THEN '[INFORMATION: TF10204 disables merge/recompress during columnstore index reorganization]'
  5137. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5138. END AS [Deviation], TraceFlag
  5139. FROM @tracestatus
  5140. WHERE [Global] = 1 AND TraceFlag = 10204
  5141. END;
  5142. END;
  5143. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag IN (4135,4199))
  5144. BEGIN
  5145. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5146. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1787 AND 1812)
  5147. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 2531 AND 2757)
  5148. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 2766)
  5149. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 1600 AND 1617)
  5150. THEN '[INFORMATION: Consider enabling TF4135 to support fixes and enhancements on the query optimizer]'
  5151. WHEN (@sqlmajorver = 9 AND @sqlbuild >= 4266)
  5152. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1818 AND 1835)
  5153. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1702) OR @sqlmajorver >= 11
  5154. THEN '[INFORMATION: Consider enabling TF4199 to enable query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  5155. END AS [Deviation]
  5156. END;
  5157. --------------------------------------------------------------------------------------------------------------------------------
  5158. -- System configurations subsection
  5159. --------------------------------------------------------------------------------------------------------------------------------
  5160. RAISERROR (N' |-Starting System configurations', 10, 1) WITH NOWAIT
  5161. -- Focus on:
  5162. -- backup compression default
  5163. -- clr enabled (only enable if needed)
  5164. -- lightweight pooling (should be zero)
  5165. -- max degree of parallelism
  5166. -- cost threshold for parallelism
  5167. -- max server memory (MB) (set to an appropriate value)
  5168. -- priority boost (should be zero)
  5169. -- remote admin connections (should be enabled in a cluster configuration, to allow remote DAC)
  5170. -- scan for startup procs (should be disabled unless business requirement, like replication)
  5171. -- min memory per query (default is 1024KB)
  5172. -- allow updates (no effect in 2005 or above, but should be off)
  5173. -- max worker threads (should be zero in 2005 or above)
  5174. -- affinity mask and affinity I/O mask (must not overlap)
  5175. DECLARE @awe tinyint, @ssp bit, @bckcomp bit, @clr bit, @costparallel tinyint, @chain bit, @lpooling bit
  5176. DECLARE @adhoc smallint, @pboost bit, @qtimeout int, @cmdshell bit, @deftrace bit, @remote bit, @autoNUMA bit
  5177. DECLARE @minmemqry int, @allowupd bit, @mwthreads int, @recinterval int, @netsize smallint
  5178. DECLARE @ixmem smallint, @adhocqry bit, @locks int, @qrywait int--, @mwthreads_count int
  5179. DECLARE @affin int, @affinIO int, @affin64 int, @affin64IO int, @block_threshold int, @oleauto int
  5180. --SELECT @mwthreads_count = max_workers_count FROM sys.dm_os_sys_info;
  5181. SELECT @adhocqry = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'Ad Hoc Distributed Queries';
  5182. SELECT @affin = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity mask';
  5183. SELECT @affinIO = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity I/O mask';
  5184. SELECT @affin64 = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity64 mask';
  5185. SELECT @affin64IO = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity64 I/O mask';
  5186. SELECT @allowupd = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'allow updates';
  5187. SELECT @block_threshold = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'blocked process threshold (s)';
  5188. SELECT @awe = CONVERT(tinyint, [value]) FROM sys.configurations WHERE [Name] = 'awe enabled';
  5189. SELECT @autoNUMA = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'automatic soft-NUMA disabled';
  5190. SELECT @bckcomp = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'backup compression default';
  5191. SELECT @clr = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'clr enabled';
  5192. SELECT @costparallel = CONVERT(tinyint, [value]) FROM sys.configurations WHERE [Name] = 'cost threshold for parallelism';
  5193. SELECT @chain = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'cross db ownership chaining';
  5194. SELECT @deftrace = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'default trace enabled';
  5195. SELECT @ixmem = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'index create memory (KB)';
  5196. SELECT @locks = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'locks';
  5197. SELECT @minmemqry = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'min memory per query (KB)';
  5198. SELECT @mwthreads = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'max worker threads';
  5199. SELECT @netsize = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'network packet size (B)';
  5200. SELECT @lpooling = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'lightweight pooling';
  5201. SELECT @recinterval = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'recovery interval (min)';
  5202. SELECT @remote = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'remote admin connections';
  5203. SELECT @qrywait = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'query wait (s)';
  5204. SELECT @adhoc = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'optimize for ad hoc workloads';
  5205. SELECT @oleauto = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'Ole Automation Procedures';
  5206. SELECT @pboost = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'priority boost';
  5207. SELECT @qtimeout = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'remote query timeout (s)';
  5208. SELECT @ssp = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'scan for startup procs';
  5209. SELECT @cmdshell = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'xp_cmdshell';
  5210. 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]
  5211. UNION ALL
  5212. 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]
  5213. UNION ALL
  5214. 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]
  5215. UNION ALL
  5216. 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]
  5217. UNION ALL
  5218. 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]
  5219. UNION ALL
  5220. 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]
  5221. UNION ALL
  5222. 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]
  5223. UNION ALL
  5224. 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]
  5225. UNION ALL
  5226. 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]
  5227. UNION ALL
  5228. 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]
  5229. UNION ALL
  5230. 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]
  5231. UNION ALL
  5232. 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]
  5233. UNION ALL
  5234. 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]
  5235. UNION ALL
  5236. 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]
  5237. UNION ALL
  5238. 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]
  5239. UNION ALL
  5240. 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]
  5241. UNION ALL
  5242. 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]
  5243. UNION ALL
  5244. 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]
  5245. UNION ALL
  5246. 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]
  5247. UNION ALL
  5248. 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]
  5249. UNION ALL
  5250. 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]
  5251. UNION ALL
  5252. 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]
  5253. UNION ALL
  5254. 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]
  5255. UNION ALL
  5256. 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]
  5257. UNION ALL
  5258. 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]
  5259. UNION ALL
  5260. 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]
  5261. UNION ALL
  5262. 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];
  5263. IF (SELECT COUNT([Name]) FROM master.sys.configurations WHERE [value] <> [value_in_use] AND [is_dynamic] = 0) > 0
  5264. BEGIN
  5265. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Check], '[WARNING: There are system configurations with differences between running and configured values]' AS [Deviation]
  5266. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Information], [Name] AS [Setting],
  5267. [value] AS 'Config_Value',
  5268. [value_in_use] AS 'Run_Value'
  5269. FROM master.sys.configurations (NOLOCK)
  5270. WHERE [value] <> [value_in_use] AND [is_dynamic] = 0;
  5271. END
  5272. ELSE
  5273. BEGIN
  5274. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Check], '[OK]' AS [Deviation]
  5275. END;
  5276. --------------------------------------------------------------------------------------------------------------------------------
  5277. -- IFI subsection
  5278. --------------------------------------------------------------------------------------------------------------------------------
  5279. RAISERROR (N' |-Starting IFI', 10, 1) WITH NOWAIT
  5280. DECLARE @ifi bit, @IFIStatus NVARCHAR(256)
  5281. IF ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13)
  5282. BEGIN
  5283. IF @allow_xpcmdshell = 1
  5284. BEGIN
  5285. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  5286. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5287. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  5288. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5289. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  5290. BEGIN
  5291. RAISERROR (' |-Configuration options set for IFI check', 10, 1) WITH NOWAIT
  5292. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  5293. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  5294. IF @sao = 0
  5295. BEGIN
  5296. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  5297. END
  5298. IF @xcmd = 0
  5299. BEGIN
  5300. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  5301. END
  5302. BEGIN TRY
  5303. DECLARE @xp_cmdshell_output2 TABLE ([Output] VARCHAR (8000));
  5304. SET @CMD = ('whoami /priv')
  5305. INSERT INTO @xp_cmdshell_output2
  5306. EXEC master.dbo.xp_cmdshell @CMD;
  5307. IF EXISTS (SELECT * FROM @xp_cmdshell_output2 WHERE [Output] LIKE '%SeManageVolumePrivilege%')
  5308. BEGIN
  5309. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[OK]' AS [Deviation];
  5310. SET @ifi = 1;
  5311. END
  5312. ELSE
  5313. BEGIN
  5314. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[WARNING: Instant File Initialization is disabled. This can impact data file autogrowth times]' AS [Deviation];
  5315. SET @ifi = 0
  5316. END
  5317. END TRY
  5318. BEGIN CATCH
  5319. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  5320. SELECT @ErrorMessage = 'IFI subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  5321. RAISERROR (@ErrorMessage, 16, 1);
  5322. END CATCH
  5323. IF @xcmd = 0
  5324. BEGIN
  5325. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  5326. END
  5327. IF @sao = 0
  5328. BEGIN
  5329. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  5330. END
  5331. END
  5332. ELSE
  5333. BEGIN
  5334. 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')
  5335. 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')
  5336. --RETURN
  5337. END
  5338. END
  5339. ELSE
  5340. BEGIN
  5341. RAISERROR(' |- [INFORMATION: "Instant Initialization" check was skipped because xp_cmdshell was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  5342. --RETURN
  5343. END
  5344. END
  5345. ELSE IF ((@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13)
  5346. BEGIN
  5347. 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%''';
  5348. SET @params = N'@IFIStatusOUT NVARCHAR(256) OUTPUT';
  5349. EXECUTE sp_executesql @sqlcmd, @params, @IFIStatusOUT=@IFIStatus OUTPUT;
  5350. IF @IFIStatus = 'Y'
  5351. BEGIN
  5352. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[OK]' AS [Deviation];
  5353. SET @ifi = 1;
  5354. END
  5355. ELSE
  5356. BEGIN
  5357. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[WARNING: Instant File Initialization is disabled. This can impact data file autogrowth times]' AS [Deviation];
  5358. SET @ifi = 0
  5359. END
  5360. END;
  5361. --------------------------------------------------------------------------------------------------------------------------------
  5362. -- Full Text Configurations subsection
  5363. --------------------------------------------------------------------------------------------------------------------------------
  5364. RAISERROR (N' |-Starting Full Text Configurations', 10, 1) WITH NOWAIT
  5365. DECLARE @FullTextDefaultPath NVARCHAR(512), @fterr tinyint
  5366. DECLARE @fttbl TABLE ([KeyExist] int)
  5367. DECLARE @FullTextDetails TABLE (FullText_ResourceUsage tinyint,
  5368. [DefaultPath] NVARCHAR(512),
  5369. [ConnectTimeout] int,
  5370. [DataTimeout] int,
  5371. [AllowUnsignedBinaries] bit,
  5372. [LoadOSResourcesEnabled] bit,
  5373. [CatalogUpgradeOption] tinyint)
  5374. SET @fterr = 0
  5375. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  5376. BEGIN
  5377. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 1)
  5378. BEGIN
  5379. BEGIN TRY
  5380. INSERT INTO @fttbl
  5381. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup' -- check if Full-Text path exists
  5382. IF (SELECT [KeyExist] FROM @fttbl) = 1
  5383. BEGIN
  5384. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup', N'FullTextDefaultPath', @FullTextDefaultPath OUTPUT, NO_OUTPUT;
  5385. END
  5386. END TRY
  5387. BEGIN CATCH
  5388. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  5389. SELECT @ErrorMessage = 'Full Text Configurations subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  5390. RAISERROR (@ErrorMessage, 16, 1);
  5391. END CATCH
  5392. END
  5393. ELSE
  5394. BEGIN
  5395. RAISERROR('[WARNING: Missing permissions for full "Full Text Configurations" checks. Bypassing Full Text path check]', 16, 1, N'sysadmin')
  5396. --RETURN
  5397. END
  5398. INSERT INTO @FullTextDetails
  5399. SELECT FULLTEXTSERVICEPROPERTY('ResourceUsage'), ISNULL(@FullTextDefaultPath, N'') AS [Default Path],
  5400. ISNULL(FULLTEXTSERVICEPROPERTY('ConnectTimeout'),0), ISNULL(FULLTEXTSERVICEPROPERTY('DataTimeout'),0),
  5401. CASE WHEN @sqlmajorver >= 9 THEN
  5402. FULLTEXTSERVICEPROPERTY('VerifySignature') ELSE NULL
  5403. END AS [AllowUnsignedBinaries],
  5404. CASE WHEN @sqlmajorver >= 9 THEN
  5405. FULLTEXTSERVICEPROPERTY('LoadOSResources') ELSE NULL
  5406. END AS [LoadOSResourcesEnabled],
  5407. CASE WHEN @sqlmajorver >= 10 THEN
  5408. FULLTEXTSERVICEPROPERTY('UpgradeOption') ELSE NULL
  5409. END AS [CatalogUpgradeOption];
  5410. IF @sqlmajorver <= 9 AND (SELECT FullText_ResourceUsage FROM @FullTextDetails) <> 3
  5411. BEGIN
  5412. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[INFORMATION: FullText Resource usage setting is not default]' AS [Deviation],
  5413. CASE WHEN FullText_ResourceUsage < 3 THEN '[Least Aggressive Usage Level]'
  5414. WHEN FullText_ResourceUsage = 4 THEN '[More Aggressive Usage Level]'
  5415. WHEN FullText_ResourceUsage = 5 THEN '[Most Aggressive Usage Level]'
  5416. END AS [Comment]
  5417. FROM @FullTextDetails;
  5418. SET @fterr = @fterr + 1
  5419. END
  5420. IF @sqlmajorver >= 9 AND (SELECT [AllowUnsignedBinaries] FROM @FullTextDetails) = 0
  5421. BEGIN
  5422. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[WARNING: FullText Binaries verification setting is not default]' AS [Deviation],
  5423. '[Do not verify whether or not binaries are signed]' AS [Comment];
  5424. SET @fterr = @fterr + 1
  5425. END
  5426. IF @sqlmajorver >= 9 AND (SELECT [LoadOSResourcesEnabled] FROM @FullTextDetails) = 1
  5427. BEGIN
  5428. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[WARNING: FullText OS Resource utilization setting is not default]' AS [Deviation],
  5429. '[Load OS filters and word breakers]' AS [Comment];
  5430. SET @fterr = @fterr + 1
  5431. END
  5432. IF @fterr = 0
  5433. BEGIN
  5434. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[OK]' AS [Deviation],
  5435. '[All FullText settings are aligned with defaults]' AS [Comment];
  5436. END
  5437. END;
  5438. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 0
  5439. BEGIN
  5440. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], NULL AS [Deviation], '[FullText search is not installed]' AS [Comment];
  5441. END;
  5442. --------------------------------------------------------------------------------------------------------------------------------
  5443. -- Deprecated features subsection
  5444. --------------------------------------------------------------------------------------------------------------------------------
  5445. IF @ptochecks = 1
  5446. BEGIN
  5447. RAISERROR (N' |-Starting Deprecated features', 10, 1) WITH NOWAIT
  5448. IF (SELECT COUNT(instance_name) FROM sys.dm_os_performance_counters WHERE [object_name] = 'SQLServer:Deprecated Features' AND cntr_value > 0) > 0
  5449. BEGIN
  5450. 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]
  5451. SELECT 'Instance_checks' AS [Category], 'Deprecated_features' AS [Information], instance_name, cntr_value AS [Times_used_since_startup]
  5452. FROM sys.dm_os_performance_counters (NOLOCK)
  5453. WHERE [object_name] LIKE '%Deprecated Features%' AND cntr_value > 0
  5454. ORDER BY instance_name;
  5455. END
  5456. ELSE
  5457. BEGIN
  5458. SELECT 'Instance_checks' AS [Category], 'Deprecated_features' AS [Check], '[OK]' AS [Deviation]
  5459. END;
  5460. END;
  5461. --------------------------------------------------------------------------------------------------------------------------------
  5462. -- Default data collections subsection
  5463. --------------------------------------------------------------------------------------------------------------------------------
  5464. RAISERROR (N' |-Starting default data collections', 10, 1) WITH NOWAIT
  5465. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE is_default = 1 AND status = 1)
  5466. BEGIN
  5467. SELECT 'Instance_checks' AS [Category], 'Default_Trace' AS [Check], '[OK]' AS [Deviation]
  5468. END
  5469. ELSE
  5470. BEGIN
  5471. 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]
  5472. END;
  5473. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE [path] LIKE '%blackbox%.trc' AND status = 1)
  5474. BEGIN
  5475. 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]
  5476. END
  5477. ELSE
  5478. BEGIN
  5479. SELECT 'Instance_checks' AS [Category], 'Blackbox_Trace' AS [Information], '[OK]' AS [Deviation]
  5480. END;
  5481. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE (is_default = 1 OR [path] LIKE '%blackbox%.trc') AND status = 1)
  5482. BEGIN
  5483. 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
  5484. FROM sys.traces
  5485. WHERE (is_default = 1 OR [path] LIKE '%blackbox%.trc') AND status = 1
  5486. END;
  5487. IF @sqlmajorver > 10
  5488. BEGIN
  5489. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] = 'system_health')
  5490. BEGIN
  5491. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_SystemHealth' AS [Check], '[OK]' AS [Deviation]
  5492. END
  5493. ELSE
  5494. BEGIN
  5495. 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]
  5496. END;
  5497. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] = 'sp_server_diagnostics session')
  5498. BEGIN
  5499. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_sp_server_diagnostics' AS [Check], '[OK]' AS [Deviation]
  5500. END
  5501. ELSE
  5502. BEGIN
  5503. 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]
  5504. END;
  5505. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] IN ('system_health', 'sp_server_diagnostics session'))
  5506. BEGIN
  5507. 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,
  5508. dropped_event_count, dropped_buffer_count, blocked_event_fire_time, create_time, largest_event_dropped_size
  5509. FROM sys.dm_xe_sessions
  5510. WHERE [name] IN ('system_health', 'sp_server_diagnostics session')
  5511. END;
  5512. END;
  5513. RAISERROR (N'|-Starting Database and tempDB Checks', 10, 1) WITH NOWAIT
  5514. --------------------------------------------------------------------------------------------------------------------------------
  5515. -- User objects in master DB
  5516. --------------------------------------------------------------------------------------------------------------------------------
  5517. RAISERROR (N' |-Starting User Objects in master DB', 10, 1) WITH NOWAIT
  5518. 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
  5519. BEGIN
  5520. SELECT 'Database_checks' AS [Category], 'User_Objects_in_master' AS [Check], '[WARNING: User objects are created in the master database]' AS [Deviation]
  5521. 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
  5522. FROM master.sys.all_objects sao
  5523. INNER JOIN master.sys.schemas ss ON sao.[schema_id] = ss.[schema_id]
  5524. WHERE sao.is_ms_shipped = 0
  5525. AND sao.[type] IN ('AF','FN','P','IF','PC','TF','TR','T','V')
  5526. ORDER BY sao.name, sao.type_desc;
  5527. END
  5528. ELSE
  5529. BEGIN
  5530. SELECT 'Database_checks' AS [Category], 'User_Objects_in_master' AS [Check], '[OK]' AS [Deviation]
  5531. END;
  5532. --------------------------------------------------------------------------------------------------------------------------------
  5533. -- DBs with collation <> master subsection
  5534. --------------------------------------------------------------------------------------------------------------------------------
  5535. RAISERROR (N' |-Starting DBs with collation <> master', 10, 1) WITH NOWAIT
  5536. DECLARE @master_collate NVARCHAR(128), @dif_collate int
  5537. SELECT @master_collate = collation_name FROM master.sys.databases (NOLOCK) WHERE database_id = 1;
  5538. SELECT @dif_collate = COUNT(collation_name) FROM master.sys.databases (NOLOCK) WHERE collation_name <> @master_collate;
  5539. IF @dif_collate >= 1
  5540. BEGIN
  5541. SELECT 'Database_checks' AS [Category], 'Collations' AS [Check], '[WARNING: Some user databases collation differ from the master Database_Collation]' AS [Deviation]
  5542. SELECT 'Database_checks' AS [Category], 'Collations' AS [Information], name AS [Database_Name], collation_name AS [Database_Collation], @master_collate AS [Master_Collation]
  5543. FROM master.sys.databases (NOLOCK)
  5544. WHERE collation_name <> @master_collate;
  5545. END
  5546. ELSE
  5547. BEGIN
  5548. SELECT 'Database_checks' AS [Category], 'Collations' AS [Check], '[OK]' AS [Deviation]
  5549. END;
  5550. --------------------------------------------------------------------------------------------------------------------------------
  5551. -- DBs with skewed compatibility level subsection
  5552. --------------------------------------------------------------------------------------------------------------------------------
  5553. RAISERROR (N' |-Starting DBs with skewed compatibility level', 10, 1) WITH NOWAIT
  5554. DECLARE @dif_compat int
  5555. SELECT @dif_compat = COUNT([compatibility_level]) FROM master.sys.databases (NOLOCK) WHERE [compatibility_level] <> @sqlmajorver * 10;
  5556. IF @dif_compat >= 1
  5557. BEGIN
  5558. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Check], '[WARNING: Some user databases have a non-optimal compatibility level]' AS [Deviation]
  5559. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Information], name AS [Database_Name], [compatibility_level] AS [Compatibility_Level]
  5560. FROM master.sys.databases (NOLOCK)
  5561. WHERE [compatibility_level] <> @sqlmajorver * 10;
  5562. END
  5563. ELSE
  5564. BEGIN
  5565. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Check], '[OK]' AS [Deviation]
  5566. END;
  5567. --------------------------------------------------------------------------------------------------------------------------------
  5568. -- User DBs with non-default options subsection
  5569. --------------------------------------------------------------------------------------------------------------------------------
  5570. RAISERROR (N' |-Starting User DBs with non-default options', 10, 1) WITH NOWAIT
  5571. DECLARE @cnt int, @cnt_i int
  5572. DECLARE @is_auto_close_on bit, @is_auto_shrink_on bit, @page_verify_option bit
  5573. DECLARE @is_auto_create_stats_on bit, @is_auto_update_stats_on bit
  5574. DECLARE @is_db_chaining_on bit, @is_auto_create_stats_incremental_on bit--, @is_indirect_checkpoint_on bit
  5575. DECLARE @is_trustworthy_on bit, @is_parameterization_forced bit
  5576. DECLARE @dbopterrtb TABLE (id int,
  5577. name sysname,
  5578. is_auto_close_on bit,
  5579. is_auto_shrink_on bit,
  5580. page_verify_option tinyint,
  5581. page_verify_option_desc NVARCHAR(60),
  5582. is_auto_create_stats_on bit,
  5583. is_auto_update_stats_on bit,
  5584. is_db_chaining_on bit,
  5585. --is_indirect_checkpoint_on bit,
  5586. is_auto_create_stats_incremental_on bit NULL,
  5587. is_trustworthy_on bit,
  5588. is_parameterization_forced bit)
  5589. IF @sqlmajorver < 12
  5590. BEGIN
  5591. SET @sqlcmd = 'SELECT ROW_NUMBER() OVER(ORDER BY name), name, is_auto_close_on,
  5592. is_auto_shrink_on, page_verify_option, page_verify_option_desc,
  5593. is_auto_create_stats_on, is_auto_update_stats_on, is_db_chaining_on,
  5594. --0 AS is_indirect_checkpoint_on,
  5595. NULL AS is_auto_create_stats_incremental_on,
  5596. is_trustworthy_on, is_parameterization_forced
  5597. FROM master.sys.databases (NOLOCK)
  5598. WHERE database_id > 4 OR name = ''model'''
  5599. END
  5600. ELSE
  5601. BEGIN
  5602. SET @sqlcmd = 'SELECT ROW_NUMBER() OVER(ORDER BY name), name, is_auto_close_on,
  5603. is_auto_shrink_on, page_verify_option, page_verify_option_desc,
  5604. is_auto_create_stats_on, is_auto_update_stats_on,
  5605. is_db_chaining_on,
  5606. --CASE WHEN target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  5607. is_auto_create_stats_incremental_on,
  5608. is_trustworthy_on, is_parameterization_forced
  5609. FROM master.sys.databases (NOLOCK)
  5610. WHERE database_id > 4 OR name = ''model'''
  5611. END;
  5612. INSERT INTO @dbopterrtb
  5613. EXECUTE sp_executesql @sqlcmd;
  5614. SET @cnt = (SELECT COUNT(id) FROM @dbopterrtb)
  5615. SET @cnt_i = 1
  5616. 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 = 0--, @is_indirect_checkpoint_on = 0
  5617. WHILE @cnt_i <> @cnt
  5618. BEGIN
  5619. 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,
  5620. @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,
  5621. @page_verify_option = CASE WHEN page_verify_option <> 2 AND @page_verify_option = 0 THEN 1 ELSE @page_verify_option END,
  5622. @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,
  5623. @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,
  5624. @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,
  5625. --@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,
  5626. @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,
  5627. @is_trustworthy_on = CASE WHEN is_trustworthy_on = 1 AND @is_trustworthy_on = 0 THEN 1 ELSE @is_trustworthy_on END,
  5628. @is_parameterization_forced = CASE WHEN is_parameterization_forced = 1 AND @is_parameterization_forced = 0 THEN 1 ELSE @is_parameterization_forced END
  5629. FROM @dbopterrtb
  5630. WHERE id = @cnt_i;
  5631. SET @cnt_i = @cnt_i + 1
  5632. END
  5633. 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
  5634. BEGIN
  5635. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Check], '[WARNING: Some user databases may have Non-optimal_Settings]' AS [Deviation]
  5636. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Information],
  5637. name AS [Database_Name],
  5638. RTRIM(
  5639. CASE WHEN is_auto_close_on = 1 THEN 'Auto_Close;' ELSE '' END +
  5640. CASE WHEN is_auto_shrink_on = 1 THEN 'Auto_Shrink;' ELSE '' END +
  5641. CASE WHEN page_verify_option <> 2 THEN 'Page_Verify;' ELSE '' END +
  5642. CASE WHEN is_auto_create_stats_on = 0 THEN 'Auto_Create_Stats;' ELSE '' END +
  5643. CASE WHEN is_auto_update_stats_on = 0 THEN 'Auto_Update_Stats;' ELSE '' END +
  5644. CASE WHEN is_db_chaining_on = 1 THEN 'DB_Chaining;' ELSE '' END +
  5645. --CASE WHEN is_indirect_checkpoint_on = 1 THEN 'Indirect_Checkpoint;' ELSE '' END +
  5646. CASE WHEN is_auto_create_stats_incremental_on = 0 THEN 'Incremental_Stats;' ELSE '' END +
  5647. CASE WHEN is_trustworthy_on = 1 THEN 'Trustworthy_bit;' ELSE '' END +
  5648. CASE WHEN is_parameterization_forced = 1 THEN 'Forced_Parameterization;' ELSE '' END
  5649. ) AS [Non-optimal_Settings],
  5650. CASE WHEN is_auto_close_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Close],
  5651. CASE WHEN is_auto_shrink_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Shrink],
  5652. page_verify_option_desc AS [Page_Verify],
  5653. CASE WHEN is_auto_create_stats_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Create_Stats],
  5654. CASE WHEN is_auto_update_stats_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Update_Stats],
  5655. CASE WHEN is_db_chaining_on = 1 THEN 'ON' ELSE 'OFF' END AS [DB_Chaining],
  5656. --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.
  5657. 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],
  5658. CASE WHEN is_trustworthy_on = 1 THEN 'ON' ELSE 'OFF' END AS [Trustworthy_bit],
  5659. CASE WHEN is_parameterization_forced = 1 THEN 'ON' ELSE 'OFF' END AS [Forced_Parameterization]
  5660. FROM @dbopterrtb
  5661. 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)
  5662. 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;
  5663. END
  5664. ELSE
  5665. BEGIN
  5666. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Check], '[OK]' AS [Deviation]
  5667. END;
  5668. IF (SELECT COUNT(*) FROM master.sys.databases (NOLOCK) WHERE is_auto_update_stats_on = 0 AND is_auto_update_stats_async_on = 1) > 0
  5669. BEGIN
  5670. 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]
  5671. 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
  5672. END
  5673. ELSE
  5674. BEGIN
  5675. SELECT 'Database_checks' AS [Category], 'Database_Options_Disabled_Async_AutoUpdate' AS [Check], '[OK]' AS [Deviation]
  5676. END;
  5677. --------------------------------------------------------------------------------------------------------------------------------
  5678. -- DBs with Sparse files subsection
  5679. --------------------------------------------------------------------------------------------------------------------------------
  5680. RAISERROR (N' |-Starting DBs with Sparse files', 10, 1) WITH NOWAIT
  5681. -- 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
  5682. -- http://blogs.msdn.com/b/jorgepc/archive/2010/11/25/what-are-sparse-files-and-why-should-i-care-as-sql-server-dba.aspx
  5683. 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
  5684. BEGIN
  5685. 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]
  5686. SELECT 'Database_checks' AS [Category], 'DB_nonSnap_Sparse' AS [Information], DB_NAME(sd.database_id) AS database_name, smf.name, smf.physical_name
  5687. FROM sys.databases sd
  5688. INNER JOIN sys.master_files smf ON sd.database_id = smf.database_id
  5689. WHERE sd.source_database_id IS NULL AND smf.is_sparse = 1
  5690. END
  5691. ELSE
  5692. BEGIN
  5693. SELECT 'Database_checks' AS [Category], 'DB_nonSnap_Sparse' AS [Check], '[OK]' AS [Deviation]
  5694. END;
  5695. --------------------------------------------------------------------------------------------------------------------------------
  5696. -- DBs Autogrow in percentage subsection
  5697. --------------------------------------------------------------------------------------------------------------------------------
  5698. RAISERROR (N' |-Starting DBs Autogrow in percentage', 10, 1) WITH NOWAIT
  5699. IF (SELECT COUNT(is_percent_growth) FROM sys.master_files WHERE is_percent_growth = 1) > 0
  5700. BEGIN
  5701. 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]
  5702. SELECT 'Database_checks' AS [Category], 'Percent_Autogrows' AS [Information], database_id,
  5703. DB_NAME(database_id) AS [Database_Name],
  5704. mf.name AS [Logical_Name],
  5705. mf.size*8 AS [Current_Size_KB],
  5706. mf.type_desc AS [File_Type],
  5707. mf.[state_desc] AS [File_State],
  5708. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  5709. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount_KB],
  5710. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((mf.size*8)*CONVERT(bigint, mf.growth))/100
  5711. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  5712. ELSE 0 END AS [Next_Growth_KB],
  5713. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  5714. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  5715. ELSE '' END AS [Comments],
  5716. mf.is_read_only
  5717. FROM sys.master_files mf (NOLOCK)
  5718. WHERE is_percent_growth = 1
  5719. 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
  5720. ORDER BY DB_NAME(mf.database_id), mf.name
  5721. END
  5722. ELSE
  5723. BEGIN
  5724. SELECT 'Database_checks' AS [Category], 'Percent_Autogrows' AS [Check], '[OK]' AS [Deviation]
  5725. END;
  5726. --------------------------------------------------------------------------------------------------------------------------------
  5727. -- DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled) subsection
  5728. --------------------------------------------------------------------------------------------------------------------------------
  5729. RAISERROR (N' |-Starting DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled)', 10, 1) WITH NOWAIT
  5730. IF (SELECT COUNT(growth) FROM sys.master_files (NOLOCK)
  5731. WHERE [type] >= CASE WHEN @ifi = 1 THEN 1 ELSE 0 END
  5732. AND [type] < 2
  5733. AND ((is_percent_growth = 1 AND ((CONVERT(bigint,size)*8)*growth)/100 > 1048576)
  5734. OR (is_percent_growth = 0 AND growth*8 > 1048576))) > 0
  5735. BEGIN
  5736. 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]
  5737. SELECT 'Database_checks' AS [Category], 'Large_Autogrows' AS [Information], database_id,
  5738. DB_NAME(database_id) AS [Database_Name],
  5739. mf.name AS [Logical_Name],
  5740. mf.size*8 AS [Current_Size_KB],
  5741. mf.[type_desc] AS [File_Type],
  5742. mf.[state_desc] AS [File_State],
  5743. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  5744. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount],
  5745. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((CONVERT(bigint,mf.size)*8)*mf.growth)/100
  5746. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  5747. ELSE 0 END AS [Next_Growth_KB],
  5748. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  5749. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  5750. ELSE '' END AS [Comments],
  5751. mf.is_read_only
  5752. FROM sys.master_files mf (NOLOCK)
  5753. WHERE mf.[type] >= CASE WHEN @ifi = 1 THEN 1 ELSE 0 END
  5754. AND mf.[type] < 2
  5755. AND ((is_percent_growth = 1 AND ((CONVERT(bigint,mf.size)*8)*mf.growth)/100 > 1048576)
  5756. OR (is_percent_growth = 0 AND mf.growth*8 > 1048576))
  5757. 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
  5758. ORDER BY DB_NAME(mf.database_id), mf.name
  5759. END
  5760. ELSE
  5761. BEGIN
  5762. SELECT 'Database_checks' AS [Category], 'Large_Autogrows' AS [Check], '[OK]' AS [Deviation]
  5763. END;
  5764. --------------------------------------------------------------------------------------------------------------------------------
  5765. -- VLF subsection
  5766. --------------------------------------------------------------------------------------------------------------------------------
  5767. RAISERROR (N' |-Starting VLF', 10, 1) WITH NOWAIT
  5768. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1
  5769. BEGIN
  5770. 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)
  5771. DECLARE @potsize DECIMAL(20,1), @n_iter int, @n_iter_final int, @initgrow DECIMAL(20,1), @n_init_iter int
  5772. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  5773. DROP TABLE #log_info1;
  5774. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  5775. CREATE TABLE #log_info1 (dbname VARCHAR(100),
  5776. Current_log_size_MB DECIMAL(20,1),
  5777. Used_Log_size_MB DECIMAL(20,1),
  5778. Potential_log_size_MB DECIMAL(20,1),
  5779. Current_VLFs int,
  5780. Used_VLFs int,
  5781. Avg_VLF_size_KB DECIMAL(20,1),
  5782. Potential_VLFs int,
  5783. Growth_iterations int,
  5784. Log_Initial_size_MB DECIMAL(20,1),
  5785. File_autogrow_MB DECIMAL(20,1))
  5786. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  5787. DROP TABLE #log_info2;
  5788. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  5789. CREATE TABLE #log_info2 (dbname VARCHAR(100),
  5790. Current_VLFs int,
  5791. VLF_size_KB DECIMAL(20,1),
  5792. growth_iteration int)
  5793. UPDATE #tmpdbs0
  5794. SET isdone = 0;
  5795. UPDATE #tmpdbs0
  5796. SET isdone = 1
  5797. WHERE [state] <> 0;
  5798. UPDATE #tmpdbs0
  5799. SET isdone = 1
  5800. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  5801. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  5802. BEGIN
  5803. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  5804. BEGIN
  5805. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  5806. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info3'))
  5807. DROP TABLE #log_info3;
  5808. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info3'))
  5809. CREATE TABLE #log_info3 (recoveryunitid int NULL,
  5810. fileid tinyint,
  5811. file_size bigint,
  5812. start_offset bigint,
  5813. FSeqNo int,
  5814. [status] tinyint,
  5815. parity tinyint,
  5816. create_lsn numeric(25,0))
  5817. SET @query = 'DBCC LOGINFO (' + '''' + @dbname + ''') WITH NO_INFOMSGS'
  5818. IF @sqlmajorver < 11
  5819. BEGIN
  5820. INSERT INTO #log_info3 (fileid, file_size, start_offset, FSeqNo, [status], parity, create_lsn)
  5821. EXEC (@query)
  5822. END
  5823. ELSE
  5824. BEGIN
  5825. INSERT INTO #log_info3 (recoveryunitid, fileid, file_size, start_offset, FSeqNo, [status], parity, create_lsn)
  5826. EXEC (@query)
  5827. END
  5828. SET @count = @@ROWCOUNT
  5829. SET @count_used = (SELECT COUNT(fileid) FROM #log_info3 l WHERE l.[status] = 2)
  5830. SET @logsize = (SELECT (MIN(l.start_offset) + SUM(l.file_size))/1048576.00 FROM #log_info3 l)
  5831. 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)
  5832. SET @avgvlfsize = (SELECT AVG(l.file_size)/1024.00 FROM #log_info3 l)
  5833. INSERT INTO #log_info2
  5834. SELECT @dbname, COUNT(create_lsn), MIN(l.file_size)/1024.00,
  5835. ROW_NUMBER() OVER(ORDER BY l.create_lsn) FROM #log_info3 l
  5836. GROUP BY l.create_lsn
  5837. ORDER BY l.create_lsn
  5838. DROP TABLE #log_info3;
  5839. -- Grow logs in MB instead of GB because of known issue prior to SQL 2012.
  5840. -- More detail here: http://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx
  5841. -- and http://connect.microsoft.com/SQLServer/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately
  5842. -- or https://connect.microsoft.com/SQLServer/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb
  5843. IF @sqlmajorver >= 11
  5844. BEGIN
  5845. SET @n_iter = (SELECT CASE WHEN @logsize <= 64 THEN 1
  5846. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)
  5847. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)
  5848. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)
  5849. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)
  5850. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4096, 0)
  5851. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8192, 0)
  5852. END)
  5853. SET @potsize = (SELECT CASE WHEN @logsize <= 64 THEN 1*64
  5854. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)*256
  5855. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)*512
  5856. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)*1024
  5857. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)*2048
  5858. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4096, 0)*4096
  5859. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8192, 0)*8192
  5860. END)
  5861. END
  5862. ELSE
  5863. BEGIN
  5864. SET @n_iter = (SELECT CASE WHEN @logsize <= 64 THEN 1
  5865. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)
  5866. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)
  5867. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)
  5868. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)
  5869. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4000, 0)
  5870. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8000, 0)
  5871. END)
  5872. SET @potsize = (SELECT CASE WHEN @logsize <= 64 THEN 1*64
  5873. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)*256
  5874. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)*512
  5875. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)*1024
  5876. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)*2048
  5877. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4000, 0)*4000
  5878. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8000, 0)*8000
  5879. END)
  5880. END
  5881. -- If the proposed log size is smaller than current log, and also smaller than 4GB,
  5882. -- and there is less than 512MB of diff between the current size and proposed size, add 1 grow.
  5883. SET @n_iter_final = @n_iter
  5884. IF @logsize > @potsize AND @potsize <= 4096 AND ABS(@logsize - @potsize) < 512
  5885. BEGIN
  5886. SET @n_iter_final = @n_iter + 1
  5887. END
  5888. -- If the proposed log size is larger than current log, and also larger than 50GB,
  5889. -- and there is less than 1GB of diff between the current size and proposed size, take 1 grow.
  5890. ELSE IF @logsize < @potsize AND @potsize <= 51200 AND ABS(@logsize - @potsize) > 1024
  5891. BEGIN
  5892. SET @n_iter_final = @n_iter - 1
  5893. END
  5894. IF @potsize = 0
  5895. BEGIN
  5896. SET @potsize = 64
  5897. END
  5898. IF @n_iter = 0
  5899. BEGIN
  5900. SET @n_iter = 1
  5901. END
  5902. SET @potsize = (SELECT CASE WHEN @n_iter < @n_iter_final THEN @potsize + (@potsize/@n_iter)
  5903. WHEN @n_iter > @n_iter_final THEN @potsize - (@potsize/@n_iter)
  5904. ELSE @potsize END)
  5905. SET @n_init_iter = @n_iter_final
  5906. IF @potsize >= 8192
  5907. BEGIN
  5908. SET @initgrow = @potsize/@n_iter_final
  5909. END
  5910. IF @potsize >= 64 AND @potsize <= 512
  5911. BEGIN
  5912. SET @n_init_iter = 1
  5913. SET @initgrow = 512
  5914. END
  5915. IF @potsize > 512 AND @potsize <= 1024
  5916. BEGIN
  5917. SET @n_init_iter = 1
  5918. SET @initgrow = 1023
  5919. END
  5920. IF @potsize > 1024 AND @potsize < 8192
  5921. BEGIN
  5922. SET @n_init_iter = 1
  5923. SET @initgrow = @potsize
  5924. END
  5925. INSERT INTO #log_info1
  5926. VALUES(@dbname, @logsize, @usedlogsize, @potsize, @count, @count_used, @avgvlfsize,
  5927. CASE WHEN @potsize <= 64 THEN (@potsize/(@potsize/@n_init_iter))*4
  5928. WHEN @potsize > 64 AND @potsize < 1024 THEN (@potsize/(@potsize/@n_init_iter))*8
  5929. WHEN @potsize >= 1024 THEN (@potsize/(@potsize/@n_init_iter))*16
  5930. END,
  5931. @n_init_iter, @initgrow,
  5932. CASE WHEN (@potsize/@n_iter_final) <= 1024 THEN (@potsize/@n_iter_final) ELSE 1024 END
  5933. );
  5934. UPDATE #tmpdbs0
  5935. SET isdone = 1
  5936. WHERE [dbid] = @dbid
  5937. END
  5938. END;
  5939. IF (SELECT COUNT(dbname) FROM #log_info1 WHERE Current_VLFs >= 50) > 0
  5940. BEGIN
  5941. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Check], '[WARNING: Some user databases have many VLFs. Please review these]' AS [Deviation]
  5942. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Information], dbname AS [Database_Name], Current_log_size_MB, Used_Log_size_MB,
  5943. Potential_log_size_MB, Current_VLFs, Used_VLFs, Potential_VLFs, Growth_iterations, Log_Initial_size_MB, File_autogrow_MB
  5944. FROM #log_info1
  5945. WHERE Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5946. ORDER BY dbname;
  5947. 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
  5948. FROM #log_info2
  5949. INNER JOIN #log_info1 ON #log_info2.dbname = #log_info1.dbname
  5950. WHERE #log_info1.Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5951. ORDER BY #log_info2.dbname, growth_iteration
  5952. 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
  5953. FROM #log_info2
  5954. INNER JOIN #log_info1 ON #log_info2.dbname = #log_info1.dbname
  5955. WHERE #log_info1.Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5956. GROUP BY #log_info2.dbname, VLF_size_KB
  5957. ORDER BY #log_info2.dbname, VLF_size_KB DESC
  5958. END
  5959. ELSE
  5960. BEGIN
  5961. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Check], '[OK]' AS [Deviation]
  5962. /*
  5963. 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
  5964. FROM #log_info1
  5965. ORDER BY dbname;
  5966. 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
  5967. FROM #log_info2
  5968. ORDER BY dbname, growth_iteration
  5969. 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
  5970. FROM #log_info2
  5971. GROUP BY dbname, VLF_size_KB
  5972. ORDER BY dbname, VLF_size_KB DESC
  5973. */
  5974. END
  5975. END
  5976. ELSE
  5977. BEGIN
  5978. RAISERROR('[WARNING: Only a sysadmin can run the "VLF" check. Bypassing check]', 16, 1, N'sysadmin')
  5979. --RETURN
  5980. END;
  5981. --------------------------------------------------------------------------------------------------------------------------------
  5982. -- Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware) subsection
  5983. --------------------------------------------------------------------------------------------------------------------------------
  5984. RAISERROR (N' |-Starting Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware)', 10, 1) WITH NOWAIT
  5985. IF @allow_xpcmdshell = 1
  5986. BEGIN
  5987. DECLARE /*@dbid int,*/ @ctr2 int, @ctr3 int, @ctr4 int, @pserr bit
  5988. SET @pserr = 0
  5989. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  5990. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5991. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  5992. AND (SELECT COUNT(l.name)
  5993. FROM sys.server_permissions p (NOLOCK) INNER JOIN sys.server_principals l (NOLOCK)
  5994. ON p.grantee_principal_id = l.principal_id
  5995. AND p.class = 100 -- Server
  5996. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  5997. AND l.is_disabled = 0
  5998. AND p.permission_name = 'ALTER SETTINGS'
  5999. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  6000. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  6001. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  6002. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  6003. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  6004. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  6005. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  6006. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  6007. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  6008. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  6009. BEGIN
  6010. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild <= 2500)
  6011. BEGIN
  6012. DECLARE @pstbl TABLE ([KeyExist] int)
  6013. BEGIN TRY
  6014. INSERT INTO @pstbl
  6015. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\PowerShell\1' -- check if Powershell is installed
  6016. END TRY
  6017. BEGIN CATCH
  6018. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  6019. SELECT @ErrorMessage = 'Data files and Logs in same volume (Mountpoint aware) subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  6020. RAISERROR (@ErrorMessage, 16, 1);
  6021. END CATCH
  6022. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  6023. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  6024. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  6025. RAISERROR (' |-Configuration options set for Data and Log location check', 10, 1) WITH NOWAIT
  6026. IF @sao = 0
  6027. BEGIN
  6028. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  6029. END
  6030. IF @xcmd = 0
  6031. BEGIN
  6032. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  6033. END
  6034. IF @ole = 0
  6035. BEGIN
  6036. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  6037. END
  6038. IF (SELECT [KeyExist] FROM @pstbl) = 1
  6039. BEGIN
  6040. DECLARE @ctr int
  6041. DECLARE @output_hw_tot TABLE ([PS_OUTPUT] NVARCHAR(2048));
  6042. DECLARE @output_hw_format TABLE ([volid] smallint IDENTITY(1,1), [HD_Volume] NVARCHAR(2048) NULL)
  6043. IF @custompath IS NULL
  6044. BEGIN
  6045. IF @sqlmajorver < 11
  6046. BEGIN
  6047. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  6048. SET @path = @path + '\LOG'
  6049. END
  6050. ELSE
  6051. BEGIN
  6052. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  6053. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  6054. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  6055. END
  6056. -- Create COM object with FSO
  6057. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  6058. IF @OLEResult <> 0
  6059. BEGIN
  6060. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  6061. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  6062. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6063. END
  6064. ELSE
  6065. BEGIN
  6066. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  6067. IF @OLEResult <> 0
  6068. BEGIN
  6069. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  6070. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  6071. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6072. END
  6073. ELSE
  6074. BEGIN
  6075. IF @existout <> 1
  6076. BEGIN
  6077. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  6078. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  6079. END
  6080. END
  6081. EXEC @OLEResult = sp_OADestroy @FSO
  6082. END
  6083. END
  6084. ELSE
  6085. BEGIN
  6086. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  6087. END
  6088. SET @FileName = @path + '\checkbp_' + RTRIM(@server) + '.ps1'
  6089. EXEC master.dbo.xp_fileexist @FileName, @existout out
  6090. IF @existout = 0
  6091. BEGIN
  6092. -- Scan for local disks
  6093. SET @Text1 = '[string] $serverName = ''localhost''
  6094. $vols = Get-WmiObject -computername $serverName -query "select Name from Win32_Volume where Capacity <> NULL and DriveType = 3"
  6095. foreach($vol in $vols)
  6096. {
  6097. [string] $drive = "{0}" -f $vol.name
  6098. Write-Output $drive
  6099. }'
  6100. -- Create COM object with FSO
  6101. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  6102. IF @OLEResult <> 0
  6103. BEGIN
  6104. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6105. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  6106. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6107. END
  6108. --Open file
  6109. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  6110. IF @OLEResult <> 0
  6111. BEGIN
  6112. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6113. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  6114. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6115. END
  6116. ELSE
  6117. BEGIN
  6118. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  6119. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6120. END
  6121. --Write Text1
  6122. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  6123. IF @OLEResult <> 0
  6124. BEGIN
  6125. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6126. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  6127. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6128. END
  6129. EXEC @OLEResult = sp_OADestroy @FileID
  6130. EXEC @OLEResult = sp_OADestroy @FS
  6131. END;
  6132. ELSE
  6133. BEGIN
  6134. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  6135. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6136. END
  6137. IF @psver = 1
  6138. BEGIN
  6139. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  6140. END
  6141. ELSE
  6142. BEGIN
  6143. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  6144. END;
  6145. INSERT INTO @output_hw_tot
  6146. EXEC master.dbo.xp_cmdshell @CMD
  6147. SET @CMD = 'del /Q "' + @FileName + '"'
  6148. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  6149. IF (SELECT COUNT([PS_OUTPUT])
  6150. FROM @output_hw_tot WHERE [PS_OUTPUT] LIKE '%cannot be loaded because%'
  6151. OR [PS_OUTPUT] LIKE '%scripts is disabled%'
  6152. OR [PS_OUTPUT] LIKE '%scripts est désactivée%') = 0
  6153. BEGIN
  6154. INSERT INTO @output_hw_format ([HD_Volume])
  6155. SELECT RTRIM([PS_OUTPUT])
  6156. FROM @output_hw_tot
  6157. WHERE [PS_OUTPUT] IS NOT NULL
  6158. END
  6159. ELSE
  6160. BEGIN
  6161. SET @pserr = 1
  6162. RAISERROR ('[WARNING: Powershell script cannot be loaded because the execution of scripts is disabled on this system.
  6163. To change the execution policy, type the following command in Powershell console: Set-ExecutionPolicy RemoteSigned
  6164. The Set-ExecutionPolicy cmdlet enables you to determine which Windows PowerShell scripts (if any) will be allowed to run on your computer.
  6165. Windows PowerShell has four different execution policies:
  6166. Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  6167. AllSigned - Only scripts signed by a trusted publisher can be run.
  6168. RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  6169. |- REQUIRED by BP Check
  6170. Unrestricted - No restrictions; all Windows PowerShell scripts can be run.]
  6171. ',16,1);
  6172. END
  6173. SET @CMD2 = 'del ' + @FileName
  6174. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  6175. END
  6176. ELSE
  6177. BEGIN
  6178. SET @pserr = 1
  6179. RAISERROR ('[WARNING: Powershell is not present. Bypassing Data files and Logs in same volume check]',16,1);
  6180. END
  6181. IF @xcmd = 0
  6182. BEGIN
  6183. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  6184. END
  6185. IF @ole = 0
  6186. BEGIN
  6187. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  6188. END
  6189. IF @sao = 0
  6190. BEGIN
  6191. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  6192. END
  6193. END
  6194. ELSE
  6195. BEGIN
  6196. INSERT INTO @output_hw_format ([HD_Volume])
  6197. 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')
  6198. END;
  6199. IF @pserr = 0
  6200. BEGIN
  6201. -- select mountpoints only
  6202. DECLARE @intertbl TABLE (physical_name nvarchar(260))
  6203. INSERT INTO @intertbl
  6204. SELECT physical_name
  6205. FROM sys.master_files t1 (NOLOCK)
  6206. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6207. WHERE ([database_id] > 4 OR [database_id] = 2)
  6208. AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3
  6209. -- select database files in mountpoints
  6210. DECLARE @filetbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6211. INSERT INTO @filetbl
  6212. SELECT database_id, type, file_id, physical_name, volid
  6213. FROM sys.master_files t1 (NOLOCK)
  6214. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6215. WHERE ([database_id] > 4 OR [database_id] = 2) AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3
  6216. UNION ALL
  6217. -- select database files not in mountpoints
  6218. SELECT database_id, type, file_id, physical_name, volid
  6219. FROM sys.master_files t1 (NOLOCK)
  6220. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6221. WHERE ([database_id] > 4 OR [database_id] = 2) AND [database_id] <> 32767 AND physical_name NOT IN (SELECT physical_name FROM @intertbl)
  6222. SELECT @ctr = COUNT(DISTINCT(t1.[database_id])) FROM @filetbl t1
  6223. INNER JOIN @filetbl t2 ON t1.database_id = t2.database_id
  6224. AND t1.[type] <> t2.[type]
  6225. AND ((t1.[type] = 1 AND t2.[type] <> 1) OR (t2.[type] = 1 AND t1.[type] <> 1))
  6226. AND t1.volid = t2.volid;
  6227. IF @ctr > 0
  6228. BEGIN
  6229. 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]
  6230. 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
  6231. FROM sys.master_files mf (NOLOCK) INNER JOIN @filetbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6232. INNER JOIN @filetbl t2 ON t1.database_id = t2.database_id
  6233. AND t1.[type] <> t2.[type]
  6234. AND ((t1.[type] = 1 AND t2.[type] <> 1) OR (t2.[type] = 1 AND t1.[type] <> 1))
  6235. AND t1.volid = t2.volid
  6236. ORDER BY mf.physical_name OPTION (RECOMPILE);
  6237. END
  6238. ELSE
  6239. BEGIN
  6240. SELECT 'Database_checks' AS [Category], 'Data_and_Log_locations' AS [Check], '[OK]' AS [Deviation]
  6241. END;
  6242. -- select backup mountpoints only
  6243. DECLARE @interbcktbl TABLE (physical_device_name nvarchar(260))
  6244. INSERT INTO @interbcktbl
  6245. SELECT physical_device_name
  6246. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6247. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6248. WHERE LEN(t2.HD_Volume) > 3
  6249. -- select backups in mountpoints only
  6250. DECLARE @bcktbl TABLE (physical_device_name nvarchar(260), HD_Volume nvarchar(260))
  6251. INSERT INTO @bcktbl
  6252. SELECT physical_device_name, RTRIM(t2.HD_Volume)
  6253. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6254. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6255. WHERE LEN(t2.HD_Volume) > 3
  6256. -- select backups not in mountpoints
  6257. UNION ALL
  6258. SELECT physical_device_name, RTRIM(t2.HD_Volume)
  6259. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6260. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6261. WHERE physical_device_name NOT IN (SELECT physical_device_name FROM @interbcktbl);
  6262. SELECT @ctr4 = COUNT(DISTINCT(physical_device_name)) FROM @bcktbl;
  6263. IF @ctr4 > 0
  6264. BEGIN
  6265. 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]
  6266. 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]
  6267. FROM @bcktbl
  6268. OPTION (RECOMPILE);
  6269. END
  6270. ELSE
  6271. BEGIN
  6272. SELECT 'Database_checks' AS [Category], 'Backup_and_Database_locations' AS [Check], '[OK]' AS [Deviation]
  6273. END;
  6274. -- select tempDB mountpoints only
  6275. DECLARE @intertbl2 TABLE (physical_name nvarchar(260))
  6276. INSERT INTO @intertbl2
  6277. SELECT physical_name
  6278. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2
  6279. ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6280. WHERE [database_id] = 2 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6281. -- select user DBs mountpoints only
  6282. DECLARE @intertbl3 TABLE (physical_name nvarchar(260))
  6283. INSERT INTO @intertbl3
  6284. SELECT physical_name
  6285. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2
  6286. ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6287. WHERE [database_id] > 4 AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6288. -- select tempDB files in mountpoints
  6289. DECLARE @tempDBtbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6290. INSERT INTO @tempDBtbl
  6291. SELECT database_id, type, file_id, physical_name, volid
  6292. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6293. WHERE [database_id] = 2 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6294. UNION ALL
  6295. SELECT database_id, type, file_id, physical_name, volid
  6296. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6297. WHERE [database_id] = 2 AND [type] = 0 AND physical_name NOT IN (SELECT physical_name FROM @intertbl2)
  6298. -- select user DBs files in mountpoints
  6299. DECLARE @otherstbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6300. INSERT INTO @otherstbl
  6301. SELECT database_id, type, file_id, physical_name, volid
  6302. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6303. WHERE [database_id] > 4 AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6304. UNION ALL
  6305. SELECT database_id, type, file_id, physical_name, volid
  6306. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6307. WHERE [database_id] > 4 AND [database_id] <> 32767 AND [type] = 0 AND physical_name NOT IN (SELECT physical_name FROM @intertbl3)
  6308. SELECT @ctr2 = COUNT(*) FROM @tempDBtbl WHERE LEFT(physical_name, 1) = 'C'
  6309. SELECT @ctr3 = COUNT(DISTINCT(t1.[database_id])) FROM @otherstbl t1 INNER JOIN @tempDBtbl t2 ON t1.volid = t2.volid;
  6310. IF @ctr3 > 0
  6311. BEGIN
  6312. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: tempDB is on the same physical volume as user databases]' AS [Deviation];
  6313. END
  6314. ELSE IF @ctr2 > 0
  6315. BEGIN
  6316. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: tempDB is on C: drive]' AS [Deviation]
  6317. END
  6318. ELSE
  6319. BEGIN
  6320. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[OK]' AS [Deviation]
  6321. END;
  6322. IF @ctr2 > 0 OR @ctr3 > 0
  6323. BEGIN
  6324. 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
  6325. FROM sys.master_files mf (NOLOCK) INNER JOIN @otherstbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6326. INNER JOIN @tempDBtbl t2 ON t1.volid = t2.volid
  6327. UNION ALL
  6328. 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
  6329. FROM sys.master_files mf (NOLOCK) INNER JOIN @tempDBtbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6330. ORDER BY DB_NAME(mf.[database_id]) OPTION (RECOMPILE);
  6331. END
  6332. END
  6333. ELSE
  6334. BEGIN
  6335. SELECT 'Database_checks' AS [Category], 'Data_and_Log_locations' AS [Check], '[WARNING: Could not gather information on file locations]' AS [Deviation]
  6336. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: Could not gather information on file locations]' AS [Deviation]
  6337. END
  6338. END
  6339. ELSE
  6340. BEGIN
  6341. 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')
  6342. 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')
  6343. --RETURN
  6344. END
  6345. END
  6346. ELSE
  6347. BEGIN
  6348. 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')
  6349. --RETURN
  6350. END;
  6351. --------------------------------------------------------------------------------------------------------------------------------
  6352. -- tempDB data file configurations subsection
  6353. --------------------------------------------------------------------------------------------------------------------------------
  6354. RAISERROR (N' |-Starting tempDB data file configurations', 10, 1) WITH NOWAIT
  6355. DECLARE @tdb_files int, @online_count int, @filesizes smallint
  6356. SELECT @tdb_files = COUNT(physical_name) FROM sys.master_files (NOLOCK) WHERE database_id = 2 AND [type] = 0;
  6357. SELECT @online_count = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE is_online = 1 AND scheduler_id < 255 AND parent_node_id < 64;
  6358. SELECT @filesizes = COUNT(DISTINCT size) FROM tempdb.sys.database_files WHERE [type] = 0;
  6359. 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)*/
  6360. OR (@tdb_files >= (@online_count / 2) AND @tdb_files >= 8 AND @tdb_files % 4 = 0)) THEN 0 ELSE 1 END) = 0
  6361. BEGIN
  6362. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Check], '[OK]' AS [Deviation]
  6363. 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]
  6364. FROM tempdb.sys.database_files (NOLOCK)
  6365. WHERE type = 0;
  6366. END
  6367. ELSE
  6368. BEGIN
  6369. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Check],
  6370. 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]'
  6371. 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]'
  6372. 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]'
  6373. WHEN @filesizes = 1 AND @tdb_files >= 4 AND @tdb_files % 4 > 0 THEN '[WARNING: Number of data files is not multiple of 4]'
  6374. WHEN @filesizes > 1 AND @tdb_files >= 4 AND @tdb_files % 4 = 0 THEN '[WARNING: Data file sizes do not match]'
  6375. ELSE '[OK]' END AS [Deviation];
  6376. 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]
  6377. FROM tempdb.sys.database_files (NOLOCK)
  6378. WHERE type = 0;
  6379. END;
  6380. --------------------------------------------------------------------------------------------------------------------------------
  6381. -- tempDB data files autogrow of equal size subsection
  6382. --------------------------------------------------------------------------------------------------------------------------------
  6383. RAISERROR (N' |-Starting tempDB Files autogrow of equal size', 10, 1) WITH NOWAIT
  6384. IF (SELECT COUNT(DISTINCT growth) FROM sys.master_files WHERE [database_id] = 2 AND [type] = 0) > 1
  6385. OR (SELECT COUNT(DISTINCT is_percent_growth) FROM sys.master_files WHERE [database_id] = 2 AND [type] = 0) > 1
  6386. BEGIN
  6387. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Check], '[WARNING: Some tempDB data files have different growth settings]' AS [Deviation]
  6388. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Information],
  6389. DB_NAME(2) AS [Database_Name],
  6390. mf.name AS [Logical_Name],
  6391. mf.[size]*8 AS [Current_Size_KB],
  6392. mf.type_desc AS [File_Type],
  6393. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  6394. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount],
  6395. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((mf.size*8)*CONVERT(bigint, mf.growth))/100
  6396. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  6397. ELSE 0 END AS [Next_Growth_KB],
  6398. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  6399. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  6400. ELSE '' END AS [Comments]
  6401. FROM tempdb.sys.database_files mf (NOLOCK)
  6402. WHERE [type] = 0
  6403. GROUP BY mf.name, mf.[size], is_percent_growth, mf.growth, mf.type_desc, mf.[type]
  6404. ORDER BY 3, 4
  6405. END
  6406. ELSE
  6407. BEGIN
  6408. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Check], '[OK]' AS [Deviation]
  6409. END;
  6410. IF @ptochecks = 1
  6411. RAISERROR (N'|-Starting Performance Checks', 10, 1) WITH NOWAIT
  6412. --------------------------------------------------------------------------------------------------------------------------------
  6413. -- Perf counters, Waits, Latches and Spinlocks subsection
  6414. --------------------------------------------------------------------------------------------------------------------------------
  6415. IF @ptochecks = 1
  6416. BEGIN
  6417. SELECT @ErrorMessage = ' |-Starting Perf counters, Waits and Latches (wait for ' + CONVERT(VARCHAR(3), @duration) + 's)'
  6418. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6419. DECLARE @minctr DATETIME, @maxctr DATETIME, @durationstr NVARCHAR(24)
  6420. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  6421. DROP TABLE #tblPerfCount;
  6422. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  6423. CREATE TABLE #tblPerfCount (
  6424. [retrieval_time] [datetime],
  6425. [object_name] [NVARCHAR](128),
  6426. [counter_name] [NVARCHAR](128),
  6427. [instance_name] [NVARCHAR](128),
  6428. [counter_name_type] int,
  6429. [cntr_value] float NULL
  6430. );
  6431. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  6432. DROP TABLE tempdb.dbo.tblPerfThresholds;
  6433. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  6434. CREATE TABLE tempdb.dbo.tblPerfThresholds (
  6435. [counter_family] [NVARCHAR](128),
  6436. [counter_name] [NVARCHAR](128),
  6437. [counter_instance] [NVARCHAR](128),
  6438. [counter_name_type] int,
  6439. [counter_value] float NULL
  6440. );
  6441. -- Create the helper function
  6442. 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')
  6443. EXEC ('USE tempdb; EXEC(''
  6444. CREATE FUNCTION dbo.fn_perfctr (@ctr1Fam NVARCHAR(128), @ctr1 NVARCHAR(128))
  6445. RETURNS float
  6446. AS
  6447. BEGIN
  6448. DECLARE @ReturnVals float, @ctr1Val float, @ctr2Val float, @ctr2Fam NVARCHAR(128), @ctr2 NVARCHAR(128), @type tinyint
  6449. -- ctr1Fam = source counter object; ctr1 = source counter; ctr2Fam = counter object to compare with; ctr2 = counter to compare with
  6450. -- 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
  6451. IF @ctr1 IN (''''Forwarded Records/sec'''',''''FreeSpace Scans/sec'''',''''Page Splits/sec'''',''''Workfiles Created/sec'''',''''Page lookups/sec'''',''''SQL Compilations/sec'''')
  6452. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''Batch Requests/sec'''', @type = 1
  6453. ELSE IF @ctr1 = ''''Lock Requests/sec''''
  6454. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''Batch Requests/sec'''', @type = 0
  6455. ELSE IF @ctr1 = ''''Full Scans/sec''''
  6456. SELECT @ctr2Fam = ''''SQLServer:Access Methods'''', @ctr2 = ''''Index Searches/sec'''', @type = 1
  6457. ELSE IF @ctr1 = ''''Index Searches/sec''''
  6458. SELECT @ctr2Fam = ''''SQLServer:Access Methods'''', @ctr2 = ''''Full Scans/sec'''', @type = 3
  6459. ELSE IF @ctr1 = ''''Readahead pages/sec''''
  6460. SELECT @ctr2Fam = ''''SQLServer:Buffer Manager'''', @ctr2 = ''''Page reads/sec'''', @type = 1
  6461. ELSE IF @ctr1 = ''''Target Server Memory (KB)''''
  6462. SELECT @ctr2Fam = ''''SQLServer:Memory Manager'''', @ctr2 = ''''Total Server Memory (KB)'''', @type = 2
  6463. ELSE IF @ctr1 = ''''SQL Re-Compilations/sec''''
  6464. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''SQL Compilations/sec'''', @type = 1
  6465. ELSE IF @ctr1 = ''''Page writes/sec''''
  6466. SELECT @ctr2Fam = ''''SQLServer:Buffer Manager'''', @ctr2 = ''''Page reads/sec'''', @type = 3
  6467. SELECT @ctr1Val = [counter_value] FROM tempdb.dbo.tblPerfThresholds WHERE [counter_family] = @ctr1Fam AND [counter_name] = @ctr1
  6468. SELECT @ctr2Val = [counter_value] FROM tempdb.dbo.tblPerfThresholds WHERE [counter_family] = @ctr2Fam AND [counter_name] = @ctr2
  6469. IF @ctr1 = ''''Target Server Memory (KB)''''
  6470. SELECT @ctr1Val = @ctr1Val / 1024, @ctr2Val = @ctr2Val / 1024
  6471. --Find ratio between counter 1 and 2
  6472. IF @ctr1Val IS NULL OR @ctr2Val IS NULL
  6473. BEGIN
  6474. SELECT @ReturnVals = NULL
  6475. END
  6476. ELSE IF @ctr1Val > 1 AND @ctr2Val > 1
  6477. BEGIN
  6478. IF @type = 0
  6479. SELECT @ReturnVals = (@ctr1Val / @ctr2Val)
  6480. IF @type = 1
  6481. SELECT @ReturnVals = (@ctr1Val / @ctr2Val) * 100
  6482. If @type = 2
  6483. SELECT @ReturnVals = (@ctr1Val - @ctr2Val)
  6484. IF @type = 3
  6485. SELECT @ReturnVals = (@ctr2Val / @ctr1Val) * 100
  6486. END
  6487. ELSE
  6488. BEGIN
  6489. SELECT @ReturnVals = 0
  6490. END
  6491. RETURN (@ReturnVals)
  6492. END'')
  6493. ')
  6494. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  6495. DROP TABLE #tblWaits;
  6496. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  6497. CREATE TABLE [dbo].[#tblWaits](
  6498. [retrieval_time] [datetime],
  6499. [wait_type] [nvarchar](60) NOT NULL,
  6500. [wait_time_ms] bigint NULL,
  6501. [signal_wait_time_ms] bigint NULL,
  6502. [resource_wait_time_ms] bigint NULL
  6503. );
  6504. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  6505. DROP TABLE #tblFinalWaits;
  6506. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  6507. CREATE TABLE [dbo].[#tblFinalWaits](
  6508. [wait_type] [nvarchar](60) NOT NULL,
  6509. [wait_time_s] [numeric](16, 6) NULL,
  6510. [signal_wait_time_s] [numeric](16, 6) NULL,
  6511. [resource_wait_time_s] [numeric](16, 6) NULL,
  6512. [pct] [numeric](12, 2) NULL,
  6513. [rn] [bigint] NULL,
  6514. [signal_wait_pct] [numeric](12, 2) NULL,
  6515. [resource_wait_pct] [numeric](12, 2) NULL
  6516. );
  6517. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  6518. DROP TABLE #tblLatches;
  6519. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  6520. CREATE TABLE [dbo].[#tblLatches](
  6521. [retrieval_time] [datetime],
  6522. [latch_class] [nvarchar](60) NOT NULL,
  6523. [wait_time_ms] bigint NULL,
  6524. [waiting_requests_count] [bigint] NULL
  6525. );
  6526. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  6527. DROP TABLE #tblFinalLatches;
  6528. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  6529. CREATE TABLE [dbo].[#tblFinalLatches](
  6530. [latch_class] [nvarchar](60) NOT NULL,
  6531. [wait_time_s] [decimal](16, 6) NULL,
  6532. [waiting_requests_count] [bigint] NULL,
  6533. [pct] [decimal](12, 2) NULL,
  6534. [rn] [bigint] NULL
  6535. );
  6536. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  6537. DROP TABLE #tblSpinlocksBefore;
  6538. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  6539. CREATE TABLE [dbo].[#tblSpinlocksBefore](
  6540. [name] NVARCHAR(512) NOT NULL,
  6541. [collisions] bigint NULL,
  6542. [spins] bigint NULL,
  6543. [spins_per_collision] real NULL,
  6544. [sleep_time] bigint NULL,
  6545. [backoffs] int NULL
  6546. );
  6547. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  6548. DROP TABLE #tblSpinlocksAfter;
  6549. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  6550. CREATE TABLE [dbo].[#tblSpinlocksAfter](
  6551. [name] NVARCHAR(512) NOT NULL,
  6552. [collisions] bigint NULL,
  6553. [spins] bigint NULL,
  6554. [spins_per_collision] real NULL,
  6555. [sleep_time] bigint NULL,
  6556. [backoffs] int NULL
  6557. );
  6558. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  6559. DROP TABLE #tblFinalSpinlocks;
  6560. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  6561. CREATE TABLE [dbo].[#tblFinalSpinlocks](
  6562. [name] NVARCHAR(512) NOT NULL,
  6563. [collisions] bigint NULL,
  6564. [spins] bigint NULL,
  6565. [spins_per_collision] real NULL,
  6566. [sleep_time] bigint NULL,
  6567. [backoffs] int NULL,
  6568. [spins_pct] [decimal](12, 2) NULL,
  6569. [rn] [bigint] NULL
  6570. );
  6571. SELECT @minctr = GETDATE()
  6572. -- When counter type = 272696576 (find delta from two collection points)
  6573. -- When counter type = 65792 (face value)
  6574. -- When counter type = 1073939712 (base value, check next counter types)
  6575. -- When counter type = 1073874176 (find delta from current value and base value between two collection points). Base value is counter with type 1073939712.
  6576. -- When counter type = 537003264 (find delta from current value and base value). Base value is counter with type 1073939712.
  6577. INSERT INTO #tblPerfCount
  6578. SELECT @minctr, [object_name], counter_name, instance_name, cntr_type AS counter_name_type, cntr_value
  6579. FROM sys.dm_os_performance_counters pc0 (NOLOCK)
  6580. WHERE ([object_name] LIKE '%:Access Methods%'
  6581. OR [object_name] LIKE '%:Buffer Manager%'
  6582. OR [object_name] LIKE '%:Buffer Node%'
  6583. OR [object_name] LIKE '%:Latches%'
  6584. OR [object_name] LIKE '%:Locks%'
  6585. OR [object_name] LIKE '%:Memory Manager%'
  6586. OR [object_name] LIKE '%:Memory Node%'
  6587. OR [object_name] LIKE '%:Plan Cache%'
  6588. OR [object_name] LIKE '%:SQL Statistics%'
  6589. OR [object_name] LIKE '%:Wait Statistics%'
  6590. OR [object_name] LIKE '%:Workload Group Stats%'
  6591. OR [object_name] LIKE '%:Memory Broker Clerks%'
  6592. OR [object_name] LIKE '%:Databases%'
  6593. OR [object_name] LIKE '%:Database Replica%')
  6594. AND (counter_name LIKE '%FreeSpace Scans/sec%'
  6595. OR counter_name LIKE '%Forwarded Records/sec%'
  6596. OR counter_name LIKE '%Full Scans/sec%'
  6597. OR counter_name LIKE '%Index Searches/sec%'
  6598. OR counter_name LIKE '%Page Splits/sec%'
  6599. OR counter_name LIKE '%Scan Point Revalidations/sec%'
  6600. OR counter_name LIKE '%Table Lock Escalations/sec%'
  6601. OR counter_name LIKE '%Workfiles Created/sec%'
  6602. OR counter_name LIKE '%Worktables Created/sec%'
  6603. OR counter_name LIKE '%Worktables From Cache%'
  6604. OR counter_name LIKE '%Buffer cache hit ratio%'
  6605. OR counter_name LIKE '%Buffer cache hit ratio base%'
  6606. OR counter_name LIKE '%Checkpoint pages/sec%'
  6607. OR counter_name LIKE '%Background writer pages/sec%'
  6608. OR counter_name LIKE '%Lazy writes/sec%'
  6609. OR counter_name LIKE '%Free pages%'
  6610. OR counter_name LIKE '%Page life expectancy%'
  6611. OR counter_name LIKE '%Page lookups/sec%'
  6612. OR counter_name LIKE '%Page reads/sec%'
  6613. OR counter_name LIKE '%Page writes/sec%'
  6614. OR counter_name LIKE '%Readahead pages/sec%'
  6615. OR counter_name LIKE '%Average Latch Wait Time (ms)%'
  6616. OR counter_name LIKE '%Average Latch Wait Time Base%'
  6617. OR counter_name LIKE '%Total Latch Wait Time (ms)%'
  6618. OR counter_name LIKE '%Average Wait Time (ms)%'
  6619. OR counter_name LIKE '%Average Wait Time Base%'
  6620. OR counter_name LIKE '%Number of Deadlocks/sec%'
  6621. OR counter_name LIKE '%Free Memory (KB)%'
  6622. OR counter_name LIKE '%Stolen Server Memory (KB)%'
  6623. OR counter_name LIKE '%Target Server Memory (KB)%'
  6624. OR counter_name LIKE '%Total Server Memory (KB)%'
  6625. OR counter_name LIKE '%Free Node Memory (KB)%'
  6626. OR counter_name LIKE '%Foreign Node Memory (KB)%'
  6627. OR counter_name LIKE '%Stolen Node Memory (KB)%'
  6628. OR counter_name LIKE '%Target Node Memory (KB)%'
  6629. OR counter_name LIKE '%Total Node Memory (KB)%'
  6630. OR counter_name LIKE '%Batch Requests/sec%'
  6631. OR counter_name LIKE '%SQL Compilations/sec%'
  6632. OR counter_name LIKE '%SQL Re-Compilations/sec%'
  6633. OR counter_name LIKE '%Lock waits%'
  6634. OR counter_name LIKE '%Log buffer waits%'
  6635. OR counter_name LIKE '%Log write waits%'
  6636. OR counter_name LIKE '%Memory grant queue waits%'
  6637. OR counter_name LIKE '%Network IO waits%'
  6638. OR counter_name LIKE '%Non-Page latch waits%'
  6639. OR counter_name LIKE '%Page IO latch waits%'
  6640. OR counter_name LIKE '%Page latch waits%'
  6641. OR counter_name LIKE '%Active parallel threads%'
  6642. OR counter_name LIKE '%Blocked tasks%'
  6643. OR counter_name LIKE '%CPU usage %'
  6644. OR counter_name LIKE '%CPU usage % base%'
  6645. OR counter_name LIKE '%Query optimizations/sec%'
  6646. OR counter_name LIKE '%Requests completed/sec%'
  6647. OR counter_name LIKE '%Suboptimal plans/sec%'
  6648. OR counter_name LIKE '%Temporary Tables & Table Variables%'
  6649. OR counter_name LIKE '%Extended Stored Procedures%'
  6650. OR counter_name LIKE '%Bound Trees%'
  6651. OR counter_name LIKE '%SQL Plans%'
  6652. OR counter_name LIKE '%Object Plans%'
  6653. OR counter_name LIKE '%_Total%'
  6654. OR counter_name LIKE 'Transactions/sec%'
  6655. OR counter_name LIKE '%Log Flush Wait Time%'
  6656. OR counter_name LIKE '%Log Flush Waits/sec%'
  6657. OR counter_name LIKE '%Recovery Queue%'
  6658. OR counter_name LIKE '%Log Send Queue%'
  6659. OR counter_name LIKE '%Transaction Delay%'
  6660. OR counter_name LIKE '%Redo blocked/sec%'
  6661. OR counter_name LIKE '%Resent Messages/sec%'
  6662. OR instance_name LIKE '%Buffer Pool%'
  6663. OR instance_name LIKE '%Column store object pool%');
  6664. INSERT INTO #tblWaits
  6665. SELECT @minctr, wait_type, wait_time_ms, signal_wait_time_ms,(wait_time_ms-signal_wait_time_ms) AS resource_wait_time_ms
  6666. FROM sys.dm_os_wait_stats (NOLOCK)
  6667. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
  6668. 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT',
  6669. 'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH',
  6670. 'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6671. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6672. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6673. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6674. AND wait_type NOT LIKE N'SLEEP_%'
  6675. AND wait_time_ms > 0;
  6676. INSERT INTO #tblLatches
  6677. SELECT @minctr, latch_class, wait_time_ms, waiting_requests_count
  6678. FROM sys.dm_os_latch_stats (NOLOCK)
  6679. WHERE /*latch_class NOT IN ('BUFFER')
  6680. AND*/ wait_time_ms > 0;
  6681. IF @sqlmajorver > 9
  6682. BEGIN
  6683. INSERT INTO #tblSpinlocksBefore
  6684. SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs
  6685. FROM sys.dm_os_spinlock_stats;
  6686. END
  6687. ELSE IF @sqlmajorver = 9
  6688. BEGIN
  6689. INSERT INTO #tblSpinlocksBefore
  6690. EXEC ('DBCC SQLPERF(''spinlockstats'')');
  6691. END;
  6692. IF @duration > 255
  6693. SET @duration = 255;
  6694. IF @duration < 10
  6695. SET @duration = 10;
  6696. SELECT @durationstr = 'WAITFOR DELAY ''00:' + CASE WHEN LEN(CONVERT(VARCHAR(3),@duration/60%60)) = 1
  6697. THEN '0' + CONVERT(VARCHAR(3),@duration/60%60)
  6698. ELSE CONVERT(VARCHAR(3),@duration/60%60) END
  6699. + ':' + CONVERT(VARCHAR(3),@duration-(@duration/60)*60) + ''''
  6700. EXECUTE sp_executesql @durationstr;
  6701. SELECT @maxctr = GETDATE()
  6702. INSERT INTO #tblPerfCount
  6703. SELECT @maxctr, [object_name], counter_name, instance_name, cntr_type AS counter_name_type, cntr_value
  6704. FROM sys.dm_os_performance_counters pc0 (NOLOCK)
  6705. WHERE (cntr_type = 272696576 OR cntr_type = 1073874176 OR cntr_type = 1073939712) -- Get only counters whose delta between collection points matters
  6706. AND ([object_name] LIKE '%:Access Methods%'
  6707. OR [object_name] LIKE '%:Buffer Manager%'
  6708. OR [object_name] LIKE '%:Buffer Node%'
  6709. OR [object_name] LIKE '%:Latches%'
  6710. OR [object_name] LIKE '%:Locks%'
  6711. OR [object_name] LIKE '%:Memory Manager%'
  6712. OR [object_name] LIKE '%:Memory Node%'
  6713. OR [object_name] LIKE '%:Plan Cache%'
  6714. OR [object_name] LIKE '%:SQL Statistics%'
  6715. OR [object_name] LIKE '%:Wait Statistics%'
  6716. OR [object_name] LIKE '%:Workload Group Stats%'
  6717. OR [object_name] LIKE '%:Memory Broker Clerks%'
  6718. OR [object_name] LIKE '%:Databases%'
  6719. OR [object_name] LIKE '%:Database Replica%')
  6720. AND (counter_name LIKE '%FreeSpace Scans/sec%'
  6721. OR counter_name LIKE '%Forwarded Records/sec%'
  6722. OR counter_name LIKE '%Full Scans/sec%'
  6723. OR counter_name LIKE '%Index Searches/sec%'
  6724. OR counter_name LIKE '%Page Splits/sec%'
  6725. OR counter_name LIKE '%Scan Point Revalidations/sec%'
  6726. OR counter_name LIKE '%Table Lock Escalations/sec%'
  6727. OR counter_name LIKE '%Workfiles Created/sec%'
  6728. OR counter_name LIKE '%Worktables Created/sec%'
  6729. OR counter_name LIKE '%Worktables From Cache%'
  6730. OR counter_name LIKE '%Buffer cache hit ratio%'
  6731. OR counter_name LIKE '%Buffer cache hit ratio base%'
  6732. OR counter_name LIKE '%Checkpoint pages/sec%'
  6733. OR counter_name LIKE '%Background writer pages/sec%'
  6734. OR counter_name LIKE '%Lazy writes/sec%'
  6735. OR counter_name LIKE '%Free pages%'
  6736. OR counter_name LIKE '%Page life expectancy%'
  6737. OR counter_name LIKE '%Page lookups/sec%'
  6738. OR counter_name LIKE '%Page reads/sec%'
  6739. OR counter_name LIKE '%Page writes/sec%'
  6740. OR counter_name LIKE '%Readahead pages/sec%'
  6741. OR counter_name LIKE '%Average Latch Wait Time (ms)%'
  6742. OR counter_name LIKE '%Average Latch Wait Time Base%'
  6743. OR counter_name LIKE '%Total Latch Wait Time (ms)%'
  6744. OR counter_name LIKE '%Average Wait Time (ms)%'
  6745. OR counter_name LIKE '%Average Wait Time Base%'
  6746. OR counter_name LIKE '%Number of Deadlocks/sec%'
  6747. OR counter_name LIKE '%Free Memory (KB)%'
  6748. OR counter_name LIKE '%Stolen Server Memory (KB)%'
  6749. OR counter_name LIKE '%Target Server Memory (KB)%'
  6750. OR counter_name LIKE '%Total Server Memory (KB)%'
  6751. OR counter_name LIKE '%Free Node Memory (KB)%'
  6752. OR counter_name LIKE '%Foreign Node Memory (KB)%'
  6753. OR counter_name LIKE '%Stolen Node Memory (KB)%'
  6754. OR counter_name LIKE '%Target Node Memory (KB)%'
  6755. OR counter_name LIKE '%Total Node Memory (KB)%'
  6756. OR counter_name LIKE '%Batch Requests/sec%'
  6757. OR counter_name LIKE '%SQL Compilations/sec%'
  6758. OR counter_name LIKE '%SQL Re-Compilations/sec%'
  6759. OR counter_name LIKE '%Lock waits%'
  6760. OR counter_name LIKE '%Log buffer waits%'
  6761. OR counter_name LIKE '%Log write waits%'
  6762. OR counter_name LIKE '%Memory grant queue waits%'
  6763. OR counter_name LIKE '%Network IO waits%'
  6764. OR counter_name LIKE '%Non-Page latch waits%'
  6765. OR counter_name LIKE '%Page IO latch waits%'
  6766. OR counter_name LIKE '%Page latch waits%'
  6767. OR counter_name LIKE '%Active parallel threads%'
  6768. OR counter_name LIKE '%Blocked tasks%'
  6769. OR counter_name LIKE '%CPU usage %'
  6770. OR counter_name LIKE '%CPU usage % base%'
  6771. OR counter_name LIKE '%Query optimizations/sec%'
  6772. OR counter_name LIKE '%Requests completed/sec%'
  6773. OR counter_name LIKE '%Suboptimal plans/sec%'
  6774. OR counter_name LIKE '%Temporary Tables & Table Variables%'
  6775. OR counter_name LIKE '%Extended Stored Procedures%'
  6776. OR counter_name LIKE '%Bound Trees%'
  6777. OR counter_name LIKE '%SQL Plans%'
  6778. OR counter_name LIKE '%Object Plans%'
  6779. OR counter_name LIKE '%_Total%'
  6780. OR counter_name LIKE 'Transactions/sec%'
  6781. OR counter_name LIKE '%Log Flush Wait Time%'
  6782. OR counter_name LIKE '%Log Flush Waits/sec%'
  6783. OR counter_name LIKE '%Recovery Queue%'
  6784. OR counter_name LIKE '%Log Send Queue%'
  6785. OR counter_name LIKE '%Transaction Delay%'
  6786. OR counter_name LIKE '%Redo blocked/sec%'
  6787. OR counter_name LIKE '%Resent Messages/sec%'
  6788. OR instance_name LIKE '%Buffer Pool%'
  6789. OR instance_name LIKE '%Column store object pool%');
  6790. INSERT INTO #tblWaits
  6791. SELECT @maxctr, wait_type, wait_time_ms, signal_wait_time_ms,(wait_time_ms-signal_wait_time_ms) AS resource_wait_time_ms
  6792. FROM sys.dm_os_wait_stats (NOLOCK)
  6793. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
  6794. 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT',
  6795. 'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH',
  6796. 'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6797. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6798. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6799. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6800. AND wait_type NOT LIKE N'SLEEP_%'
  6801. AND wait_time_ms > 0;
  6802. INSERT INTO #tblLatches
  6803. SELECT @maxctr, latch_class, wait_time_ms, waiting_requests_count
  6804. FROM sys.dm_os_latch_stats (NOLOCK)
  6805. WHERE /*latch_class NOT IN ('BUFFER')
  6806. AND*/ wait_time_ms > 0;
  6807. IF @sqlmajorver > 9
  6808. BEGIN
  6809. INSERT INTO #tblSpinlocksAfter
  6810. SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs
  6811. FROM sys.dm_os_spinlock_stats;
  6812. END
  6813. ELSE IF @sqlmajorver = 9
  6814. BEGIN
  6815. INSERT INTO #tblSpinlocksAfter
  6816. EXEC ('DBCC SQLPERF(''spinlockstats'')');
  6817. END;
  6818. INSERT INTO tempdb.dbo.tblPerfThresholds
  6819. SELECT DISTINCT t1.[object_name], t1.counter_name, t1.instance_name, t1.[counter_name_type],
  6820. CASE WHEN t1.counter_name_type = 272696576
  6821. THEN CONVERT(float,(
  6822. (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) -
  6823. (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)
  6824. ) / DATEDIFF(ss,@minctr,@maxctr)) -- Get value per s over last xx s
  6825. WHEN t1.counter_name_type = 537003264
  6826. THEN (SELECT CONVERT(float,(t2.cntr_value / CASE WHEN t3.cntr_value <= 0 THEN 1 ELSE t3.cntr_value END) * 100.0)
  6827. 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')
  6828. 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
  6829. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6830. WHEN t1.counter_name_type = 1073874176 AND t1.counter_name = 'Average Latch Wait Time (ms)'
  6831. THEN CONVERT(float,(
  6832. (
  6833. (SELECT t2.cntr_value - t3.cntr_value
  6834. FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.counter_name = t3.counter_name
  6835. 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
  6836. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6837. /
  6838. (SELECT CASE WHEN t2.cntr_value - t3.cntr_value <= 0 THEN 1 ELSE t2.cntr_value - t3.cntr_value END
  6839. FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.counter_name = t3.counter_name
  6840. 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
  6841. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6842. )
  6843. / DATEDIFF(ss,@minctr,@maxctr))) -- Get value per s over last xx s
  6844. WHEN t1.counter_name_type = 1073874176 AND t1.counter_name = 'Average Wait Time (ms)'
  6845. THEN CONVERT(float,(
  6846. (
  6847. SELECT (t4.cntr_value / CASE WHEN t5.cntr_value <= 0 THEN 1 ELSE t5.cntr_value END) / DATEDIFF(ss,@minctr,@maxctr)
  6848. FROM
  6849. (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
  6850. 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
  6851. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name, t2.instance_name) AS t4
  6852. INNER JOIN
  6853. (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
  6854. 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
  6855. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name, t2.instance_name) AS t5
  6856. ON t4.instance_name = t5.instance_name
  6857. ))) -- Get value per s over last xx s
  6858. ELSE CONVERT(float,t1.cntr_value)
  6859. END
  6860. FROM #tblPerfCount t1
  6861. WHERE (t1.counter_name_type <> 1073939712)
  6862. GROUP BY t1.[object_name], t1.[counter_name], t1.instance_name, t1.counter_name_type, t1.cntr_value
  6863. ORDER BY t1.[object_name], t1.[counter_name], t1.instance_name;
  6864. ;WITH ctectr AS (SELECT [counter_family],[counter_name],[counter_instance],[counter_value],
  6865. CASE WHEN [counter_name] IN ('Worktables Created/sec','Worktables From Cache Ratio','Buffer cache hit ratio',
  6866. 'Free list stalls/sec','Free pages','Free Memory (KB)','Lazy writes/sec','Page life expectancy',
  6867. 'Page reads/sec','Log Flush Wait Time','Log Flush Waits/sec','Average Latch Wait Time (ms)',
  6868. 'Total Latch Wait Time (ms)','Lock Waits/sec','Number of Deadlocks/sec','Batch Requests/sec') THEN [counter_value]
  6869. ELSE tempdb.dbo.fn_perfctr([counter_family],[counter_name]) END AS [counter_calculated_threshold_value]
  6870. FROM tempdb.dbo.tblPerfThresholds)
  6871. SELECT 'Performance_checks' AS [Category], 'Perf_Counters' AS [Check],[counter_family],[counter_name],[counter_instance],[counter_value],[counter_calculated_threshold_value],
  6872. 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]'
  6873. 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]'
  6874. 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]'
  6875. 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]'
  6876. 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]'
  6877. WHEN [counter_name] = 'Worktables Created/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: Greater than 20 Worktables created per second]'
  6878. WHEN [counter_name] = 'Worktables From Cache Ratio' AND [counter_calculated_threshold_value] < 90 THEN '[WARNING: Less than 90 percent Worktables from Cache Ratio]'
  6879. WHEN [counter_name] = 'Buffer cache hit ratio' AND [counter_calculated_threshold_value] < 97 THEN '[WARNING: Less than 97 percent buffer cache hit ratio]'
  6880. WHEN [counter_name] = 'Buffer cache hit ratio' AND [counter_calculated_threshold_value] < 90 THEN '[WARNING: Less than 90 percent buffer cache hit ratio]'
  6881. WHEN [counter_name] = 'Free list stalls/sec' AND [counter_calculated_threshold_value] < 2 THEN '[WARNING: Free list stalls per second is less than 2]'
  6882. WHEN [counter_name] = 'Free pages' AND [counter_calculated_threshold_value] < 640 THEN '[WARNING: Less than 640 Free Pages]'
  6883. WHEN [counter_name] = 'Free Memory (KB)' AND [counter_calculated_threshold_value] < 5 THEN '[WARNING: Less than 5MB]'
  6884. WHEN [counter_name] = 'Lazy writes/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: Greater than 20 Lazy Writes per second]'
  6885. WHEN [counter_name] = 'Page life expectancy' AND [counter_calculated_threshold_value] < 300 THEN '[WARNING: Less than 300 seconds of Page Life Expectancy]'
  6886. WHEN [counter_name] = 'Page life expectancy' AND [counter_calculated_threshold_value] < 700 THEN '[WARNING: Less than 700 seconds of Page Life Expectancy]'
  6887. 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]'
  6888. WHEN [counter_name] = 'Page reads/sec' AND [counter_calculated_threshold_value] > 90 THEN '[WARNING: Greater than 90 page reads per second]'
  6889. 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]'
  6890. WHEN [counter_name] = 'Page writes/sec' AND [counter_value] > 90 THEN '[WARNING: Greater than 90 page writes per second]'
  6891. WHEN [counter_name] = 'Readahead pages/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: More than 20 percent of page reads per second]'
  6892. 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]'
  6893. 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]'
  6894. 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]'
  6895. 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]'
  6896. 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]'
  6897. 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]'
  6898. WHEN [counter_name] = 'Batch Requests/sec' AND [counter_calculated_threshold_value] > 1000 THEN '[WARNING: Greater than 1000 batch requests per second]'
  6899. 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]'
  6900. 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]'
  6901. WHEN [counter_calculated_threshold_value] IS NULL THEN NULL
  6902. ELSE '[OK]' END AS [Deviation]
  6903. FROM ctectr
  6904. ORDER BY [counter_family],[counter_name],[counter_instance];
  6905. IF @sqlmajorver >= 11
  6906. BEGIN
  6907. 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"
  6908. FROM (SELECT [counter_name],[instance_name],[cntr_value] FROM #tblPerfCount WHERE [object_name] LIKE '%Batch Resp Statistics%') AS pc
  6909. PIVOT(AVG([cntr_value]) FOR [instance_name]
  6910. IN ("CPU Time:Total(ms)", "CPU Time:Requests", "Elapsed Time:Total(ms)", "Elapsed Time:Requests")
  6911. ) AS Pvt;
  6912. END
  6913. ;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),
  6914. 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)
  6915. INSERT INTO #tblFinalWaits
  6916. SELECT DISTINCT t1.wait_type, (t2.wait_time_ms-t1.wait_time_ms) / 1000. AS wait_time_s,
  6917. (t2.signal_wait_time_ms-t1.signal_wait_time_ms) / 1000. AS signal_wait_time_s,
  6918. ((t2.wait_time_ms-t2.signal_wait_time_ms)-(t1.wait_time_ms-t1.signal_wait_time_ms)) / 1000. AS resource_wait_time_s,
  6919. 100.0 * (t2.wait_time_ms-t1.wait_time_ms) / SUM(t2.wait_time_ms-t1.wait_time_ms) OVER() AS pct,
  6920. ROW_NUMBER() OVER(ORDER BY (t2.wait_time_ms-t1.wait_time_ms) DESC) AS rn,
  6921. 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,
  6922. (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
  6923. FROM cteWaits1 t1 INNER JOIN cteWaits2 t2 ON t1.wait_type = t2.wait_type
  6924. 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
  6925. HAVING (t2.wait_time_ms-t1.wait_time_ms) > 0
  6926. ORDER BY wait_time_s DESC;
  6927. SELECT 'Performance_checks' AS [Category], 'Waits_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], W1.wait_type,
  6928. CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s,
  6929. CAST(W1.signal_wait_time_s AS DECIMAL(12, 2)) AS signal_wait_time_s,
  6930. CAST(W1.resource_wait_time_s AS DECIMAL(12, 2)) AS resource_wait_time_s,
  6931. CAST(W1.pct AS DECIMAL(12, 2)) AS pct,
  6932. CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  6933. CAST(W1.signal_wait_pct AS DECIMAL(12, 2)) AS signal_wait_pct,
  6934. CAST(W1.resource_wait_pct AS DECIMAL(12, 2)) AS resource_wait_pct,
  6935. CASE WHEN W1.wait_type LIKE N'LCK_%' OR W1.wait_type = N'LOCK' THEN N'Lock'
  6936. WHEN W1.wait_type LIKE N'LATCH_%' THEN N'Latch'
  6937. WHEN W1.wait_type LIKE N'PAGELATCH_%' THEN N'Buffer Latch'
  6938. WHEN W1.wait_type LIKE N'PAGEIOLATCH_%' THEN N'Buffer IO'
  6939. WHEN W1.wait_type LIKE N'HADR_SYNC_COMMIT' THEN N'Always On - Secondary Synch'
  6940. WHEN W1.wait_type LIKE N'HADR_%' THEN N'Always On'
  6941. WHEN W1.wait_type LIKE N'FFT_%' THEN N'FileTable'
  6942. 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;
  6943. WHEN W1.wait_type IN (N'IO_COMPLETION', N'ASYNC_IO_COMPLETION', /*N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',*/ N'DISKIO_SUSPEND') THEN N'Other IO'
  6944. WHEN W1.wait_type IN(N'BACKUPIO', N'BACKUPBUFFER') THEN 'Backup IO'
  6945. WHEN W1.wait_type = N'THREADPOOL' THEN 'CPU - Unavailable Worker Threads'
  6946. WHEN W1.wait_type = N'SOS_SCHEDULER_YIELD' THEN N'CPU - Scheduler Yielding'
  6947. WHEN W1.wait_type IN (N'CXPACKET', N'EXCHANGE') THEN N'CPU - Parallelism'
  6948. WHEN W1.wait_type IN (N'LOGMGR', N'LOGBUFFER', N'LOGMGR_RESERVE_APPEND', N'LOGMGR_FLUSH', N'WRITELOG') THEN N'Logging'
  6949. WHEN W1.wait_type IN (N'NET_WAITFOR_PACKET',N'NETWORK_IO') THEN N'Network IO'
  6950. WHEN W1.wait_type = N'ASYNC_NETWORK_IO' THEN N'Client Network IO'
  6951. WHEN W1.wait_type IN (N'UTIL_PAGE_ALLOC',N'SOS_VIRTUALMEMORY_LOW',N'CMEMTHREAD', N'SOS_RESERVEDMEMBLOCKLIST') THEN N'Memory'
  6952. WHEN W1.wait_type IN (N'RESOURCE_SEMAPHORE_SMALL_QUERY', N'RESOURCE_SEMAPHORE') THEN N'Memory - Hash or Sort'
  6953. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Memory - Compilation'
  6954. WHEN W1.wait_type LIKE N'CLR_%' OR W1.wait_type LIKE N'SQLCLR%' THEN N'CLR'
  6955. WHEN W1.wait_type LIKE N'DBMIRROR%' OR W1.wait_type = N'MIRROR_SEND_MESSAGE' THEN N'Mirroring'
  6956. 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'
  6957. -- 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'
  6958. WHEN W1.wait_type LIKE N'FT_%' THEN N'Full Text'
  6959. WHEN W1.wait_type = N'REPLICA_WRITE' THEN 'Snapshots'
  6960. WHEN W1.wait_type LIKE N'QDS%' THEN N'Query Store'
  6961. WHEN W1.wait_type LIKE N'XTP%' OR W1.wait_type LIKE N'WAIT_XTP%' THEN N'In-Memory OLTP'
  6962. ELSE N'Other' END AS 'wait_category'
  6963. FROM #tblFinalWaits AS W1 INNER JOIN #tblFinalWaits AS W2 ON W2.rn <= W1.rn
  6964. 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
  6965. HAVING W1.wait_time_s >= 0.01 AND (SUM(W2.pct)-W1.pct) < 100 -- percentage threshold
  6966. ORDER BY W1.rn;
  6967. ;WITH Waits AS
  6968. (SELECT wait_type, wait_time_ms / 1000. AS wait_time_s,
  6969. signal_wait_time_ms / 1000. AS signal_wait_time_s,
  6970. (wait_time_ms-signal_wait_time_ms) / 1000. AS resource_wait_time_s,
  6971. SUM(signal_wait_time_ms) * 1.0 / SUM(wait_time_ms) * 100 AS signal_wait_pct,
  6972. SUM(wait_time_ms-signal_wait_time_ms) * 1.0 / SUM(wait_time_ms) * 100 AS resource_wait_pct,
  6973. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  6974. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  6975. FROM sys.dm_os_wait_stats
  6976. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP'
  6977. , 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT'
  6978. ,'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH'
  6979. ,'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6980. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6981. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6982. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP', 'XTP_HOST_WAIT')
  6983. AND wait_type NOT LIKE N'SLEEP_%'
  6984. GROUP BY wait_type, wait_time_ms, signal_wait_time_ms)
  6985. SELECT 'Performance_checks' AS [Category], 'Cumulative_Waits' AS [Information], W1.wait_type,
  6986. CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s,
  6987. CAST(W1.signal_wait_time_s AS DECIMAL(12, 2)) AS signal_wait_time_s,
  6988. CAST(W1.resource_wait_time_s AS DECIMAL(12, 2)) AS resource_wait_time_s,
  6989. CAST(W1.pct AS DECIMAL(12, 2)) AS pct,
  6990. CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  6991. CAST(W1.signal_wait_pct AS DECIMAL(12, 2)) AS signal_wait_pct,
  6992. CAST(W1.resource_wait_pct AS DECIMAL(12, 2)) AS resource_wait_pct,
  6993. CASE WHEN W1.wait_type LIKE N'LCK_%' OR W1.wait_type = N'LOCK' THEN N'Lock'
  6994. -- 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;
  6995. WHEN W1.wait_type LIKE N'LATCH_%' THEN N'Latch'
  6996. -- PAGELATCH = indicates contention for access to in-memory copies of pages, like PFS, SGAM and GAM;
  6997. -- PAGELATCH_UP = Does the filegroup have enough files? Contention in PFS?
  6998. -- PAGELATCH_EX = Contention while doing many UPDATE statements against small tables?
  6999. -- 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
  7000. WHEN W1.wait_type LIKE N'PAGELATCH_%' THEN N'Buffer Latch'
  7001. -- PAGEIOLATCH = indicates IO problems, or BP pressure.
  7002. WHEN W1.wait_type LIKE N'PAGEIOLATCH_%' THEN N'Buffer IO'
  7003. WHEN W1.wait_type LIKE N'HADR_SYNC_COMMIT' THEN N'Always On - Secondary Synch'
  7004. WHEN W1.wait_type LIKE N'HADR_%' THEN N'Always On'
  7005. WHEN W1.wait_type LIKE N'FFT_%' THEN N'FileTable'
  7006. -- PREEMPTIVE_OS_WRITEFILEGATHERER (2008+) = usually autogrow scenarios, usually together with WRITELOG;
  7007. 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;
  7008. -- IO_COMPLETION = usually TempDB spilling;
  7009. -- ASYNC_IO_COMPLETION = usually when not using IFI, or waiting on backups.
  7010. -- 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;
  7011. WHEN W1.wait_type IN (N'IO_COMPLETION', N'ASYNC_IO_COMPLETION', /*N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',*/ N'DISKIO_SUSPEND') THEN N'Other IO'
  7012. -- BACKUPIO = check for slow backup media slow, like Tapes or Disks;
  7013. -- BACKUPBUFFER = usually when backing up to Tape;
  7014. WHEN W1.wait_type IN(N'BACKUPIO', N'BACKUPBUFFER') THEN 'Backup IO'
  7015. -- THREADPOOL = Look for high blocking or contention problems with workers. This will not show up in sys.dm_exec_requests;
  7016. WHEN W1.wait_type = N'THREADPOOL' THEN 'CPU - Unavailable Worker Threads'
  7017. -- 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
  7018. WHEN W1.wait_type = N'SOS_SCHEDULER_YIELD' THEN N'CPU - Scheduler Yielding'
  7019. -- Check sys.dm_os_waiting_tasks for Exchange wait types in http://technet.microsoft.com/en-us/library/ms188743.aspx;
  7020. -- Wait Resource e_waitPipeNewRow in CXPACKET waits Producer waiting on consumer for a packet to fill;
  7021. -- Wait Resource e_waitPipeGetRow in CXPACKET waits Consumer waiting on producer to fill a packet;
  7022. -- 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;
  7023. WHEN W1.wait_type IN (N'CXPACKET', N'EXCHANGE') THEN N'CPU - Parallelism'
  7024. -- WRITELOG = log management system waiting for a log flush to disk. Examine the IO latency for the log file
  7025. WHEN W1.wait_type IN (N'LOGMGR', N'LOGBUFFER', N'LOGMGR_RESERVE_APPEND', N'LOGMGR_FLUSH', N'WRITELOG') THEN N'Logging'
  7026. WHEN W1.wait_type IN (N'NET_WAITFOR_PACKET',N'NETWORK_IO') THEN N'Network IO'
  7027. WHEN W1.wait_type = N'ASYNC_NETWORK_IO' THEN N'Client Network IO'
  7028. -- 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
  7029. -- 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
  7030. WHEN W1.wait_type IN (N'UTIL_PAGE_ALLOC',N'SOS_VIRTUALMEMORY_LOW',N'CMEMTHREAD', N'SOS_RESERVEDMEMBLOCKLIST') THEN N'Memory'
  7031. -- RESOURCE_SEMAPHORE_SMALL_QUERY or RESOURCE_SEMAPHORE = queries are waiting for execution memory. Look for plans with excessive hashing or sorts.
  7032. WHEN W1.wait_type IN (N'RESOURCE_SEMAPHORE_SMALL_QUERY', N'RESOURCE_SEMAPHORE') THEN N'Memory - Hash or Sort'
  7033. -- 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
  7034. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Memory - Compilation'
  7035. WHEN W1.wait_type LIKE N'CLR_%' OR W1.wait_type LIKE N'SQLCLR%' THEN N'CLR'
  7036. -- DBMIRROR_DBM_MUTEX = indicates contention for the send buffer that database mirroring shares between all the mirroring sessions.
  7037. WHEN W1.wait_type LIKE N'DBMIRROR%' OR W1.wait_type = N'MIRROR_SEND_MESSAGE' THEN N'Mirroring'
  7038. -- 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.
  7039. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Compilation'
  7040. 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'
  7041. -- 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'
  7042. WHEN W1.wait_type LIKE N'FT_%' THEN N'Full Text'
  7043. WHEN W1.wait_type = N'REPLICA_WRITE' THEN 'Snapshots'
  7044. WHEN W1.wait_type LIKE N'QDS%' THEN N'Query Store'
  7045. WHEN W1.wait_type LIKE N'XTP%' OR W1.wait_type LIKE N'WAIT_XTP%' THEN N'In-Memory OLTP'
  7046. WHEN W1.wait_type LIKE N'PARALLEL_REDO%' THEN N'Parallel Redo'
  7047. WHEN W1.wait_type LIKE N'COLUMNSTORE%' THEN N'Columnstore'
  7048. ELSE N'Other' END AS 'wait_category'
  7049. FROM Waits AS W1 INNER JOIN Waits AS W2 ON W2.rn <= W1.rn
  7050. 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
  7051. HAVING W1.wait_time_s >= 0.01 AND (SUM(W2.pct)-W1.pct) < 100 -- percentage threshold
  7052. ORDER BY W1.rn;
  7053. ;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),
  7054. 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)
  7055. INSERT INTO #tblFinalLatches
  7056. SELECT DISTINCT t1.latch_class,
  7057. (t2.wait_time_ms-t1.wait_time_ms) / 1000.0 AS wait_time_s,
  7058. (t2.waiting_requests_count-t1.waiting_requests_count) AS waiting_requests_count,
  7059. 100.0 * (t2.wait_time_ms-t1.wait_time_ms) / SUM(t2.wait_time_ms-t1.wait_time_ms) OVER() AS pct,
  7060. ROW_NUMBER() OVER(ORDER BY t1.wait_time_ms DESC) AS rn
  7061. FROM cteLatches1 t1 INNER JOIN cteLatches2 t2 ON t1.latch_class = t2.latch_class
  7062. GROUP BY t1.latch_class, t1.wait_time_ms, t2.wait_time_ms, t1.waiting_requests_count, t2.waiting_requests_count
  7063. HAVING (t2.wait_time_ms-t1.wait_time_ms) > 0
  7064. ORDER BY wait_time_s DESC;
  7065. SELECT 'Performance_checks' AS [Category], 'Latches_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], W1.latch_class,
  7066. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7067. W1.waiting_requests_count,
  7068. CAST (W1.pct AS DECIMAL(14, 2)) AS pct,
  7069. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7070. CAST ((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7071. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7072. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7073. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7074. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7075. OR W1.latch_class LIKE N'NESTING_TRANSACTION%' THEN N'[Parallelism]'
  7076. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[Log IO]'
  7077. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7078. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER' THEN N'[Parallelism - DBCC CHECK_]'
  7079. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[Other IO]'
  7080. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION' THEN N'[Mirroring - Busy]'
  7081. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool]'
  7082. ELSE N'[Other]' END AS 'latch_category'
  7083. FROM #tblFinalLatches AS W1 INNER JOIN #tblFinalLatches AS W2 ON W2.rn <= W1.rn
  7084. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7085. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7086. ;WITH Latches AS
  7087. (SELECT latch_class,
  7088. wait_time_ms / 1000.0 AS wait_time_s,
  7089. waiting_requests_count,
  7090. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  7091. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  7092. FROM sys.dm_os_latch_stats
  7093. WHERE /*latch_class NOT IN ('BUFFER')
  7094. AND*/ wait_time_ms > 0
  7095. )
  7096. SELECT 'Performance_checks' AS [Category], 'Cumulative_Latches' AS [Information], W1.latch_class,
  7097. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7098. W1.waiting_requests_count,
  7099. CAST(W1.pct AS DECIMAL(14, 2)) AS pct,
  7100. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7101. CAST((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7102. -- 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).
  7103. -- 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.
  7104. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7105. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7106. -- 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.);
  7107. -- 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.
  7108. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7109. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7110. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7111. -- 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.
  7112. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7113. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7114. -- 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.
  7115. -- http://blogs.msdn.com/b/psssql/archive/2012/02/23/a-faster-checkdb-part-ii.aspx
  7116. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER ' THEN N'[Parallelism - DBCC CHECK_]'
  7117. -- 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.
  7118. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7119. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION ' THEN N'[Mirroring - Busy]'
  7120. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7121. ELSE N'Other' END AS 'latch_category'
  7122. FROM Latches AS W1
  7123. INNER JOIN Latches AS W2
  7124. ON W2.rn <= W1.rn
  7125. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7126. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7127. ;WITH Latches AS
  7128. (SELECT latch_class,
  7129. wait_time_ms / 1000.0 AS wait_time_s,
  7130. waiting_requests_count,
  7131. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  7132. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  7133. FROM sys.dm_os_latch_stats (NOLOCK)
  7134. WHERE latch_class NOT IN ('BUFFER')
  7135. AND wait_time_ms > 0
  7136. )
  7137. SELECT 'Performance_checks' AS [Category], 'Cumulative_Latches_wo_BUFFER' AS [Information], W1.latch_class,
  7138. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7139. W1.waiting_requests_count,
  7140. CAST(W1.pct AS DECIMAL(14, 2)) AS pct,
  7141. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7142. CAST((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7143. -- 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).
  7144. -- 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.
  7145. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7146. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7147. -- 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.);
  7148. -- 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.
  7149. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7150. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7151. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7152. -- 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.
  7153. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7154. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7155. -- 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.
  7156. -- http://blogs.msdn.com/b/psssql/archive/2012/02/23/a-faster-checkdb-part-ii.aspx
  7157. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER ' THEN N'[Parallelism - DBCC CHECK_]'
  7158. -- 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.
  7159. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7160. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION ' THEN N'[Mirroring - Busy]'
  7161. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7162. ELSE N'Other' END AS 'latch_category'
  7163. FROM Latches AS W1
  7164. INNER JOIN Latches AS W2
  7165. ON W2.rn <= W1.rn
  7166. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7167. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7168. ;WITH cteSpinlocks1 AS (SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs FROM #tblSpinlocksBefore),
  7169. cteSpinlocks2 AS (SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs FROM #tblSpinlocksAfter)
  7170. INSERT INTO #tblFinalSpinlocks
  7171. SELECT DISTINCT t1.name,
  7172. (t2.collisions-t1.collisions) AS collisions,
  7173. (t2.spins-t1.spins) AS spins,
  7174. (t2.spins_per_collision-t1.spins_per_collision) AS spins_per_collision,
  7175. (t2.sleep_time-t1.sleep_time) AS sleep_time,
  7176. (t2.backoffs-t1.backoffs) AS backoffs,
  7177. 100.0 * (t2.spins-t1.spins) / SUM(t2.spins-t1.spins) OVER() AS spins_pct,
  7178. ROW_NUMBER() OVER(ORDER BY t2.spins DESC) AS rn
  7179. FROM cteSpinlocks1 t1 INNER JOIN cteSpinlocks2 t2 ON t1.name = t2.name
  7180. 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
  7181. HAVING (t2.spins-t1.spins) > 0
  7182. ORDER BY spins DESC;
  7183. SELECT 'Performance_checks' AS [Category], 'Spinlocks_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], S1.name,
  7184. S1.collisions, S1.spins, S1.spins_per_collision, S1.sleep_time, S1.backoffs,
  7185. CAST(S1.spins_pct AS DECIMAL(14, 2)) AS spins_pct,
  7186. CAST(SUM(S1.spins_pct) AS DECIMAL(12, 2)) AS overall_running_spins_pct
  7187. FROM #tblFinalSpinlocks AS S1 INNER JOIN #tblFinalSpinlocks AS S2 ON S2.rn <= S1.rn
  7188. GROUP BY S1.rn, S1.name, S1.collisions, S1.spins, S1.spins_per_collision, S1.sleep_time, S1.backoffs, S1.spins_pct
  7189. HAVING SUM(S2.spins_pct) - S1.spins_pct < 100 -- percentage threshold
  7190. ORDER BY spins DESC;
  7191. END;
  7192. --------------------------------------------------------------------------------------------------------------------------------
  7193. -- Worker thread exhaustion subsection
  7194. --------------------------------------------------------------------------------------------------------------------------------
  7195. IF @ptochecks = 1
  7196. BEGIN
  7197. RAISERROR (N' |-Starting Worker thread exhaustion', 10, 1) WITH NOWAIT
  7198. DECLARE @avgtskcnt int, @workqcnt int
  7199. SELECT @avgtskcnt = SUM(runnable_tasks_count)/COUNT(scheduler_id), @workqcnt = SUM(work_queue_count) FROM sys.dm_os_schedulers
  7200. WHERE parent_node_id < 64 AND scheduler_id < 255
  7201. IF @avgtskcnt <= 2 AND @workqcnt > 1
  7202. BEGIN
  7203. 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]
  7204. END
  7205. ELSE IF @avgtskcnt > 2 AND @workqcnt > 1
  7206. BEGIN
  7207. 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]
  7208. END
  7209. ELSE
  7210. BEGIN
  7211. SELECT 'Performance_checks' AS [Category], 'Worker_thread_exhaustion' AS [Check], '[OK]' AS [Deviation], '' AS [Comment]
  7212. END
  7213. END;
  7214. --------------------------------------------------------------------------------------------------------------------------------
  7215. -- Blocking Chains subsection
  7216. -- Checks for blocking chains taking over 5s.
  7217. --------------------------------------------------------------------------------------------------------------------------------
  7218. IF @ptochecks = 1
  7219. BEGIN
  7220. RAISERROR (N' |-Starting Blocking Chains', 10, 1) WITH NOWAIT
  7221. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  7222. DROP TABLE #tblBlkChains;
  7223. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  7224. CREATE TABLE #tblBlkChains ([blocked_spid] [smallint], [blocked_spid_status] NVARCHAR(30), [blocked_task_status] NVARCHAR(60),
  7225. [blocked_spid_wait_type] NVARCHAR(60), [blocked_spid_wait_time_ms] [bigint], [blocked_spid_res_desc] NVARCHAR(1024),
  7226. [blocked_pageid] [int], [blocked_spid_res_type] VARCHAR(24), [blocked_batch] [xml], [blocked_statement] [xml],
  7227. [blocked_last_start] [datetime], [blocked_tran_isolation_level] VARCHAR(30), [blocker_spid] [smallint],
  7228. [is_head_blocker] [int], [blocker_batch] [xml], [blocker_statement] [xml], [blocker_last_start] [datetime],
  7229. [blocker_tran_isolation_level] VARCHAR(30), [blocked_database] NVARCHAR(128), [blocked_host] NVARCHAR(128),
  7230. [blocked_program] NVARCHAR(128), [blocked_login] NVARCHAR(128), [blocked_session_comment] VARCHAR(25),
  7231. [blocked_is_user_process] [bit], [blocker_database] NVARCHAR(128), [blocker_host] NVARCHAR(128),
  7232. [blocker_program] NVARCHAR(128), [blocker_login] NVARCHAR(128), [blocker_session_comment] VARCHAR(25), [blocker_is_user_process] [bit])
  7233. INSERT INTO #tblBlkChains
  7234. SELECT
  7235. -- blocked
  7236. es.session_id AS blocked_spid,
  7237. es.[status] AS [blocked_spid_status],
  7238. ot.task_state AS [blocked_task_status],
  7239. owt.wait_type AS blocked_spid_wait_type,
  7240. COALESCE(owt.wait_duration_ms, ABS(CONVERT(BIGINT,(DATEDIFF(mi, es.last_request_start_time, GETDATE())))*60)) AS blocked_spid_wait_time_ms,
  7241. --er.total_elapsed_time AS blocked_elapsed_time_ms,
  7242. /*
  7243. Check sys.dm_os_waiting_tasks for Exchange wait types in http://technet.microsoft.com/en-us/library/ms188743.aspx.
  7244. - Wait Resource e_waitPipeNewRow in CXPACKET waits – Producer waiting on consumer for a packet to fill.
  7245. - Wait Resource e_waitPipeGetRow in CXPACKET waits – Consumer waiting on producer to fill a packet.
  7246. */
  7247. owt.resource_description AS blocked_spid_res_desc,
  7248. owt.pageid AS blocked_pageid,
  7249. CASE WHEN owt.pageid = 1 OR owt.pageid % 8088 = 0 THEN 'Is_PFS_Page'
  7250. WHEN owt.pageid = 2 OR owt.pageid % 511232 = 0 THEN 'Is_GAM_Page'
  7251. WHEN owt.pageid = 3 OR (owt.pageid - 1) % 511232 = 0 THEN 'Is_SGAM_Page'
  7252. WHEN owt.pageid IS NULL THEN NULL
  7253. ELSE 'Is_not_PFS_GAM_SGAM_page' END AS blocked_spid_res_type,
  7254. (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(
  7255. qt.[text],
  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 qt
  7259. FOR XML PATH(''), TYPE) AS [blocked_batch],
  7260. (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(
  7261. SUBSTRING(qt2.text,
  7262. 1+(CASE WHEN er.statement_start_offset = 0 THEN 0 ELSE er.statement_start_offset/2 END),
  7263. 1+(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))),
  7264. 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'?')
  7265. AS [text()]
  7266. FROM sys.dm_exec_sql_text(COALESCE(er.sql_handle, ec.most_recent_sql_handle)) AS qt2
  7267. FOR XML PATH(''), TYPE) AS [blocked_statement],
  7268. es.last_request_start_time AS blocked_last_start,
  7269. LEFT (CASE COALESCE(es.transaction_isolation_level, er.transaction_isolation_level)
  7270. WHEN 0 THEN '0-Unspecified'
  7271. WHEN 1 THEN '1-ReadUncommitted(NOLOCK)'
  7272. WHEN 2 THEN '2-ReadCommitted'
  7273. WHEN 3 THEN '3-RepeatableRead'
  7274. WHEN 4 THEN '4-Serializable'
  7275. WHEN 5 THEN '5-Snapshot'
  7276. ELSE CONVERT (VARCHAR(30), COALESCE(es.transaction_isolation_level, er.transaction_isolation_level)) + '-UNKNOWN'
  7277. END, 30) AS blocked_tran_isolation_level,
  7278. -- blocker
  7279. er.blocking_session_id As blocker_spid,
  7280. CASE
  7281. -- session has an active request, is blocked, but is blocking others or session is idle but has an open tran and is blocking others
  7282. 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
  7283. -- session is either not blocking someone, or is blocking someone but is blocked by another party
  7284. ELSE 0
  7285. END AS is_head_blocker,
  7286. (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(
  7287. qt2.[text],
  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_batch],
  7292. (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(
  7293. SUBSTRING(qt2.text,
  7294. 1+(CASE WHEN er2.statement_start_offset = 0 THEN 0 ELSE er2.statement_start_offset/2 END),
  7295. 1+(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))),
  7296. 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'?')
  7297. AS [text()]
  7298. FROM sys.dm_exec_sql_text(COALESCE(er2.sql_handle, ec2.most_recent_sql_handle)) AS qt2
  7299. FOR XML PATH(''), TYPE) AS [blocker_statement],
  7300. es2.last_request_start_time AS blocker_last_start,
  7301. LEFT (CASE COALESCE(er2.transaction_isolation_level, es.transaction_isolation_level)
  7302. WHEN 0 THEN '0-Unspecified'
  7303. WHEN 1 THEN '1-ReadUncommitted(NOLOCK)'
  7304. WHEN 2 THEN '2-ReadCommitted'
  7305. WHEN 3 THEN '3-RepeatableRead'
  7306. WHEN 4 THEN '4-Serializable'
  7307. WHEN 5 THEN '5-Snapshot'
  7308. ELSE CONVERT (VARCHAR(30), COALESCE(er2.transaction_isolation_level, es.transaction_isolation_level)) + '-UNKNOWN'
  7309. END, 30) AS blocker_tran_isolation_level,
  7310. -- blocked - other data
  7311. DB_NAME(er.database_id) AS blocked_database,
  7312. es.[host_name] AS blocked_host,
  7313. es.[program_name] AS blocked_program,
  7314. es.login_name AS blocked_login,
  7315. CASE WHEN es.session_id = -2 THEN 'Orphaned_distributed_tran'
  7316. WHEN es.session_id = -3 THEN 'Defered_recovery_tran'
  7317. WHEN es.session_id = -4 THEN 'Unknown_tran' ELSE NULL END AS blocked_session_comment,
  7318. es.is_user_process AS [blocked_is_user_process],
  7319. -- blocker - other data
  7320. DB_NAME(er2.database_id) AS blocker_database,
  7321. es2.[host_name] AS blocker_host,
  7322. es2.[program_name] AS blocker_program,
  7323. es2.login_name AS blocker_login,
  7324. CASE WHEN es2.session_id = -2 THEN 'Orphaned_distributed_tran'
  7325. WHEN es2.session_id = -3 THEN 'Defered_recovery_tran'
  7326. WHEN es2.session_id = -4 THEN 'Unknown_tran' ELSE NULL END AS blocker_session_comment,
  7327. es2.is_user_process AS [blocker_is_user_process]
  7328. FROM sys.dm_exec_sessions es
  7329. LEFT OUTER JOIN sys.dm_exec_requests er ON es.session_id = er.session_id
  7330. LEFT OUTER JOIN sys.dm_exec_connections ec ON es.session_id = ec.session_id
  7331. LEFT OUTER JOIN sys.dm_os_tasks ot ON er.session_id = ot.session_id AND er.request_id = ot.request_id
  7332. LEFT OUTER JOIN sys.dm_exec_sessions es2 ON er.blocking_session_id = es2.session_id
  7333. LEFT OUTER JOIN sys.dm_exec_requests er2 ON es2.session_id = er2.session_id
  7334. LEFT OUTER JOIN sys.dm_exec_connections ec2 ON es2.session_id = ec2.session_id
  7335. LEFT OUTER JOIN
  7336. (
  7337. -- In some cases (e.g. parallel queries, also waiting for a worker), one thread can be flagged as
  7338. -- waiting for several different threads. This will cause that thread to show up in multiple rows
  7339. -- in our grid, which we don't want. Use ROW_NUMBER to select the longest wait for each thread,
  7340. -- and use it as representative of the other wait relationships this thread is involved in.
  7341. SELECT waiting_task_address, session_id, exec_context_id, wait_duration_ms,
  7342. wait_type, resource_address, blocking_task_address, blocking_session_id,
  7343. blocking_exec_context_id, resource_description,
  7344. 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)
  7345. ELSE NULL END AS pageid,
  7346. ROW_NUMBER() OVER (PARTITION BY waiting_task_address ORDER BY wait_duration_ms DESC) AS row_num
  7347. FROM sys.dm_os_waiting_tasks
  7348. WHERE wait_type <> 'SP_SERVER_DIAGNOSTICS_SLEEP'
  7349. ) owt ON ot.task_address = owt.waiting_task_address AND owt.row_num = 1
  7350. --OUTER APPLY sys.dm_exec_sql_text (er.sql_handle) est
  7351. --OUTER APPLY sys.dm_exec_query_plan (er.plan_handle) eqp
  7352. WHERE es.session_id <> @@SPID AND es.is_user_process = 1
  7353. 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
  7354. AND (es.session_id IN (SELECT er3.blocking_session_id FROM sys.dm_exec_requests er3) OR er.blocking_session_id IS NOT NULL)
  7355. ORDER BY blocked_spid, is_head_blocker DESC, blocked_spid_wait_time_ms DESC, blocker_spid;
  7356. IF (SELECT COUNT(blocked_spid) FROM #tblBlkChains WHERE CONVERT(VARCHAR(max), blocked_batch) <> 'sp_server_diagnostics') > 0
  7357. BEGIN
  7358. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Check], '[WARNING: Blocking chains in excess of 5s were found.]' AS [Deviation]
  7359. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Information],[blocked_spid],[blocked_spid_status],[blocked_task_status],
  7360. [blocked_spid_wait_type],[blocked_spid_wait_time_ms],[blocked_spid_res_desc],[blocked_pageid],[blocked_spid_res_type],
  7361. [blocked_batch],[blocked_statement],[blocked_last_start],[blocked_tran_isolation_level],[blocker_spid],[is_head_blocker],
  7362. [blocker_batch],[blocker_statement],[blocker_last_start],[blocker_tran_isolation_level],[blocked_database],
  7363. [blocked_host],[blocked_program],[blocked_login],[blocked_session_comment],[blocked_is_user_process],[blocker_database],
  7364. [blocker_host],[blocker_program],[blocker_login],[blocker_session_comment],[blocker_is_user_process]
  7365. FROM #tblBlkChains
  7366. END
  7367. ELSE
  7368. BEGIN
  7369. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Check], '[OK]' AS [Deviation]
  7370. END;
  7371. END;
  7372. --------------------------------------------------------------------------------------------------------------------------------
  7373. -- Plan use ratio subsection
  7374. --------------------------------------------------------------------------------------------------------------------------------
  7375. IF @ptochecks = 1
  7376. BEGIN
  7377. RAISERROR (N' |-Starting Plan use ratio', 10, 1) WITH NOWAIT
  7378. IF (SELECT SUM(CAST(size_in_bytes AS bigint))/1024/1024 AS Size_MB
  7379. FROM sys.dm_exec_cached_plans (NOLOCK)
  7380. WHERE cacheobjtype LIKE '%Plan%' AND usecounts = 1)
  7381. >=
  7382. (SELECT SUM(CAST(size_in_bytes AS bigint))/1024/1024 AS Size_MB
  7383. FROM sys.dm_exec_cached_plans (NOLOCK)
  7384. WHERE cacheobjtype LIKE '%Plan%' AND usecounts > 1)
  7385. BEGIN
  7386. 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]
  7387. END
  7388. ELSE
  7389. BEGIN
  7390. SELECT 'Performance_checks' AS [Category], 'Plan_use_ratio' AS [Check], '[OK]' AS [Deviation], '' AS [Comment]
  7391. END;
  7392. --High number of cached plans with usecounts = 1.
  7393. 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
  7394. FROM sys.dm_exec_cached_plans (NOLOCK)
  7395. WHERE cacheobjtype LIKE '%Plan%' AND usecounts = 1
  7396. GROUP BY objtype, cacheobjtype
  7397. UNION ALL
  7398. --High number of cached plans with usecounts > 1.
  7399. 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
  7400. FROM sys.dm_exec_cached_plans (NOLOCK)
  7401. WHERE cacheobjtype LIKE '%Plan%' AND usecounts > 1
  7402. GROUP BY objtype, cacheobjtype
  7403. ORDER BY objtype, cacheobjtype;
  7404. END;
  7405. --------------------------------------------------------------------------------------------------------------------------------
  7406. -- Hints usage subsection
  7407. -- Refer to "Hints" BOL entry for more information (http://msdn.microsoft.com/en-us/library/ms187713.aspx)
  7408. --------------------------------------------------------------------------------------------------------------------------------
  7409. IF @ptochecks = 1
  7410. BEGIN
  7411. RAISERROR (N' |-Starting Hints usage', 10, 1) WITH NOWAIT
  7412. IF (SELECT COUNT([counter]) FROM sys.dm_exec_query_optimizer_info WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1) > 0
  7413. BEGIN
  7414. RAISERROR (N' |-Hints are being used - finding usage in SQL modules', 10, 1) WITH NOWAIT
  7415. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  7416. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  7417. DROP TABLE #tblHints;
  7418. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  7419. CREATE TABLE #tblHints ([DBName] sysname, [Schema] VARCHAR(100), [Object] VARCHAR(255), [Type] VARCHAR(100), Hint VARCHAR(30));
  7420. UPDATE #tmpdbs0
  7421. SET isdone = 0;
  7422. UPDATE #tmpdbs0
  7423. SET isdone = 1
  7424. WHERE [state] <> 0 OR [dbid] < 5;
  7425. UPDATE #tmpdbs0
  7426. SET isdone = 1
  7427. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  7428. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  7429. BEGIN
  7430. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  7431. BEGIN
  7432. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  7433. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  7434. SELECT ''' + @dbname + ''' AS [DBName], ss.name AS [Schema_Name], so.name AS [Object_Name], so.type_desc,
  7435. CASE WHEN sm.[definition] LIKE ''%FORCE ORDER%'' THEN ''[FORCE ORDER Hint]''
  7436. WHEN sm.[definition] LIKE ''%MERGE JOIN%''
  7437. OR sm.[definition] LIKE ''%LOOP JOIN%''
  7438. OR sm.[definition] LIKE ''%HASH JOIN%'' THEN ''[JOIN Hint]'' END AS Hint
  7439. FROM sys.sql_modules sm
  7440. INNER JOIN sys.objects so ON sm.[object_id] = so.[object_id]
  7441. INNER JOIN sys.schemas ss ON so.[schema_id] = ss.[schema_id]
  7442. WHERE sm.[definition] LIKE ''%FORCE ORDER%''
  7443. OR sm.[definition] LIKE ''%MERGE JOIN%''
  7444. OR sm.[definition] LIKE ''%LOOP JOIN%''
  7445. OR sm.[definition] LIKE ''%HASH JOIN%'';'
  7446. BEGIN TRY
  7447. INSERT INTO #tblHints
  7448. EXECUTE sp_executesql @sqlcmd
  7449. END TRY
  7450. BEGIN CATCH
  7451. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  7452. SELECT @ErrorMessage = 'Hints usage subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  7453. RAISERROR (@ErrorMessage, 16, 1);
  7454. END CATCH
  7455. UPDATE #tmpdbs0
  7456. SET isdone = 1
  7457. WHERE [dbid] = @dbid
  7458. END
  7459. END;
  7460. 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]
  7461. 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
  7462. FROM sys.dm_exec_query_optimizer_info (NOLOCK)
  7463. WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1;
  7464. IF (SELECT COUNT(*) FROM #tblHints WHERE [DBName] IS NOT NULL) > 0
  7465. BEGIN
  7466. SELECT 'Performance_checks' AS [Category], 'Hints_usage_in_Objects' AS [Information], [DBName], [Schema], [Object], [Type], Hint, '' AS Comment
  7467. FROM #tblHints (NOLOCK)
  7468. ORDER BY [DBName], Hint, [Type], [Object];
  7469. END
  7470. ELSE
  7471. BEGIN
  7472. SELECT 'Performance_checks' AS [Category], 'Hints_usage_in_Objects' AS [Information], NULL AS [DBName], NULL AS [Schema], NULL AS [Object], NULL AS [Type],
  7473. 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
  7474. FROM sys.dm_exec_query_optimizer_info (NOLOCK)
  7475. WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1;
  7476. END
  7477. END
  7478. ELSE
  7479. BEGIN
  7480. SELECT 'Performance_checks' AS [Category], 'Hints_usage' AS [Check], '[OK]' AS [Deviation]
  7481. END
  7482. END;
  7483. --------------------------------------------------------------------------------------------------------------------------------
  7484. -- Cached Query Plans issues subsection
  7485. --------------------------------------------------------------------------------------------------------------------------------
  7486. IF @ptochecks = 1
  7487. BEGIN
  7488. RAISERROR (N' |-Starting Cached Query Plans issues', 10, 1) WITH NOWAIT
  7489. --DECLARE @sqlcmd NVARCHAR(max), @params NVARCHAR(500), @sqlmajorver int, @sqlminorver int, @sqlbuild int
  7490. --SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  7491. --SELECT @sqlminorver = CONVERT(int, (@@microsoftversion / 0x10000) & 0xff);
  7492. --SELECT @sqlbuild = CONVERT(int, @@microsoftversion & 0xffff);
  7493. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  7494. DROP TABLE #tmp_dm_exec_query_stats;
  7495. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  7496. CREATE TABLE #tmp_dm_exec_query_stats ([plan_id] [int] NOT NULL IDENTITY(1, 1),
  7497. [sql_handle] [varbinary](64) NOT NULL,
  7498. [statement_start_offset] [int] NOT NULL,
  7499. [statement_end_offset] [int] NOT NULL,
  7500. [plan_generation_num] [bigint] NOT NULL,
  7501. [plan_handle] [varbinary](64) NOT NULL,
  7502. [creation_time] [datetime] NOT NULL,
  7503. [last_execution_time] [datetime] NOT NULL,
  7504. [execution_count] [bigint] NOT NULL,
  7505. [total_worker_time] [bigint] NOT NULL,
  7506. [last_worker_time] [bigint] NOT NULL,
  7507. [min_worker_time] [bigint] NOT NULL,
  7508. [max_worker_time] [bigint] NOT NULL,
  7509. [total_physical_reads] [bigint] NOT NULL,
  7510. [last_physical_reads] [bigint] NOT NULL,
  7511. [min_physical_reads] [bigint] NOT NULL,
  7512. [max_physical_reads] [bigint] NOT NULL,
  7513. [total_logical_writes] [bigint] NOT NULL,
  7514. [last_logical_writes] [bigint] NOT NULL,
  7515. [min_logical_writes] [bigint] NOT NULL,
  7516. [max_logical_writes] [bigint] NOT NULL,
  7517. [total_logical_reads] [bigint] NOT NULL,
  7518. [last_logical_reads] [bigint] NOT NULL,
  7519. [min_logical_reads] [bigint] NOT NULL,
  7520. [max_logical_reads] [bigint] NOT NULL,
  7521. [total_clr_time] [bigint] NOT NULL,
  7522. [last_clr_time] [bigint] NOT NULL,
  7523. [min_clr_time] [bigint] NOT NULL,
  7524. [max_clr_time] [bigint] NOT NULL,
  7525. [total_elapsed_time] [bigint] NOT NULL,
  7526. [last_elapsed_time] [bigint] NOT NULL,
  7527. [min_elapsed_time] [bigint] NOT NULL,
  7528. [max_elapsed_time] [bigint] NOT NULL,
  7529. --2008 only
  7530. [query_hash] [binary](8) NULL,
  7531. [query_plan_hash] [binary](8) NULL,
  7532. --2008R2 only
  7533. [total_rows] bigint NULL,
  7534. [last_rows] bigint NULL,
  7535. [min_rows] bigint NULL,
  7536. [max_rows] bigint NULL,
  7537. --post 2012 SP3, 2014 SP2 and 2016
  7538. [Last_grant_kb] bigint NULL,
  7539. [Min_grant_kb] bigint NULL,
  7540. [Max_grant_kb] bigint NULL,
  7541. [Total_grant_kb] bigint NULL,
  7542. [Last_used_grant_kb] bigint NULL,
  7543. [Min_used_grant_kb] bigint NULL,
  7544. [Max_used_grant_kb] bigint NULL,
  7545. [Total_used_grant_kb] bigint NULL,
  7546. [Last_ideal_grant_kb] bigint NULL,
  7547. [Min_ideal_grant_kb] bigint NULL,
  7548. [Max_ideal_grant_kb] bigint NULL,
  7549. [Total_ideal_grant_kb] bigint NULL,
  7550. [Last_dop] bigint NULL,
  7551. [Min_dop] bigint NULL,
  7552. [Max_dop] bigint NULL,
  7553. [Total_dop] bigint NULL,
  7554. [Last_reserved_threads] bigint NULL,
  7555. [Min_reserved_threads] bigint NULL,
  7556. [Max_reserved_threads] bigint NULL,
  7557. [Total_reserved_threads] bigint NULL,
  7558. [Last_used_threads] bigint NULL,
  7559. [Min_used_threads] bigint NULL,
  7560. [Max_used_threads] bigint NULL,
  7561. [Total_used_threads] bigint NULL,
  7562. [Grant2Used_Ratio] float NULL)
  7563. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  7564. DROP TABLE #dm_exec_query_stats;
  7565. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  7566. CREATE TABLE #dm_exec_query_stats ([plan_id] [int] NOT NULL IDENTITY(1, 1),
  7567. [sql_handle] [varbinary](64) NOT NULL,
  7568. [statement_start_offset] [int] NOT NULL,
  7569. [statement_end_offset] [int] NOT NULL,
  7570. [plan_generation_num] [bigint] NOT NULL,
  7571. [plan_handle] [varbinary](64) NOT NULL,
  7572. [creation_time] [datetime] NOT NULL,
  7573. [last_execution_time] [datetime] NOT NULL,
  7574. [execution_count] [bigint] NOT NULL,
  7575. [total_worker_time] [bigint] NOT NULL,
  7576. [last_worker_time] [bigint] NOT NULL,
  7577. [min_worker_time] [bigint] NOT NULL,
  7578. [max_worker_time] [bigint] NOT NULL,
  7579. [total_physical_reads] [bigint] NOT NULL,
  7580. [last_physical_reads] [bigint] NOT NULL,
  7581. [min_physical_reads] [bigint] NOT NULL,
  7582. [max_physical_reads] [bigint] NOT NULL,
  7583. [total_logical_writes] [bigint] NOT NULL,
  7584. [last_logical_writes] [bigint] NOT NULL,
  7585. [min_logical_writes] [bigint] NOT NULL,
  7586. [max_logical_writes] [bigint] NOT NULL,
  7587. [total_logical_reads] [bigint] NOT NULL,
  7588. [last_logical_reads] [bigint] NOT NULL,
  7589. [min_logical_reads] [bigint] NOT NULL,
  7590. [max_logical_reads] [bigint] NOT NULL,
  7591. [total_clr_time] [bigint] NOT NULL,
  7592. [last_clr_time] [bigint] NOT NULL,
  7593. [min_clr_time] [bigint] NOT NULL,
  7594. [max_clr_time] [bigint] NOT NULL,
  7595. [total_elapsed_time] [bigint] NOT NULL,
  7596. [last_elapsed_time] [bigint] NOT NULL,
  7597. [min_elapsed_time] [bigint] NOT NULL,
  7598. [max_elapsed_time] [bigint] NOT NULL,
  7599. --2008 only
  7600. [query_hash] [binary](8) NULL,
  7601. [query_plan_hash] [binary](8) NULL,
  7602. --2008R2 only
  7603. [total_rows] bigint NULL,
  7604. [last_rows] bigint NULL,
  7605. [min_rows] bigint NULL,
  7606. [max_rows] bigint NULL,
  7607. --post 2012 SP3, 2014 SP2 and 2016
  7608. [Last_grant_kb] bigint NULL,
  7609. [Min_grant_kb] bigint NULL,
  7610. [Max_grant_kb] bigint NULL,
  7611. [Total_grant_kb] bigint NULL,
  7612. [Last_used_grant_kb] bigint NULL,
  7613. [Min_used_grant_kb] bigint NULL,
  7614. [Max_used_grant_kb] bigint NULL,
  7615. [Total_used_grant_kb] bigint NULL,
  7616. [Last_ideal_grant_kb] bigint NULL,
  7617. [Min_ideal_grant_kb] bigint NULL,
  7618. [Max_ideal_grant_kb] bigint NULL,
  7619. [Total_ideal_grant_kb] bigint NULL,
  7620. [Last_dop] bigint NULL,
  7621. [Min_dop] bigint NULL,
  7622. [Max_dop] bigint NULL,
  7623. [Total_dop] bigint NULL,
  7624. [Last_reserved_threads] bigint NULL,
  7625. [Min_reserved_threads] bigint NULL,
  7626. [Max_reserved_threads] bigint NULL,
  7627. [Total_reserved_threads] bigint NULL,
  7628. [Last_used_threads] bigint NULL,
  7629. [Min_used_threads] bigint NULL,
  7630. [Max_used_threads] bigint NULL,
  7631. [Total_used_threads] bigint NULL,
  7632. [Grant2Used_Ratio] float NULL,
  7633. --end
  7634. [query_plan] [xml] NULL,
  7635. [text] [nvarchar](MAX) COLLATE database_default NULL,
  7636. [text_filtered] [nvarchar](MAX) COLLATE database_default NULL)
  7637. IF @sqlmajorver = 9
  7638. BEGIN
  7639. --CPU
  7640. 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])
  7641. --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]
  7642. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7643. --ORDER BY qs.total_worker_time DESC');
  7644. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7645. 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]
  7646. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7647. ORDER BY qs.total_worker_time DESC),
  7648. 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
  7649. FROM TopSearch ts
  7650. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7651. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7652. 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]
  7653. FROM TopFineSearch tfs
  7654. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7655. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7656. ORDER BY tfs.total_worker_time DESC');
  7657. --IO
  7658. 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])
  7659. --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]
  7660. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7661. --ORDER BY qs.total_logical_reads DESC');
  7662. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7663. 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]
  7664. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7665. ORDER BY qs.total_logical_reads DESC),
  7666. 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
  7667. FROM TopSearch ts
  7668. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7669. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7670. 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]
  7671. FROM TopFineSearch tfs
  7672. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7673. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7674. ORDER BY tfs.total_logical_reads DESC');
  7675. --Recompiles
  7676. 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])
  7677. --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]
  7678. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7679. --ORDER BY qs.plan_generation_num DESC');
  7680. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7681. 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]
  7682. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7683. ORDER BY qs.plan_generation_num DESC),
  7684. 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
  7685. FROM TopSearch ts
  7686. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7687. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7688. 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]
  7689. FROM TopFineSearch tfs
  7690. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7691. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7692. ORDER BY tfs.plan_generation_num DESC');
  7693. END
  7694. ELSE IF @sqlmajorver = 10 AND (@sqlminorver = 0 OR (@sqlminorver = 50 AND @sqlbuild < 2500))
  7695. BEGIN
  7696. --CPU
  7697. 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])
  7698. --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]
  7699. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7700. --ORDER BY qs.total_worker_time DESC');
  7701. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7702. 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]
  7703. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7704. ORDER BY qs.total_worker_time DESC),
  7705. 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
  7706. FROM TopSearch ts
  7707. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7708. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7709. 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]
  7710. FROM TopFineSearch tfs
  7711. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7712. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7713. ORDER BY tfs.total_worker_time DESC');
  7714. --IO
  7715. 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])
  7716. --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]
  7717. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7718. --ORDER BY qs.total_logical_reads DESC');
  7719. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7720. 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]
  7721. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7722. ORDER BY qs.total_logical_reads DESC),
  7723. 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
  7724. FROM TopSearch ts
  7725. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7726. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7727. 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]
  7728. FROM TopFineSearch tfs
  7729. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7730. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7731. ORDER BY tfs.total_logical_reads DESC');
  7732. --Recompiles
  7733. 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])
  7734. --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]
  7735. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7736. --ORDER BY qs.plan_generation_num DESC');
  7737. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7738. 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]
  7739. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7740. ORDER BY qs.plan_generation_num DESC),
  7741. 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
  7742. FROM TopSearch ts
  7743. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7744. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7745. 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]
  7746. FROM TopFineSearch tfs
  7747. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7748. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7749. ORDER BY tfs.plan_generation_num DESC');
  7750. END
  7751. ELSE IF (@sqlmajorver = 10 AND @sqlminorver = 50) OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  7752. BEGIN
  7753. --CPU
  7754. 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])
  7755. --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]
  7756. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7757. --ORDER BY qs.total_worker_time DESC');
  7758. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7759. 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]
  7760. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7761. ORDER BY qs.total_worker_time DESC),
  7762. 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
  7763. FROM TopSearch ts
  7764. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7765. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7766. 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]
  7767. FROM TopFineSearch tfs
  7768. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7769. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7770. ORDER BY tfs.total_worker_time DESC');
  7771. --IO
  7772. 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])
  7773. --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]
  7774. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7775. --ORDER BY qs.total_logical_reads DESC');
  7776. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7777. 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]
  7778. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7779. ORDER BY qs.total_logical_reads DESC),
  7780. 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
  7781. FROM TopSearch ts
  7782. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7783. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7784. 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]
  7785. FROM TopFineSearch tfs
  7786. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7787. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7788. ORDER BY tfs.total_logical_reads DESC');
  7789. --Recompiles
  7790. 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])
  7791. --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]
  7792. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7793. --ORDER BY qs.plan_generation_num DESC');
  7794. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7795. 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]
  7796. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7797. ORDER BY qs.plan_generation_num DESC),
  7798. 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
  7799. FROM TopSearch ts
  7800. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7801. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7802. 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]
  7803. FROM TopFineSearch tfs
  7804. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7805. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7806. ORDER BY tfs.plan_generation_num DESC');
  7807. END
  7808. ELSE IF (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  7809. BEGIN
  7810. --CPU
  7811. 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])
  7812. --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]
  7813. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7814. --ORDER BY qs.total_worker_time DESC');
  7815. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7816. 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
  7817. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7818. ORDER BY qs.total_worker_time DESC),
  7819. 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
  7820. FROM TopSearch ts
  7821. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7822. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7823. 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
  7824. FROM TopFineSearch tfs
  7825. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7826. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7827. ORDER BY tfs.total_worker_time DESC');
  7828. --IO
  7829. 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])
  7830. --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]
  7831. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7832. --ORDER BY qs.total_logical_reads DESC');
  7833. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7834. 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
  7835. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7836. ORDER BY qs.total_logical_reads DESC),
  7837. 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
  7838. FROM TopSearch ts
  7839. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7840. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7841. 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
  7842. FROM TopFineSearch tfs
  7843. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7844. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7845. ORDER BY tfs.total_logical_reads DESC');
  7846. --Recompiles
  7847. 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])
  7848. --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]
  7849. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7850. --ORDER BY qs.plan_generation_num DESC');
  7851. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7852. 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
  7853. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7854. ORDER BY qs.plan_generation_num DESC),
  7855. 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
  7856. FROM TopSearch ts
  7857. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7858. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7859. 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
  7860. FROM TopFineSearch tfs
  7861. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7862. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7863. ORDER BY tfs.plan_generation_num DESC');
  7864. --Mem Grants
  7865. 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])
  7866. --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]
  7867. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7868. --ORDER BY qs.Total_grant_kb DESC');
  7869. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7870. 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
  7871. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7872. WHERE [Total_used_grant_kb] > 0
  7873. ORDER BY Total_used_grant_kb DESC, COALESCE((([Total_used_grant_kb] * 100.00) / NULLIF([Total_grant_kb],0)), 0) ASC),
  7874. 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
  7875. FROM TopSearch ts
  7876. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7877. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7878. 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
  7879. FROM TopFineSearch tfs
  7880. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7881. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7882. ORDER BY tfs.Grant2Used_Ratio ASC');
  7883. END;
  7884. -- Remove duplicates before inserting XML
  7885. IF @sqlmajorver = 9
  7886. BEGIN
  7887. 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])
  7888. 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]
  7889. FROM #tmp_dm_exec_query_stats;
  7890. END
  7891. ELSE IF @sqlmajorver = 10 AND (@sqlminorver = 0 OR (@sqlminorver = 50 AND @sqlbuild < 2500))
  7892. BEGIN
  7893. 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])
  7894. 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]
  7895. FROM #tmp_dm_exec_query_stats;
  7896. END
  7897. ELSE IF (@sqlmajorver = 10 AND @sqlminorver = 50) OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  7898. BEGIN
  7899. 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])
  7900. 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]
  7901. FROM #tmp_dm_exec_query_stats;
  7902. END
  7903. ELSE IF (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  7904. BEGIN
  7905. 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])
  7906. 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]
  7907. FROM #tmp_dm_exec_query_stats;
  7908. END;
  7909. UPDATE #dm_exec_query_stats
  7910. SET query_plan = qp.query_plan,
  7911. [text] = st.[text],
  7912. text_filtered = SUBSTRING(st.[text],
  7913. (CASE WHEN qs.statement_start_offset = 0 THEN 0 ELSE qs.statement_start_offset/2 END),
  7914. (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)))
  7915. FROM #dm_exec_query_stats qs
  7916. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
  7917. CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
  7918. -- Delete own queries
  7919. DELETE FROM #dm_exec_query_stats
  7920. WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE '%Query_Plan_Warnings%';
  7921. -- Aggregate results
  7922. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  7923. DROP TABLE #qpwarnings;
  7924. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  7925. CREATE TABLE #qpwarnings ([Deviation] VARCHAR(50), [Comment] VARCHAR(255), query_plan XML, [statement] XML)
  7926. -- Find issues
  7927. INSERT INTO #qpwarnings
  7928. SELECT 'Scalar_UDFs'AS [Deviation],
  7929. ('[WARNING: Scalar UDF found in a top resource-intensive query, which that may inhibit parallelism]') AS [Comment],
  7930. 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(
  7931. qs.text_filtered,
  7932. 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'?')
  7933. FOR XML PATH(''), TYPE) AS [statement]
  7934. FROM #dm_exec_query_stats qs
  7935. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%UserDefinedFunction%'
  7936. UNION ALL
  7937. SELECT 'Implicit_Conversion_with_IX_Scan'AS [Deviation],
  7938. ('[WARNING: Implicit type conversions found where an Index Scan is present]') AS Details ,
  7939. 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(
  7940. qs.text_filtered,
  7941. 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'?')
  7942. FOR XML PATH(''), TYPE) AS [statement]
  7943. FROM #dm_exec_query_stats qs
  7944. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%CONVERT_IMPLICIT%'
  7945. AND CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%PhysicalOp="Index Scan"%'
  7946. UNION ALL
  7947. SELECT 'Missing_Index'AS [Deviation],
  7948. ('[WARNING: One of the top resource-intensive queries may be improved by adding an index]') AS [Comment],
  7949. 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(
  7950. qs.text_filtered,
  7951. 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'?')
  7952. FOR XML PATH(''), TYPE) AS [statement]
  7953. FROM #dm_exec_query_stats qs
  7954. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%MissingIndexGroup%'
  7955. UNION ALL
  7956. SELECT 'Cursor'AS [Deviation],
  7957. ('[WARNING: Cursor usage found in a top resource-intensive query. Check if it can be rewritten as a WHILE cycle]') AS [Comment],
  7958. 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(
  7959. qs.text_filtered,
  7960. 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'?')
  7961. FOR XML PATH(''), TYPE) AS [statement]
  7962. FROM #dm_exec_query_stats qs
  7963. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<CursorType%'
  7964. UNION ALL
  7965. SELECT 'Missing_Join_Predicate'AS [Deviation],
  7966. ('[WARNING: NO JOIN predicate event fired for a top resource-intensive query]') AS [Comment],
  7967. 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(
  7968. qs.text_filtered,
  7969. 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'?')
  7970. FOR XML PATH(''), TYPE) AS [statement]
  7971. FROM #dm_exec_query_stats qs
  7972. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings NoJoinPredicate="true"%'
  7973. UNION ALL
  7974. SELECT 'Columns_with_no_Statistics'AS [Deviation],
  7975. ('[WARNING: Missing Column Statistics event fired for a top resource-intensive query]') AS [Comment],
  7976. 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(
  7977. qs.text_filtered,
  7978. 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'?')
  7979. FOR XML PATH(''), TYPE) AS [statement]
  7980. FROM #dm_exec_query_stats qs
  7981. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings ColumnsWithNoStatistics%';
  7982. IF @sqlmajorver > 10
  7983. BEGIN
  7984. INSERT INTO #qpwarnings
  7985. -- Note that currently SpillToTempDb warnings are only found in actual execution plans
  7986. SELECT 'Spill_to_TempDb'AS [Deviation],
  7987. ('[WARNING: Spill to TempDB found during a HASH or SORT operation]') AS [Comment],
  7988. 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(
  7989. qs.text_filtered,
  7990. 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'?')
  7991. FOR XML PATH(''), TYPE) AS [statement]
  7992. FROM #dm_exec_query_stats qs
  7993. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<SpillToTempDb SpillLevel%'
  7994. UNION ALL
  7995. SELECT 'Implicit_Convert_affecting_Seek_Plan'AS [Deviation],
  7996. ('[WARNING: Implicit type conversions found, which can be affecting the choice of seek plans]') AS [Comment],
  7997. 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(
  7998. qs.text_filtered,
  7999. 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'?')
  8000. FOR XML PATH(''), TYPE) AS [statement]
  8001. FROM #dm_exec_query_stats qs
  8002. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Seek Plan" Expression="CONVERT_IMPLICIT%'
  8003. UNION ALL
  8004. SELECT 'Explicit_Conversion_affecting_Cardinality'AS [Deviation],
  8005. ('[WARNING: Explicit type conversions found, which can be affecting cardinality estimates]') AS [Comment],
  8006. 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(
  8007. qs.text_filtered,
  8008. 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'?')
  8009. FOR XML PATH(''), TYPE) AS [statement]
  8010. FROM #dm_exec_query_stats qs
  8011. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Cardinality Estimate" Expression="CONVERT%'
  8012. UNION ALL
  8013. SELECT 'Implicit_Conversion_affecting_Cardinality'AS [Deviation],
  8014. ('[WARNING: Implicit type conversions found, which can be affecting cardinality estimates]') AS [Comment],
  8015. 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(
  8016. qs.text_filtered,
  8017. 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'?')
  8018. FOR XML PATH(''), TYPE) AS [statement]
  8019. FROM #dm_exec_query_stats qs
  8020. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Cardinality Estimate" Expression="CONVERT_IMPLICIT%'
  8021. UNION ALL
  8022. SELECT 'Unmatched_Indexes'AS [Deviation],
  8023. ('[WARNING: An unmatched indexes warning fired, where an index could not be used due to parameterization]') AS [Comment],
  8024. 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(
  8025. qs.text_filtered,
  8026. 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'?')
  8027. FOR XML PATH(''), TYPE) AS [statement]
  8028. FROM #dm_exec_query_stats qs
  8029. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings UnmatchedIndexes="true"%';
  8030. END;
  8031. IF (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  8032. BEGIN
  8033. INSERT INTO #qpwarnings
  8034. -- Note that currently MemoryGrant warnings are only found in actual execution plans
  8035. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8036. ('[WARNING: Granted memory was much larger than maximum used memory]') AS [Comment],
  8037. 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(
  8038. qs.text_filtered,
  8039. 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'?')
  8040. FOR XML PATH(''), TYPE) AS [statement]
  8041. FROM #dm_exec_query_stats qs
  8042. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Excessive Grant"%'
  8043. UNION ALL
  8044. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8045. ('[WARNING: Maximum used memory exceeds granted memory]') AS [Comment],
  8046. 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(
  8047. qs.text_filtered,
  8048. 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'?')
  8049. FOR XML PATH(''), TYPE) AS [statement]
  8050. FROM #dm_exec_query_stats qs
  8051. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Used More Than Granted"%'
  8052. UNION ALL
  8053. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8054. ('[WARNING: Dynamic grant increased too much when compared to initial grant request]') AS [Comment],
  8055. 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(
  8056. qs.text_filtered,
  8057. 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'?')
  8058. FOR XML PATH(''), TYPE) AS [statement]
  8059. FROM #dm_exec_query_stats qs
  8060. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Grant Increase"%'
  8061. END;
  8062. IF (SELECT COUNT(*) FROM #qpwarnings) > 0
  8063. BEGIN
  8064. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], '[WARNING: Top resource-intensive queries issued plan level warnings]' AS [Deviation]
  8065. END
  8066. ELSE
  8067. BEGIN
  8068. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], '[OK]' AS [Deviation]
  8069. END;
  8070. IF (SELECT COUNT(*) FROM #qpwarnings) > 0
  8071. BEGIN
  8072. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], [Comment], query_plan, [statement]
  8073. FROM #qpwarnings;
  8074. END;
  8075. IF (SELECT COUNT(*) FROM #dm_exec_query_stats) > 0
  8076. BEGIN
  8077. SELECT 'Performance_checks' AS [Category], 'Inefficient_Plans_Reads' AS [Check], query_plan,
  8078. (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(
  8079. text_filtered,
  8080. 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'?')
  8081. FOR XML PATH(''), TYPE) AS [statement],
  8082. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8083. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8084. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8085. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8086. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8087. [Grant2Used_Ratio],
  8088. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8089. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8090. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8091. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8092. FROM #dm_exec_query_stats
  8093. ORDER BY [Avg_Logical_Reads] DESC;
  8094. SELECT 'Performance_checks' AS [Category], 'Inefficient_Plans_CPU' AS [Check], query_plan,
  8095. (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(
  8096. text_filtered,
  8097. 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'?')
  8098. FOR XML PATH(''), TYPE) AS [statement],
  8099. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8100. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8101. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8102. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8103. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8104. [Grant2Used_Ratio],
  8105. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8106. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8107. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8108. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8109. FROM #dm_exec_query_stats
  8110. ORDER BY [Avg_Worker_Time] DESC;
  8111. SELECT 'Performance_checks' AS [Category], 'Inefficient_Memory_Use' AS [Check], query_plan,
  8112. (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(
  8113. text_filtered,
  8114. 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'?')
  8115. FOR XML PATH(''), TYPE) AS [statement],
  8116. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8117. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8118. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8119. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8120. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8121. [Grant2Used_Ratio],
  8122. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8123. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8124. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8125. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8126. FROM #dm_exec_query_stats
  8127. ORDER BY Grant2Used_Ratio ASC;
  8128. END;
  8129. END;
  8130. --------------------------------------------------------------------------------------------------------------------------------
  8131. -- Declarative Referential Integrity - Untrusted Constraints subsection
  8132. --------------------------------------------------------------------------------------------------------------------------------
  8133. IF @ptochecks = 1
  8134. BEGIN
  8135. RAISERROR (N' |-Starting Declarative Referential Integrity - Untrusted Constraints', 10, 1) WITH NOWAIT
  8136. /*
  8137. Declarative Referential Integrity (DRI), meaning “trusting” constraints will allow SQL Server to introduce optimizations that would otherwise not be possible,
  8138. such as eliminating JOINs or even not reading any table for particular queries.
  8139. 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.
  8140. */
  8141. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  8142. DROP TABLE #tblDRI;
  8143. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  8144. 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)
  8145. CONSTRAINT PK_DRI PRIMARY KEY CLUSTERED(databaseID, [schema_id], [object_id], [constraint_name]))
  8146. UPDATE #tmpdbs1
  8147. SET isdone = 0
  8148. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  8149. BEGIN
  8150. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  8151. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8152. USE ' + QUOTENAME(@dbname) + '
  8153. 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]
  8154. FROM sys.foreign_keys FKC (NOLOCK)
  8155. INNER JOIN sys.objects o (NOLOCK) ON FKC.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 FKC.is_not_trusted = 1 AND FKC.is_not_for_replication = 0
  8159. GROUP BY o.[schema_id], mst.[object_id], FKC.name, t.name, mst.name
  8160. UNION ALL
  8161. 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]
  8162. FROM sys.check_constraints CC (NOLOCK)
  8163. INNER JOIN sys.objects o (NOLOCK) ON CC.parent_object_id = o.[object_id]
  8164. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8165. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8166. WHERE o.type = ''U'' AND CC.is_not_trusted = 1 AND CC.is_not_for_replication = 0 AND CC.is_disabled = 0
  8167. GROUP BY t.[schema_id], mst.[object_id], CC.name, t.name, mst.name
  8168. ORDER BY mst.name, [constraint_name];'
  8169. BEGIN TRY
  8170. INSERT INTO #tblDRI
  8171. EXECUTE sp_executesql @sqlcmd
  8172. END TRY
  8173. BEGIN CATCH
  8174. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8175. SELECT @ErrorMessage = 'Declarative Referential Integrity subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8176. RAISERROR (@ErrorMessage, 16, 1);
  8177. END CATCH
  8178. UPDATE #tmpdbs1
  8179. SET isdone = 1
  8180. WHERE [dbid] = @dbid
  8181. END;
  8182. IF (SELECT COUNT(*) FROM #tblDRI) > 0
  8183. BEGIN
  8184. 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]
  8185. SELECT 'Performance_checks' AS [Category], 'DRI_UntrustedConstraints' AS [Information], [database_name] AS [Database_Name], constraint_name AS [Constraint_Name],
  8186. [schema_name] AS [Schema_Name], table_name AS [Table_Name], [constraint_type] AS [Constraint_Type]
  8187. FROM #tblDRI
  8188. ORDER BY [database_name], [schema_name], table_name, [constraint_type];
  8189. IF @gen_scripts = 1
  8190. BEGIN
  8191. DECLARE @strSQL1 NVARCHAR(4000)
  8192. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8193. PRINT CHAR(10) + '--############# Trust untrusted Contraints statements #############' + CHAR(10)
  8194. DECLARE cDRI CURSOR FAST_FORWARD FOR SELECT 'USE ' + [database_name] + CHAR(10) + 'GO' + CHAR(10) +
  8195. 'ALTER TABLE ' + QUOTENAME([schema_name]) + '.' + QUOTENAME(table_name) + CHAR(10) +
  8196. 'WITH CHECK CHECK CONSTRAINT ' + QUOTENAME(constraint_name) + CHAR(10) + 'GO'
  8197. FROM #tblDRI
  8198. ORDER BY [database_name], [schema_name], table_name, [constraint_type]
  8199. OPEN cDRI
  8200. FETCH NEXT FROM cDRI INTO @strSQL1
  8201. WHILE (@@FETCH_STATUS = 0)
  8202. BEGIN
  8203. PRINT @strSQL1
  8204. FETCH NEXT FROM cDRI INTO @strSQL1
  8205. END
  8206. CLOSE cDRI
  8207. DEALLOCATE cDRI
  8208. PRINT CHAR(10) + '--############# Ended Trust untrusted Contraints statements #############' + CHAR(10)
  8209. END;
  8210. END
  8211. ELSE
  8212. BEGIN
  8213. SELECT 'Performance_checks' AS [Category], 'DRI_UntrustedConstraints' AS [Check], '[OK]' AS [Deviation]
  8214. END;
  8215. END;
  8216. IF @ptochecks = 1
  8217. RAISERROR (N'|-Starting Indexes and Statistics Checks', 10, 1) WITH NOWAIT
  8218. --------------------------------------------------------------------------------------------------------------------------------
  8219. -- Statistics update subsection
  8220. --------------------------------------------------------------------------------------------------------------------------------
  8221. IF @ptochecks = 1
  8222. BEGIN
  8223. RAISERROR (N' |-Starting Statistics update', 10, 1) WITH NOWAIT
  8224. UPDATE #tmpdbs0
  8225. SET isdone = 0;
  8226. UPDATE #tmpdbs0
  8227. SET isdone = 1
  8228. WHERE [state] <> 0 OR [dbid] < 5;
  8229. UPDATE #tmpdbs0
  8230. SET isdone = 1
  8231. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8232. DECLARE @dbcmptlevel int
  8233. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  8234. DROP TABLE #tblStatsUpd;
  8235. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  8236. 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)
  8237. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8238. BEGIN
  8239. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8240. BEGIN
  8241. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid], @dbcmptlevel = [compatibility_level] FROM #tmpdbs0 WHERE isdone = 0
  8242. IF ((@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4000) OR (@sqlmajorver = 11 AND @sqlbuild >= 3000) OR @sqlmajorver > 11) AND @dbcmptlevel > 80
  8243. BEGIN
  8244. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8245. 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,
  8246. 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
  8247. FROM sys.objects AS o
  8248. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8249. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8250. INNER JOIN sys.stats AS ss ON ss.[object_id] = mst.[object_id]
  8251. CROSS APPLY sys.dm_db_stats_properties(ss.[object_id], ss.[stats_id]) AS sp
  8252. WHERE sp.[rows] > 0
  8253. AND ((sp.[rows] <= 500 AND sp.modification_counter >= 500)
  8254. OR (sp.[rows] > 500 AND sp.modification_counter >= (500 + sp.[rows] * 0.20)))'
  8255. END
  8256. ELSE
  8257. BEGIN
  8258. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8259. 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,
  8260. 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
  8261. FROM sys.sysindexes AS si
  8262. INNER JOIN sys.objects AS o ON si.id = o.[object_id]
  8263. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8264. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8265. INNER JOIN sys.stats AS ss ON ss.[object_id] = o.[object_id]
  8266. INNER JOIN sys.partitions AS p ON p.[object_id] = ss.[object_id]
  8267. LEFT JOIN sys.indexes i ON si.id = i.[object_id] AND si.indid = i.index_id
  8268. WHERE o.type <> ''S'' AND i.name IS NOT NULL
  8269. GROUP BY mst.[object_id], t.name, rowmodctr, ss.stats_id, ss.name, ss.auto_created, ss.user_created
  8270. HAVING SUM(p.[rows]) > 0
  8271. AND ((SUM(p.[rows]) <= 500 AND rowmodctr >= 500)
  8272. OR (SUM(p.[rows]) > 500 AND rowmodctr >= (500 + SUM(p.[rows]) * 0.20)))'
  8273. END
  8274. BEGIN TRY
  8275. INSERT INTO #tblStatsUpd
  8276. EXECUTE sp_executesql @sqlcmd
  8277. END TRY
  8278. BEGIN CATCH
  8279. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8280. SELECT @ErrorMessage = 'Statistics update subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8281. RAISERROR (@ErrorMessage, 16, 1);
  8282. END CATCH
  8283. UPDATE #tmpdbs0
  8284. SET isdone = 1
  8285. WHERE [dbid] = @dbid
  8286. END
  8287. END;
  8288. CREATE INDEX IX_Stats ON #tblStatsUpd([databaseID]);
  8289. IF (SELECT COUNT(*) FROM #tblStatsUpd) > 0
  8290. BEGIN
  8291. 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
  8292. BEGIN
  8293. 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]
  8294. 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],
  8295. last_updated, [rows], modification_counter, CAST((su.modification_counter*1.00/(su.[rows]*1.00))*100.0 AS DECIMAL(18,2)) AS [RowMod_Pct],
  8296. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8297. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8298. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8299. ELSE NULL
  8300. END AS [Statistic_Type],
  8301. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition], su.unfiltered_rows AS [Unfiltered_Rows]
  8302. FROM #tblStatsUpd AS su INNER JOIN master.sys.databases AS sd (NOLOCK) ON su.[databaseID] = sd.[database_id]
  8303. WHERE sd.is_auto_update_stats_on = 0
  8304. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8305. END;
  8306. 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
  8307. BEGIN
  8308. 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]
  8309. 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],
  8310. last_updated, [rows], modification_counter, CAST((su.modification_counter*1.00/(su.[rows]*1.00))*100.0 AS DECIMAL(18,2)) AS [RowMod_Pct],
  8311. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8312. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8313. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8314. ELSE NULL
  8315. END AS [Statistic_Type],
  8316. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition]
  8317. FROM #tblStatsUpd AS su INNER JOIN master.sys.databases AS sd (NOLOCK) ON su.[databaseID] = sd.[database_id]
  8318. WHERE sd.is_auto_update_stats_on = 1
  8319. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8320. END;
  8321. END
  8322. ELSE
  8323. BEGIN
  8324. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_to_update' AS [Check], '[OK]' AS [Deviation]
  8325. END;
  8326. END;
  8327. --------------------------------------------------------------------------------------------------------------------------------
  8328. -- Statistics sampling subsection
  8329. --------------------------------------------------------------------------------------------------------------------------------
  8330. IF @ptochecks = 1
  8331. BEGIN
  8332. IF (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4000) OR (@sqlmajorver = 11 AND @sqlbuild >= 3000) OR @sqlmajorver > 11
  8333. BEGIN
  8334. RAISERROR (N' |-Starting Statistics sampling', 10, 1) WITH NOWAIT
  8335. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  8336. DROP TABLE #tblStatsSamp;
  8337. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  8338. 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)
  8339. UPDATE #tmpdbs0
  8340. SET isdone = 0;
  8341. UPDATE #tmpdbs0
  8342. SET isdone = 1
  8343. WHERE [state] <> 0 OR [dbid] < 5;
  8344. UPDATE #tmpdbs0
  8345. SET isdone = 1
  8346. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8347. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8348. BEGIN
  8349. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8350. BEGIN
  8351. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid], @dbcmptlevel = [compatibility_level] FROM #tmpdbs0 WHERE isdone = 0
  8352. IF @dbcmptlevel > 80
  8353. BEGIN
  8354. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8355. 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,
  8356. 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
  8357. FROM sys.objects AS o
  8358. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8359. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8360. INNER JOIN sys.stats AS ss ON ss.[object_id] = mst.[object_id]
  8361. CROSS APPLY sys.dm_db_stats_properties(ss.[object_id], ss.[stats_id]) AS sp
  8362. WHERE sp.[rows] > 0
  8363. AND CAST((sp.rows_sampled/(sp.[rows]*1.00))*100.0 AS DECIMAL(5,2)) < 25'
  8364. BEGIN TRY
  8365. INSERT INTO #tblStatsSamp
  8366. EXECUTE sp_executesql @sqlcmd
  8367. END TRY
  8368. BEGIN CATCH
  8369. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8370. SELECT @ErrorMessage = 'Statistics sampling subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8371. RAISERROR (@ErrorMessage, 16, 1);
  8372. END CATCH
  8373. END
  8374. UPDATE #tmpdbs0
  8375. SET isdone = 1
  8376. WHERE [dbid] = @dbid
  8377. END
  8378. END;
  8379. CREATE INDEX IX_Stats ON #tblStatsSamp([databaseID]);
  8380. IF (SELECT COUNT(*) FROM #tblStatsSamp) > 0
  8381. BEGIN
  8382. 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]
  8383. 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],
  8384. last_updated, [rows], rows_sampled, CAST((rows_sampled/([rows]*1.00))*100.0 AS DECIMAL(5,2)) AS [Sample_Pct],
  8385. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8386. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8387. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8388. ELSE NULL
  8389. END AS [Statistic_Type],
  8390. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition]
  8391. FROM #tblStatsSamp AS su
  8392. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8393. END
  8394. ELSE
  8395. BEGIN
  8396. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_sampling_lt_25pct' AS [Check], '[OK]' AS [Deviation]
  8397. END;
  8398. END;
  8399. END;
  8400. --------------------------------------------------------------------------------------------------------------------------------
  8401. -- Hypothetical objects subsection
  8402. --------------------------------------------------------------------------------------------------------------------------------
  8403. IF @ptochecks = 1
  8404. BEGIN
  8405. RAISERROR (N' |-Starting Hypothetical objects', 10, 1) WITH NOWAIT
  8406. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  8407. DROP TABLE #tblHypObj;
  8408. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  8409. CREATE TABLE #tblHypObj ([DBName] sysname, [Schema] VARCHAR(100), [Table] VARCHAR(255), [Object] VARCHAR(255), [Type] VARCHAR(10));
  8410. UPDATE #tmpdbs0
  8411. SET isdone = 0;
  8412. UPDATE #tmpdbs0
  8413. SET isdone = 1
  8414. WHERE [state] <> 0 OR [dbid] = 2;
  8415. UPDATE #tmpdbs0
  8416. SET isdone = 1
  8417. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8418. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8419. BEGIN
  8420. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8421. BEGIN
  8422. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  8423. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8424. SELECT ''' + @dbname + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), i.name, ''INDEX''
  8425. FROM sys.indexes i
  8426. INNER JOIN sys.objects o ON o.[object_id] = i.[object_id]
  8427. INNER JOIN sys.tables AS mst ON mst.[object_id] = i.[object_id]
  8428. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8429. WHERE i.is_hypothetical = 1
  8430. UNION ALL
  8431. SELECT ''' + @dbname + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), s.name, ''STATISTICS''
  8432. FROM sys.stats s
  8433. INNER JOIN sys.objects o (NOLOCK) ON o.[object_id] = s.[object_id]
  8434. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = s.[object_id]
  8435. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8436. WHERE (s.name LIKE ''hind_%'' OR s.name LIKE ''_dta_stat%'') AND auto_created = 0
  8437. AND s.name NOT IN (SELECT name FROM ' + QUOTENAME(@dbname) + '.sys.indexes)'
  8438. BEGIN TRY
  8439. INSERT INTO #tblHypObj
  8440. EXECUTE sp_executesql @sqlcmd
  8441. END TRY
  8442. BEGIN CATCH
  8443. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8444. SELECT @ErrorMessage = 'Hypothetical objects subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8445. RAISERROR (@ErrorMessage, 16, 1);
  8446. END CATCH
  8447. UPDATE #tmpdbs0
  8448. SET isdone = 1
  8449. WHERE [dbid] = @dbid
  8450. END
  8451. END;
  8452. UPDATE #tmpdbs0
  8453. SET isdone = 0;
  8454. IF (SELECT COUNT([Object]) FROM #tblHypObj) > 0
  8455. BEGIN
  8456. 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]
  8457. 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]
  8458. FROM #tblHypObj
  8459. ORDER BY 2, 3, 5
  8460. IF @gen_scripts = 1
  8461. BEGIN
  8462. DECLARE @strSQL NVARCHAR(4000)
  8463. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8464. PRINT CHAR(10) + '--############# Existing Hypothetical objects drop statements #############' + CHAR(10)
  8465. 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) +
  8466. CASE WHEN [Type] = 'STATISTICS' THEN 'DROP STATISTICS ' + [Schema] + '.' + [Table] + '.' + QUOTENAME([Object]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  8467. ELSE 'DROP INDEX ' + QUOTENAME([Object]) + ' ON ' + [Schema] + '.' + [Table] + ';' + CHAR(10) + 'GO' + CHAR(10)
  8468. END
  8469. FROM #tblHypObj
  8470. ORDER BY DBName, [Table]
  8471. OPEN ITW_Stats
  8472. FETCH NEXT FROM ITW_Stats INTO @strSQL
  8473. WHILE (@@FETCH_STATUS = 0)
  8474. BEGIN
  8475. PRINT @strSQL
  8476. FETCH NEXT FROM ITW_Stats INTO @strSQL
  8477. END
  8478. CLOSE ITW_Stats
  8479. DEALLOCATE ITW_Stats
  8480. PRINT CHAR(10) + '--############# Ended Hypothetical objects drop statements #############' + CHAR(10)
  8481. END;
  8482. END
  8483. ELSE
  8484. BEGIN
  8485. SELECT 'Index_and_Stats_checks' AS [Category], 'Hypothetical_objects' AS [Check], '[OK]' AS [Deviation]
  8486. END;
  8487. END;
  8488. --------------------------------------------------------------------------------------------------------------------------------
  8489. -- Index Health Analysis subsection
  8490. --------------------------------------------------------------------------------------------------------------------------------
  8491. IF @ixfrag = 1 AND @ptochecks = 1
  8492. BEGIN
  8493. RAISERROR (N' |-Starting Index Health Analysis check', 10, 1) WITH NOWAIT
  8494. DECLARE /*@dbid int, */@objectid int, @indexid int, @partition_nr int, @type_desc NVARCHAR(60)
  8495. DECLARE @ColumnStoreGetIXSQL NVARCHAR(2000), @ColumnStoreGetIXSQL_Param NVARCHAR(1000), @HasInMem bit
  8496. DECLARE /*@sqlcmd NVARCHAR(4000), @params NVARCHAR(500),*/ @schema_name VARCHAR(100), @table_name VARCHAR(300), @KeyCols VARCHAR(4000), @distinctCnt bigint, @OptimBucketCnt bigint
  8497. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  8498. DROP TABLE #tmpIPS;
  8499. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  8500. 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,
  8501. CONSTRAINT PK_IPS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id], [partition_number]));
  8502. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  8503. DROP TABLE #tmpIPS_CI;
  8504. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  8505. 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),
  8506. CONSTRAINT PK_IPS_CI PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id], [partition_number], row_group_id));
  8507. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  8508. DROP TABLE #tmpXIS;
  8509. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  8510. 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,
  8511. CONSTRAINT PK_tmpXIS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id]));
  8512. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  8513. DROP TABLE #tmpXNCIS;
  8514. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  8515. 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,
  8516. CONSTRAINT PK_tmpXNCIS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id]));
  8517. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  8518. DROP TABLE #tblWorking;
  8519. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  8520. 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)
  8521. -- type 0 = Heap; 1 = Clustered; 2 = Nonclustered; 3 = XML; 4 = Spatial; 5 = Clustered columnstore; 6 = Nonclustered columnstore; 7 = Nonclustered hash
  8522. RAISERROR (N' |-Populating support table...', 10, 1) WITH NOWAIT
  8523. UPDATE #tmpdbs0
  8524. SET isdone = 0;
  8525. UPDATE #tmpdbs0
  8526. SET isdone = 1
  8527. WHERE [state] <> 0 OR [dbid] < 5;
  8528. UPDATE #tmpdbs0
  8529. SET isdone = 1
  8530. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8531. IF EXISTS (SELECT TOP 1 id FROM #tmpdbs0 WHERE isdone = 0)
  8532. BEGIN
  8533. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8534. BEGIN
  8535. SELECT TOP 1 @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  8536. 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
  8537. FROM [' + DB_NAME(@dbid) + '].sys.indexes si
  8538. INNER JOIN [' + DB_NAME(@dbid) + '].sys.partitions sp ON si.[object_id] = sp.[object_id] AND si.index_id = sp.index_id
  8539. INNER JOIN [' + DB_NAME(@dbid) + '].sys.tables AS mst ON mst.[object_id] = si.[object_id]
  8540. INNER JOIN [' + DB_NAME(@dbid) + '].sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8541. 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
  8542. INSERT INTO #tblWorking
  8543. EXEC sp_executesql @sqlcmd;
  8544. IF @sqlmajorver >= 12
  8545. BEGIN
  8546. SELECT @sqlcmd = 'SELECT @HasInMemOUT = ISNULL((SELECT TOP 1 1 FROM [' + DB_NAME(@dbid) + '].sys.filegroups FG where FG.[type] = ''FX''), 0)'
  8547. SET @params = N'@HasInMemOUT bit OUTPUT';
  8548. EXECUTE sp_executesql @sqlcmd, @params, @HasInMemOUT=@HasInMem OUTPUT
  8549. IF @HasInMem = 1
  8550. BEGIN
  8551. 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)
  8552. EXECUTE sp_executesql @ColumnStoreGetIXSQL, @ColumnStoreGetIXSQL_Param, @dbid_In = @dbid, @objectid_In = @objectid, @indexid_In = @indexid, @partition_nr_In = @partition_nr;
  8553. SELECT @ErrorMessage = ' |-Gathering sys.dm_db_xtp_hash_index_stats and sys.dm_db_xtp_nonclustered_index_stats data in ' + DB_NAME(@dbid) + '...'
  8554. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT;
  8555. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8556. USE [' + DB_NAME(@dbid) + '];
  8557. 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,
  8558. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8559. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8560. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8561. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8562. WHERE si.[object_id] = i.[object_id] AND si.index_id = i.index_id AND ic.is_included_column = 0
  8563. ORDER BY ic.key_ordinal
  8564. FOR XML PATH('''')), 2, 8000) AS KeyCols, NULL, NULL, 0
  8565. FROM sys.dm_db_xtp_hash_index_stats AS xhis
  8566. INNER JOIN sys.dm_db_xtp_index_stats AS xis ON xis.[object_id] = xhis.[object_id] AND xis.[index_id] = xhis.[index_id]
  8567. INNER JOIN sys.indexes AS si (NOLOCK) ON xis.[object_id] = si.[object_id] AND xis.[index_id] = si.[index_id]
  8568. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  8569. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8570. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8571. WHERE o.[type] = ''U'''
  8572. BEGIN TRY
  8573. INSERT INTO #tmpXIS
  8574. EXECUTE sp_executesql @sqlcmd
  8575. END TRY
  8576. BEGIN CATCH
  8577. 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)) + ')'
  8578. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8579. END CATCH
  8580. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8581. USE [' + DB_NAME(@dbid) + '];
  8582. SELECT ' + CONVERT(NVARCHAR(20), @dbid) + ' AS [database_id],
  8583. xis.[object_id], t.name, o.name, xis.index_id, si.name, si.type_desc,
  8584. xnis.delta_pages, xnis.internal_pages, xnis.leaf_pages, xnis.page_update_count,
  8585. xnis.page_update_retry_count, xnis.page_consolidation_count,
  8586. xnis.page_consolidation_retry_count, xnis.page_split_count, xnis.page_split_retry_count,
  8587. xnis.key_split_count, xnis.key_split_retry_count, xnis.page_merge_count, xnis.page_merge_retry_count,
  8588. xnis.key_merge_count, xnis.key_merge_retry_count,
  8589. xis.scans_started, xis.scans_retries
  8590. FROM sys.dm_db_xtp_nonclustered_index_stats AS xnis (NOLOCK)
  8591. 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]
  8592. INNER JOIN sys.indexes AS si (NOLOCK) ON xis.[object_id] = si.[object_id] AND xis.[index_id] = si.[index_id]
  8593. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  8594. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8595. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8596. WHERE o.[type] = ''U'''
  8597. BEGIN TRY
  8598. INSERT INTO #tmpXNCIS
  8599. EXECUTE sp_executesql @sqlcmd
  8600. END TRY
  8601. BEGIN CATCH
  8602. 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)) + ')'
  8603. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8604. END CATCH
  8605. END;
  8606. /*ELSE
  8607. BEGIN
  8608. SELECT @ErrorMessage = ' |-Skipping ' + DB_NAME(@dbid) + '. No memory optimized filegroup was found...'
  8609. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT;
  8610. END;*/
  8611. END;
  8612. UPDATE #tmpdbs0
  8613. SET isdone = 1
  8614. WHERE [dbid] = @dbid;
  8615. END
  8616. END;
  8617. IF EXISTS (SELECT TOP 1 database_id FROM #tmpXIS WHERE isdone = 0)
  8618. BEGIN
  8619. RAISERROR (' |-Gathering additional data on xtp hash indexes...', 10, 1) WITH NOWAIT;
  8620. WHILE (SELECT COUNT(database_id) FROM #tmpXIS WHERE isdone = 0) > 0
  8621. BEGIN
  8622. 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
  8623. 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;'
  8624. SET @params = N'@distinctCntOUT bigint OUTPUT, @OptimBucketCntOUT bigint OUTPUT';
  8625. EXECUTE sp_executesql @sqlcmd, @params, @distinctCntOUT=@distinctCnt OUTPUT, @OptimBucketCntOUT=@OptimBucketCnt OUTPUT;
  8626. UPDATE #tmpXIS
  8627. SET DistinctCnt = @distinctCnt, OptimBucketCnt = @OptimBucketCnt, isdone = 1
  8628. WHERE database_id = @dbid AND [object_id] = @objectid AND [index_id] = @indexid;
  8629. END;
  8630. END;
  8631. IF (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND [type] <= 2) > 0
  8632. BEGIN
  8633. RAISERROR (' |-Gathering sys.dm_db_index_physical_stats data...', 10, 1) WITH NOWAIT;
  8634. WHILE (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND [type] <= 2) > 0
  8635. BEGIN
  8636. SELECT TOP 1 @dbid = database_id, @objectid = [object_id], @indexid = index_id, @partition_nr = partition_number
  8637. FROM #tblWorking WHERE is_done = 0 AND [type] <= 2
  8638. INSERT INTO #tmpIPS
  8639. SELECT ps.database_id, ps.[object_id], ps.index_id, ps.partition_number, SUM(ps.avg_fragmentation_in_percent), SUM(ps.page_count),
  8640. CAST((SUM(ps.page_count)*8)/1024 AS DECIMAL(26,3)) AS [size_MB], ps.record_count, ps.forwarded_record_count -- for heaps
  8641. FROM sys.dm_db_index_physical_stats(@dbid, @objectid, @indexid , @partition_nr, @ixfragscanmode) AS ps
  8642. WHERE /*ps.index_id > 0 -- ignore heaps
  8643. AND */ps.index_level = 0 -- leaf-level nodes only
  8644. AND ps.alloc_unit_type_desc = 'IN_ROW_DATA'
  8645. GROUP BY ps.database_id, ps.[object_id], ps.index_id, ps.partition_number, ps.record_count, ps.forwarded_record_count
  8646. OPTION (MAXDOP 2);
  8647. UPDATE #tblWorking
  8648. SET is_done = 1
  8649. WHERE database_id = @dbid AND [object_id] = @objectid AND index_id = @indexid AND partition_number = @partition_nr
  8650. END
  8651. END;
  8652. IF (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND type = 5) > 0
  8653. BEGIN
  8654. RAISERROR (' |-Gathering sys.column_store_row_groups data...', 10, 1) WITH NOWAIT;
  8655. WHILE (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND type IN (5,6)) > 0
  8656. BEGIN
  8657. SELECT TOP 1 @dbid = database_id, @objectid = [object_id], @indexid = index_id, @partition_nr = partition_number
  8658. FROM #tblWorking WHERE is_done = 0 AND type IN (5,6)
  8659. BEGIN TRY
  8660. 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
  8661. FROM [' + DB_NAME(@dbid) + '].sys.column_store_row_groups rg
  8662. WHERE rg.object_id = @objectid_In
  8663. AND rg.index_id = @indexid_In
  8664. AND rg.partition_number = @partition_nr_In
  8665. --AND rg.state = 3 -- Only COMPRESSED row groups
  8666. 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
  8667. OPTION (MAXDOP 2)'
  8668. SET @ColumnStoreGetIXSQL_Param = N'@dbid_In int, @objectid_In int, @indexid_In int, @partition_nr_In int';
  8669. 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)
  8670. EXECUTE sp_executesql @ColumnStoreGetIXSQL, @ColumnStoreGetIXSQL_Param, @dbid_In = @dbid, @objectid_In = @objectid, @indexid_In = @indexid, @partition_nr_In = @partition_nr;
  8671. END TRY
  8672. BEGIN CATCH
  8673. 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)) + ')'
  8674. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8675. END CATCH
  8676. UPDATE #tblWorking
  8677. SET is_done = 1
  8678. WHERE database_id = @dbid AND [object_id] = @objectid AND index_id = @indexid AND partition_number = @partition_nr
  8679. END
  8680. END;
  8681. -- Check for index fragmentation over 5 pct when index has more than 1 extent allocated, or in CCI, all compressed row groups
  8682. IF (SELECT COUNT(*) FROM #tmpIPS WHERE fragmentation > 5 AND [page_count] > 8) > 0
  8683. OR (SELECT COUNT(*) FROM #tmpIPS_CI WHERE fragmentation > 5 AND [state] = 3) > 0
  8684. BEGIN
  8685. 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]
  8686. 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,
  8687. ips.page_count, ips.[size_MB], ips.record_count, ips.forwarded_record_count, -- for heaps
  8688. NULL AS row_group_id, NULL AS [Comment]
  8689. FROM #tmpIPS ips
  8690. 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
  8691. WHERE ips.fragmentation > 5 AND ips.[page_count] > 8
  8692. UNION ALL
  8693. 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,
  8694. ipsci.page_count, ipsci.[size_MB], ipsci.record_count, NULL AS forwarded_record_count, ipsci.row_group_id,
  8695. '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]
  8696. FROM #tmpIPS_CI ipsci
  8697. 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
  8698. WHERE ipsci.fragmentation > 5 AND ipsci.[state] = 3
  8699. ORDER BY fragmentation DESC, [page_count] ASC
  8700. END
  8701. ELSE
  8702. BEGIN
  8703. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Fragmentation' AS [Check], '[OK]' AS [Deviation]
  8704. END;
  8705. IF @sqlmajorver >= 12
  8706. BEGIN
  8707. -- For the below values, your mileage may vary. Assuming more than 50 percent empty buckets and an average chain length over 5 requires investigation
  8708. -- http://blogs.technet.com/b/dataplatforminsider/archive/2014/01/30/in-memory-oltp-index-troubleshooting-part-ii.aspx
  8709. IF (SELECT COUNT(*) FROM #tmpXIS WHERE FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) > 50 AND [avg_chain_length] > 5) > 0
  8710. BEGIN
  8711. 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]
  8712. 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,
  8713. DistinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8714. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8715. FROM #tmpXIS
  8716. WHERE FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) > 50 AND [avg_chain_length] > 5
  8717. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8718. END
  8719. ELSE
  8720. BEGIN
  8721. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_AvgChain_EmptyBuckets' AS [Check], '[OK]' AS [Deviation]
  8722. END;
  8723. IF (SELECT COUNT(*) FROM #tmpXIS WHERE total_bucket_count > DistinctCnt) > 0
  8724. BEGIN
  8725. 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]
  8726. 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,
  8727. DistinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8728. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8729. FROM #tmpXIS
  8730. WHERE total_bucket_count > DistinctCnt
  8731. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8732. END
  8733. ELSE
  8734. BEGIN
  8735. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooManyBuckets' AS [Check], '[OK]' AS [Deviation]
  8736. END;
  8737. IF (SELECT COUNT(*) FROM #tmpXIS WHERE total_bucket_count < DistinctCnt) > 0
  8738. BEGIN
  8739. 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]
  8740. 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,
  8741. DistinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8742. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8743. FROM #tmpXIS
  8744. WHERE total_bucket_count < DistinctCnt
  8745. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8746. END
  8747. ELSE
  8748. BEGIN
  8749. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooFewBuckets' AS [Check], '[OK]' AS [Deviation]
  8750. END;
  8751. -- For the below values, your mileage may vary. Assuming more than 5 percent retries requires investigation .
  8752. -- https://msdn.microsoft.com/en-us/library/dn645468.aspx
  8753. 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
  8754. OR FLOOR((CAST(page_consolidation_retry_count AS FLOAT)/CASE WHEN page_consolidation_count = 0 THEN 1 ELSE page_consolidation_count END) * 100) > 5
  8755. OR FLOOR((CAST(page_split_retry_count AS FLOAT)/CASE WHEN page_split_count = 0 THEN 1 ELSE page_split_count END) * 100) > 5
  8756. OR FLOOR((CAST(key_split_retry_count AS FLOAT)/CASE WHEN key_split_count = 0 THEN 1 ELSE key_split_count END) * 100) > 5
  8757. OR FLOOR((CAST(page_merge_retry_count AS FLOAT)/CASE WHEN page_merge_count = 0 THEN 1 ELSE page_merge_count END) * 100) > 5
  8758. OR FLOOR((CAST(key_merge_retry_count AS FLOAT)/CASE WHEN key_merge_count = 0 THEN 1 ELSE key_merge_count END) * 100) > 5
  8759. ) > 0
  8760. BEGIN
  8761. 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]
  8762. 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,
  8763. delta_pages, internal_pages, leaf_pages,
  8764. 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],
  8765. 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],
  8766. 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],
  8767. 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],
  8768. 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],
  8769. 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]
  8770. FROM #tmpXNCIS
  8771. WHERE FLOOR((CAST(page_update_retry_count AS FLOAT)/CASE WHEN page_update_count = 0 THEN 1 ELSE page_update_count END) * 100) > 5
  8772. OR FLOOR((CAST(page_consolidation_retry_count AS FLOAT)/CASE WHEN page_consolidation_count = 0 THEN 1 ELSE page_consolidation_count END) * 100) > 5
  8773. OR FLOOR((CAST(page_split_retry_count AS FLOAT)/CASE WHEN page_split_count = 0 THEN 1 ELSE page_split_count END) * 100) > 5
  8774. OR FLOOR((CAST(key_split_retry_count AS FLOAT)/CASE WHEN key_split_count = 0 THEN 1 ELSE key_split_count END) * 100) > 5
  8775. OR FLOOR((CAST(page_merge_retry_count AS FLOAT)/CASE WHEN page_merge_count = 0 THEN 1 ELSE page_merge_count END) * 100) > 5
  8776. OR FLOOR((CAST(key_merge_retry_count AS FLOAT)/CASE WHEN key_merge_count = 0 THEN 1 ELSE key_merge_count END) * 100) > 5
  8777. ORDER BY [database_name], [schema_name], table_name, [leaf_pages] DESC;
  8778. END;
  8779. END;
  8780. END
  8781. ELSE
  8782. BEGIN
  8783. RAISERROR(' |- [INFORMATION: "Index Health Analysis" check is disabled]', 10, 1, N'disallow_ixfrag')
  8784. --RETURN
  8785. END;
  8786. --------------------------------------------------------------------------------------------------------------------------------
  8787. -- Duplicate or Redundant indexes subsection (clustered, non-clustered, clustered and non-clustered columnstore indexes only)
  8788. --------------------------------------------------------------------------------------------------------------------------------
  8789. IF @ptochecks = 1
  8790. BEGIN
  8791. RAISERROR (N' |-Starting Duplicate or Redundant indexes', 10, 1) WITH NOWAIT
  8792. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  8793. DROP TABLE #tblIxs1;
  8794. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  8795. CREATE TABLE #tblIxs1 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  8796. [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),
  8797. KeyCols VARCHAR(4000), KeyColsOrdered VARCHAR(4000), IncludedCols VARCHAR(4000) NULL, IncludedColsOrdered VARCHAR(4000) NULL, AllColsOrdered VARCHAR(4000) NULL, [KeyCols_data_length_bytes] int,
  8798. CONSTRAINT PK_Ixs PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]));
  8799. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  8800. DROP TABLE #tblCode;
  8801. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  8802. CREATE TABLE #tblCode ([DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [indexName] VARCHAR(200), type_desc NVARCHAR(60));
  8803. UPDATE #tmpdbs1
  8804. SET isdone = 0;
  8805. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  8806. BEGIN
  8807. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  8808. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8809. USE ' + QUOTENAME(@dbname) + ';
  8810. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  8811. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, mi.index_id AS indexID,
  8812. mi.[name] AS Index_Name, mi.[type] AS [indexType], mi.is_primary_key, mi.[is_unique_constraint], mi.is_unique, mi.is_disabled,
  8813. mi.fill_factor, mi.is_padded, ' + CASE WHEN @sqlmajorver > 9 THEN 'mi.has_filter, mi.filter_definition,' ELSE 'NULL, NULL,' END + '
  8814. SUBSTRING(( SELECT '','' + ac.name FROM sys.tables AS st
  8815. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8816. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8817. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8818. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  8819. ORDER BY ic.key_ordinal
  8820. FOR XML PATH('''')), 2, 8000) AS KeyCols,
  8821. SUBSTRING(( SELECT '','' + ac.name FROM sys.tables AS st
  8822. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8823. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8824. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8825. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  8826. ORDER BY ac.name
  8827. FOR XML PATH('''')), 2, 8000) AS KeyColsOrdered,
  8828. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8829. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8830. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8831. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8832. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 1
  8833. ORDER BY ic.key_ordinal
  8834. FOR XML PATH('''')), 2, 8000) AS IncludedCols,
  8835. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8836. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8837. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8838. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8839. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 1
  8840. ORDER BY ac.name
  8841. FOR XML PATH('''')), 2, 8000) AS IncludedColsOrdered,
  8842. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8843. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8844. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8845. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8846. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id
  8847. ORDER BY ac.name
  8848. FOR XML PATH('''')), 2, 8000) AS AllColsOrdered,
  8849. (SELECT SUM(CASE sty.name WHEN ''nvarchar'' THEN sc.max_length/2 ELSE sc.max_length END) FROM sys.indexes AS i
  8850. INNER JOIN sys.tables AS t ON t.[object_id] = i.[object_id]
  8851. INNER JOIN sys.schemas ss ON ss.[schema_id] = t.[schema_id]
  8852. INNER JOIN sys.index_columns AS sic ON sic.object_id = mst.object_id AND sic.index_id = mi.index_id
  8853. INNER JOIN sys.columns AS sc ON sc.object_id = t.object_id AND sc.column_id = sic.column_id
  8854. INNER JOIN sys.types AS sty ON sc.user_type_id = sty.user_type_id
  8855. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND sic.key_ordinal > 0) AS [KeyCols_data_length_bytes]
  8856. FROM sys.indexes AS mi
  8857. INNER JOIN sys.tables AS mst ON mst.[object_id] = mi.[object_id]
  8858. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8859. WHERE mi.type IN (1,2,5,6) AND mst.is_ms_shipped = 0
  8860. ORDER BY objectName
  8861. OPTION (MAXDOP 2);'
  8862. BEGIN TRY
  8863. INSERT INTO #tblIxs1
  8864. EXECUTE sp_executesql @sqlcmd
  8865. END TRY
  8866. BEGIN CATCH
  8867. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8868. SELECT @ErrorMessage = 'Duplicate or Redundant indexes subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8869. RAISERROR (@ErrorMessage, 16, 1);
  8870. END CATCH
  8871. UPDATE #tmpdbs1
  8872. SET isdone = 1
  8873. WHERE [dbid] = @dbid;
  8874. END
  8875. 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]
  8876. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8877. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))) > 0
  8878. BEGIN
  8879. 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]
  8880. 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],
  8881. 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,
  8882. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  8883. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8884. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8885. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8886. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8887. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8888. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8889. 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
  8890. ORDER BY I.DatabaseName, I.[objectName], I.[indexID]
  8891. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes_toDrop' AS [Check], I.[DatabaseName], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name],
  8892. 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,
  8893. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  8894. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8895. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8896. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8897. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8898. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8899. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8900. AND I.[indexID] NOT IN (
  8901. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8902. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8903. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8904. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8905. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8906. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8907. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8908. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8909. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8910. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8911. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8912. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8913. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8914. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8915. ))
  8916. 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
  8917. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8918. DECLARE @strSQL2 NVARCHAR(4000), @DatabaseName sysname, @indexName sysname
  8919. IF @gen_scripts = 1
  8920. BEGIN
  8921. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8922. PRINT CHAR(10) + '/*
  8923. 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.
  8924. 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.
  8925. */'
  8926. PRINT CHAR(10) + '--############# Existing Duplicate indexes drop statements #############' + CHAR(10)
  8927. 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) +
  8928. 'DROP INDEX ' + QUOTENAME(I.[indexName]) + ' ON ' + QUOTENAME(I.[schemaName]) + '.' + QUOTENAME(I.[objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  8929. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8930. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8931. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8932. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8933. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8934. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8935. AND I.[indexID] NOT IN (
  8936. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8937. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8938. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8939. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8940. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8941. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8942. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8943. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8944. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8945. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8946. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8947. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8948. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8949. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8950. ))
  8951. GROUP BY I.[databaseID], I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered
  8952. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8953. OPEN Dup_Stats
  8954. FETCH NEXT FROM Dup_Stats INTO @strSQL2
  8955. WHILE (@@FETCH_STATUS = 0)
  8956. BEGIN
  8957. PRINT @strSQL2
  8958. FETCH NEXT FROM Dup_Stats INTO @strSQL2
  8959. END
  8960. CLOSE Dup_Stats
  8961. DEALLOCATE Dup_Stats
  8962. PRINT '--############# Ended Duplicate indexes drop statements #############' + CHAR(10)
  8963. END;
  8964. RAISERROR (N' |-Starting index search in sql modules...', 10, 1) WITH NOWAIT
  8965. DECLARE Dup_HardCoded CURSOR FAST_FORWARD FOR SELECT I.[DatabaseName],I.[indexName]
  8966. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8967. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8968. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8969. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8970. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8971. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8972. AND I.[indexID] NOT IN (
  8973. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8974. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8975. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8976. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8977. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8978. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8979. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8980. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8981. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8982. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8983. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8984. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8985. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8986. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8987. ))
  8988. GROUP BY I.[databaseID], I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered
  8989. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8990. OPEN Dup_HardCoded
  8991. FETCH NEXT FROM Dup_HardCoded INTO @DatabaseName,@indexName
  8992. WHILE (@@FETCH_STATUS = 0)
  8993. BEGIN
  8994. SET @sqlcmd = 'USE [' + @DatabaseName + '];
  8995. SELECT ''' + @DatabaseName + ''' AS [database], ss.name AS [schemaName], so.name AS [objectName], ''' + @indexName + ''' AS indexName, so.type_desc
  8996. FROM sys.sql_modules sm
  8997. INNER JOIN sys.objects so ON sm.[object_id] = so.[object_id]
  8998. INNER JOIN sys.schemas ss ON ss.[schema_id] = so.[schema_id]
  8999. WHERE sm.[definition] LIKE ''%' + @indexName + '%'''
  9000. INSERT INTO #tblCode
  9001. EXECUTE sp_executesql @sqlcmd
  9002. FETCH NEXT FROM Dup_HardCoded INTO @DatabaseName,@indexName
  9003. END
  9004. CLOSE Dup_HardCoded
  9005. DEALLOCATE Dup_HardCoded
  9006. RAISERROR (N' |-Ended index search in sql modules', 10, 1) WITH NOWAIT
  9007. IF (SELECT COUNT(*) FROM #tblCode) > 0
  9008. BEGIN
  9009. 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]
  9010. SELECT [DatabaseName],[schemaName],[objectName] AS [referedIn_objectName], indexName AS [referenced_indexName], type_desc AS [refered_objectType]
  9011. FROM #tblCode
  9012. ORDER BY [DatabaseName], [objectName]
  9013. END
  9014. ELSE
  9015. BEGIN
  9016. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes_HardCoded' AS [Check], '[OK]' AS [Deviation]
  9017. END
  9018. END
  9019. ELSE
  9020. BEGIN
  9021. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes' AS [Check], '[OK]' AS [Deviation]
  9022. END;
  9023. 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]
  9024. AND (I.[KeyCols] <> I2.[KeyCols] OR I.IncludedCols <> I2.IncludedCols)
  9025. AND (((I.[KeyColsOrdered] <> I2.[KeyColsOrdered] OR I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9026. 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)
  9027. OR I.[AllColsOrdered] = I2.[AllColsOrdered]))
  9028. OR (I.[KeyColsOrdered] <> I2.[KeyColsOrdered] AND I.IncludedColsOrdered = I2.IncludedColsOrdered)
  9029. OR (I.[KeyColsOrdered] = I2.[KeyColsOrdered] AND I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9030. 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)))
  9031. AND I.indexID NOT IN (SELECT I3.[indexID]
  9032. FROM #tblIxs1 I3 INNER JOIN #tblIxs1 I4
  9033. ON I3.[databaseID] = I4.[databaseID] AND I3.[objectID] = I4.[objectID] AND I3.[indexID] <> I4.[indexID]
  9034. AND I3.[KeyCols] = I4.[KeyCols] AND (I3.IncludedCols = I4.IncludedCols OR (I3.IncludedCols IS NULL AND I4.IncludedCols IS NULL))
  9035. WHERE I3.[databaseID] = I.[databaseID] AND I3.[objectID] = I.[objectID]
  9036. GROUP BY I3.[indexID])
  9037. WHERE I.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9038. AND I2.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9039. AND I.is_unique_constraint = 0 -- no unique constraints
  9040. AND I2.is_unique_constraint = 0 -- no unique constraints
  9041. ) > 0
  9042. BEGIN
  9043. 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]
  9044. 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],
  9045. I.[indexID], I.[indexName] AS [Index_Name], I.is_unique, I.fill_factor, I.is_padded, I.has_filter, I.filter_definition,
  9046. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedColsOrdered IS NULL THEN I.[KeyColsOrdered] ELSE I.[KeyColsOrdered] + ',' + I.IncludedColsOrdered END AS [KeyInclColsOrdered]
  9047. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  9048. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  9049. AND (((I.[KeyColsOrdered] <> I2.[KeyColsOrdered] OR I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9050. 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)
  9051. OR I.[AllColsOrdered] = I2.[AllColsOrdered]))
  9052. OR (I.[KeyColsOrdered] <> I2.[KeyColsOrdered] AND I.IncludedColsOrdered = I2.IncludedColsOrdered)
  9053. OR (I.[KeyColsOrdered] = I2.[KeyColsOrdered] AND I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9054. 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)))
  9055. AND I.indexID NOT IN (SELECT I3.[indexID]
  9056. FROM #tblIxs1 I3 INNER JOIN #tblIxs1 I4
  9057. ON I3.[databaseID] = I4.[databaseID] AND I3.[objectID] = I4.[objectID] AND I3.[indexID] <> I4.[indexID]
  9058. AND I3.[KeyCols] = I4.[KeyCols] AND (I3.IncludedCols = I4.IncludedCols OR (I3.IncludedCols IS NULL AND I4.IncludedCols IS NULL))
  9059. WHERE I3.[databaseID] = I.[databaseID] AND I3.[objectID] = I.[objectID]
  9060. GROUP BY I3.[indexID])
  9061. WHERE I.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9062. AND I2.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9063. AND I.is_unique_constraint = 0 -- no unique constraints
  9064. AND I2.is_unique_constraint = 0 -- no unique constraints
  9065. 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
  9066. ORDER BY I.DatabaseName, I.[objectName], I.[KeyColsOrdered], I.IncludedColsOrdered, I.[indexID]
  9067. END
  9068. ELSE
  9069. BEGIN
  9070. SELECT 'Index_and_Stats_checks' AS [Category], 'Redundant_Indexes' AS [Check], '[OK]' AS [Deviation]
  9071. END;
  9072. END;
  9073. --------------------------------------------------------------------------------------------------------------------------------
  9074. -- Unused and rarely used indexes subsection
  9075. --------------------------------------------------------------------------------------------------------------------------------
  9076. IF @ptochecks = 1
  9077. BEGIN
  9078. RAISERROR (N' |-Starting Unused and rarely used indexes', 10, 1) WITH NOWAIT
  9079. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  9080. DROP TABLE #tblIxs2;
  9081. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  9082. CREATE TABLE #tblIxs2 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  9083. [indexID] int, [indexName] VARCHAR(200), [Hits] bigint NULL, [Reads_Ratio] DECIMAL(5,2), [Writes_Ratio] DECIMAL(5,2),
  9084. user_updates bigint, last_user_seek DATETIME NULL, last_user_scan DATETIME NULL, last_user_lookup DATETIME NULL,
  9085. last_user_update DATETIME NULL, is_unique bit, [type] tinyint, is_primary_key bit, is_unique_constraint bit, is_disabled bit,
  9086. CONSTRAINT PK_Ixs2 PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]))
  9087. UPDATE #tmpdbs1
  9088. SET isdone = 0;
  9089. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9090. BEGIN
  9091. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9092. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9093. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9094. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, si.index_id AS indexID, si.[name] AS Index_Name,
  9095. (s.user_seeks + s.user_scans + s.user_lookups) AS [Hits],
  9096. 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 /
  9097. 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],
  9098. RTRIM(CONVERT(NVARCHAR(10),CAST(CASE WHEN s.user_updates = 0 THEN 0 ELSE CONVERT(REAL, s.user_updates) * 100 /
  9099. 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],
  9100. s.user_updates,
  9101. MAX(s.last_user_seek) AS last_user_seek,
  9102. MAX(s.last_user_scan) AS last_user_scan,
  9103. MAX(s.last_user_lookup) AS last_user_lookup,
  9104. MAX(s.last_user_update) AS last_user_update,
  9105. si.is_unique, si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9106. FROM sys.indexes AS si (NOLOCK)
  9107. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  9108. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = si.[object_id]
  9109. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9110. INNER JOIN sys.dm_db_index_usage_stats AS s (NOLOCK) ON s.database_id = ' + CONVERT(VARCHAR(8), @dbid) + '
  9111. AND s.object_id = si.object_id AND s.index_id = si.index_id
  9112. WHERE mst.is_ms_shipped = 0
  9113. --AND OBJECTPROPERTY(o.object_id,''IsUserTable'') = 1 -- sys.tables only returns type U
  9114. AND si.type IN (2,6) -- non-clustered and non-clustered columnstore indexes only
  9115. AND si.is_primary_key = 0 -- no primary keys
  9116. AND si.is_unique_constraint = 0 -- no unique constraints
  9117. --AND si.is_unique = 0 -- no alternate keys
  9118. 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,
  9119. si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9120. ORDER BY objectName
  9121. OPTION (MAXDOP 2);'
  9122. BEGIN TRY
  9123. INSERT INTO #tblIxs2
  9124. EXECUTE sp_executesql @sqlcmd
  9125. END TRY
  9126. BEGIN CATCH
  9127. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9128. SELECT @ErrorMessage = 'Unused and rarely used indexes subsection - Error raised in TRY block 1 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9129. RAISERROR (@ErrorMessage, 16, 1);
  9130. END CATCH
  9131. UPDATE #tmpdbs1
  9132. SET isdone = 1
  9133. WHERE [dbid] = @dbid
  9134. END
  9135. UPDATE #tmpdbs1
  9136. SET isdone = 0;
  9137. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9138. BEGIN
  9139. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9140. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9141. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9142. 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,
  9143. si.[name] AS Index_Name, 0, 0, 0, 0, NULL, NULL, NULL, NULL,
  9144. si.is_unique, si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9145. FROM sys.indexes AS si (NOLOCK)
  9146. INNER JOIN sys.objects AS so (NOLOCK) ON si.object_id = so.object_id
  9147. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = si.[object_id]
  9148. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9149. WHERE OBJECTPROPERTY(so.object_id,''IsUserTable'') = 1
  9150. AND mst.is_ms_shipped = 0
  9151. AND si.index_id NOT IN (SELECT s.index_id
  9152. FROM sys.dm_db_index_usage_stats s
  9153. WHERE s.object_id = si.object_id
  9154. AND si.index_id = s.index_id
  9155. AND database_id = ' + CONVERT(VARCHAR(8), @dbid) + ')
  9156. AND si.name IS NOT NULL
  9157. AND si.type IN (2,6) -- non-clustered and non-clustered columnstore indexes only
  9158. AND si.is_primary_key = 0 -- no primary keys
  9159. AND si.is_unique_constraint = 0 -- no unique constraints
  9160. --AND si.is_unique = 0 -- no alternate keys
  9161. '
  9162. BEGIN TRY
  9163. INSERT INTO #tblIxs2
  9164. EXECUTE sp_executesql @sqlcmd
  9165. END TRY
  9166. BEGIN CATCH
  9167. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9168. SELECT @ErrorMessage = 'Unused and rarely used indexes subsection - Error raised in TRY block 2 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9169. RAISERROR (@ErrorMessage, 16, 1);
  9170. END CATCH
  9171. UPDATE #tmpdbs1
  9172. SET isdone = 1
  9173. WHERE [dbid] = @dbid
  9174. END;
  9175. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 /*AND is_disabled = 0*/) > 0
  9176. BEGIN
  9177. 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]
  9178. 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,
  9179. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9180. user_updates, last_user_update
  9181. FROM #tblIxs2
  9182. WHERE [Hits] = 0 AND last_user_update > 0
  9183. UNION ALL
  9184. 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,
  9185. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9186. user_updates, last_user_update
  9187. FROM #tblIxs2
  9188. WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)
  9189. ORDER BY [Information], [Database_Name], [Table_Name], [R/W_Ratio] DESC;
  9190. IF @gen_scripts = 1
  9191. BEGIN
  9192. DECLARE @strSQL3 NVARCHAR(4000)
  9193. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9194. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 AND last_user_update > 0) > 0
  9195. BEGIN
  9196. PRINT CHAR(10) + '--############# Existing unused indexes with updates drop statements #############' + CHAR(10)
  9197. 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) +
  9198. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9199. FROM #tblIxs2
  9200. WHERE [Hits] = 0 AND last_user_update > 0
  9201. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC;
  9202. OPEN Un_Stats
  9203. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9204. WHILE (@@FETCH_STATUS = 0)
  9205. BEGIN
  9206. PRINT @strSQL3
  9207. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9208. END
  9209. CLOSE Un_Stats
  9210. DEALLOCATE Un_Stats
  9211. PRINT CHAR(10) + '--############# Ended unused indexes with updates drop statements #############' + CHAR(10)
  9212. END;
  9213. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)) > 0
  9214. BEGIN
  9215. PRINT CHAR(10) + '--############# Existing unused indexes with no updates drop statements #############' + CHAR(10)
  9216. 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) +
  9217. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9218. FROM #tblIxs2
  9219. WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)
  9220. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC;
  9221. OPEN Un_Stats
  9222. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9223. WHILE (@@FETCH_STATUS = 0)
  9224. BEGIN
  9225. PRINT @strSQL3
  9226. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9227. END
  9228. CLOSE Un_Stats
  9229. DEALLOCATE Un_Stats
  9230. PRINT CHAR(10) + '--############# Ended unused indexes with no updates drop statements #############' + CHAR(10)
  9231. END
  9232. END;
  9233. END
  9234. ELSE
  9235. BEGIN
  9236. SELECT 'Index_and_Stats_checks' AS [Category], 'Unused_Indexes' AS [Check], '[OK]' AS [Deviation]
  9237. END;
  9238. 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
  9239. BEGIN
  9240. 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]
  9241. 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,
  9242. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9243. user_updates, last_user_seek, last_user_scan, last_user_lookup, last_user_update
  9244. FROM #tblIxs2
  9245. WHERE [Hits] > 0 AND [Reads_Ratio] < 5
  9246. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC
  9247. IF @gen_scripts = 1
  9248. BEGIN
  9249. DECLARE @strSQL4 NVARCHAR(4000)
  9250. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9251. PRINT CHAR(10) + '--############# Existing rarely used indexes drop statements #############' + CHAR(10)
  9252. 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) +
  9253. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9254. FROM #tblIxs2
  9255. WHERE [Hits] > 0 AND [Reads_Ratio] < 5
  9256. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC
  9257. OPEN curRarUsed
  9258. FETCH NEXT FROM curRarUsed INTO @strSQL4
  9259. WHILE (@@FETCH_STATUS = 0)
  9260. BEGIN
  9261. PRINT @strSQL4
  9262. FETCH NEXT FROM curRarUsed INTO @strSQL4
  9263. END
  9264. CLOSE curRarUsed
  9265. DEALLOCATE curRarUsed
  9266. PRINT '--############# Ended rarely used indexes drop statements #############' + CHAR(10)
  9267. END;
  9268. END
  9269. ELSE
  9270. BEGIN
  9271. SELECT 'Index_and_Stats_checks' AS [Category], 'Rarely_Used_Indexes' AS [Check], '[OK]' AS [Deviation]
  9272. END;
  9273. END;
  9274. --------------------------------------------------------------------------------------------------------------------------------
  9275. -- Indexes with large keys (> 900 bytes) subsection
  9276. --------------------------------------------------------------------------------------------------------------------------------
  9277. IF @ptochecks = 1
  9278. BEGIN
  9279. RAISERROR (N' |-Starting Indexes with large keys (> 900 bytes)', 10, 1) WITH NOWAIT
  9280. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [KeyCols_data_length_bytes] > 900) > 0
  9281. BEGIN
  9282. 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]
  9283. 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],
  9284. I.KeyCols, [KeyCols_data_length_bytes]
  9285. FROM #tblIxs1 I
  9286. WHERE [KeyCols_data_length_bytes] > 900
  9287. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9288. END
  9289. ELSE
  9290. BEGIN
  9291. SELECT 'Index_and_Stats_checks' AS [Category], 'Large_Index_Key' AS [Check], '[OK]' AS [Deviation]
  9292. END;
  9293. END;
  9294. --------------------------------------------------------------------------------------------------------------------------------
  9295. -- Indexes with fill factor < 80 pct subsection
  9296. --------------------------------------------------------------------------------------------------------------------------------
  9297. IF @ptochecks = 1
  9298. BEGIN
  9299. RAISERROR (N' |-Starting Indexes with fill factor < 80 pct', 10, 1) WITH NOWAIT
  9300. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [fill_factor] BETWEEN 1 AND 79) > 0
  9301. BEGIN
  9302. 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]
  9303. 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],
  9304. [fill_factor], I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  9305. FROM #tblIxs1 I
  9306. WHERE [fill_factor] BETWEEN 1 AND 79
  9307. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9308. END
  9309. ELSE
  9310. BEGIN
  9311. SELECT 'Index_and_Stats_checks' AS [Category], 'Low_Fill_Factor' AS [Check], '[OK]' AS [Deviation]
  9312. END;
  9313. END;
  9314. --------------------------------------------------------------------------------------------------------------------------------
  9315. -- Disabled indexes subsection
  9316. --------------------------------------------------------------------------------------------------------------------------------
  9317. IF @ptochecks = 1
  9318. BEGIN
  9319. RAISERROR (N' |-Starting Disabled indexes', 10, 1) WITH NOWAIT
  9320. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [is_disabled] = 1) > 0
  9321. BEGIN
  9322. SELECT 'Index_and_Stats_checks' AS [Category], 'Disabled_IXs' AS [Check], '[WARNING: Some indexes are disabled. Revise the need to maintain these]' AS [Deviation]
  9323. 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],
  9324. CASE WHEN [indexType] = 1 THEN 'Clustered'
  9325. WHEN [indexType] = 2 THEN 'Non-clustered'
  9326. WHEN [indexType] = 3 THEN 'Clustered columnstore'
  9327. ELSE 'Non-clustered columnstore' END AS [Index_Type],
  9328. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  9329. FROM #tblIxs1 I
  9330. WHERE [is_disabled] = 1
  9331. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9332. END
  9333. ELSE
  9334. BEGIN
  9335. SELECT 'Index_and_Stats_checks' AS [Category], 'Disabled_IXs' AS [Check], '[OK]' AS [Deviation]
  9336. END;
  9337. END;
  9338. --------------------------------------------------------------------------------------------------------------------------------
  9339. -- Non-unique clustered indexes subsection
  9340. --------------------------------------------------------------------------------------------------------------------------------
  9341. IF @ptochecks = 1
  9342. BEGIN
  9343. RAISERROR (N' |-Starting Non-unique clustered indexes', 10, 1) WITH NOWAIT
  9344. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [is_unique] = 0 AND indexID = 1) > 0
  9345. BEGIN
  9346. 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]
  9347. 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]
  9348. FROM #tblIxs1 I
  9349. WHERE [is_unique] = 0 AND indexID = 1
  9350. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName]
  9351. END
  9352. ELSE
  9353. BEGIN
  9354. SELECT 'Index_and_Stats_checks' AS [Category], 'NonUnique_CIXs' AS [Check], '[OK]' AS [Deviation]
  9355. END;
  9356. END;
  9357. --------------------------------------------------------------------------------------------------------------------------------
  9358. -- Clustered Indexes with GUIDs in key subsection
  9359. --------------------------------------------------------------------------------------------------------------------------------
  9360. IF @ptochecks = 1
  9361. BEGIN
  9362. RAISERROR (N' |-Starting Clustered Indexes with GUIDs in key', 10, 1) WITH NOWAIT
  9363. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  9364. DROP TABLE #tblIxs6;
  9365. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  9366. CREATE TABLE #tblIxs6 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  9367. [indexID] int, [indexName] VARCHAR(200), [indexType] tinyint, [is_unique_constraint] bit, is_unique bit, is_disabled bit, fill_factor tinyint, is_padded bit,
  9368. KeyCols VARCHAR(4000), KeyColsOrdered VARCHAR(4000), Key_has_GUID int,
  9369. CONSTRAINT PK_Ixs3 PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]));
  9370. UPDATE #tmpdbs1
  9371. SET isdone = 0;
  9372. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9373. BEGIN
  9374. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9375. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  9376. USE ' + QUOTENAME(@dbname) + ';
  9377. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9378. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, mi.index_id AS indexID,
  9379. mi.[name] AS Index_Name, mi.[type] AS [indexType], mi.[is_unique_constraint], mi.is_unique, mi.is_disabled,
  9380. mi.fill_factor, mi.is_padded,
  9381. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  9382. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  9383. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  9384. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9385. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  9386. ORDER BY ic.key_ordinal
  9387. FOR XML PATH('''')), 2, 8000) AS KeyCols,
  9388. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  9389. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  9390. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  9391. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9392. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  9393. ORDER BY ac.name
  9394. FOR XML PATH('''')), 2, 8000) AS KeyColsOrdered,
  9395. (SELECT COUNT(sty.name) FROM sys.indexes AS i
  9396. INNER JOIN sys.tables AS t ON t.[object_id] = i.[object_id]
  9397. INNER JOIN sys.schemas ss ON ss.[schema_id] = t.[schema_id]
  9398. INNER JOIN sys.index_columns AS sic ON sic.object_id = mst.object_id AND sic.index_id = mi.index_id
  9399. INNER JOIN sys.columns AS sc ON sc.object_id = t.object_id AND sc.column_id = sic.column_id
  9400. INNER JOIN sys.types AS sty ON sc.user_type_id = sty.user_type_id
  9401. 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]
  9402. FROM sys.indexes AS mi
  9403. INNER JOIN sys.tables AS mst ON mst.[object_id] = mi.[object_id]
  9404. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  9405. WHERE mi.type = 1 AND mi.is_unique_constraint = 0
  9406. AND mst.is_ms_shipped = 0
  9407. --AND OBJECTPROPERTY(o.object_id,''IsUserTable'') = 1 -- sys.tables only returns type U
  9408. ORDER BY objectName
  9409. OPTION (MAXDOP 2);'
  9410. BEGIN TRY
  9411. INSERT INTO #tblIxs6
  9412. EXECUTE sp_executesql @sqlcmd
  9413. END TRY
  9414. BEGIN CATCH
  9415. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9416. SELECT @ErrorMessage = 'Clustered Indexes with GUIDs in key subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9417. RAISERROR (@ErrorMessage, 16, 1);
  9418. END CATCH
  9419. UPDATE #tmpdbs1
  9420. SET isdone = 1
  9421. WHERE [dbid] = @dbid
  9422. END;
  9423. IF (SELECT COUNT(*) FROM #tblIxs6 WHERE [Key_has_GUID] > 0) > 0
  9424. BEGIN
  9425. 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]
  9426. 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
  9427. FROM #tblIxs6 I
  9428. WHERE [Key_has_GUID] > 0
  9429. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9430. END
  9431. ELSE
  9432. BEGIN
  9433. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Key_GUID' AS [Check], '[OK]' AS [Deviation]
  9434. END
  9435. END;
  9436. --------------------------------------------------------------------------------------------------------------------------------
  9437. -- Foreign Keys with no Index subsection
  9438. --------------------------------------------------------------------------------------------------------------------------------
  9439. IF @ptochecks = 1
  9440. BEGIN
  9441. RAISERROR (N' |-Starting Foreign Keys with no Index', 10, 1) WITH NOWAIT
  9442. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  9443. DROP TABLE #tblFK;
  9444. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  9445. CREATE TABLE #tblFK ([databaseID] int, [DatabaseName] sysname, [constraint_name] VARCHAR(200), [parent_schema_name] VARCHAR(100),
  9446. [parent_table_name] VARCHAR(200), parent_columns VARCHAR(4000), [referenced_schema] VARCHAR(100), [referenced_table_name] VARCHAR(200), referenced_columns VARCHAR(4000),
  9447. CONSTRAINT PK_FK PRIMARY KEY CLUSTERED(databaseID, [constraint_name]))
  9448. UPDATE #tmpdbs1
  9449. SET isdone = 0
  9450. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9451. BEGIN
  9452. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9453. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  9454. USE ' + QUOTENAME(@dbname) + '
  9455. ;WITH cteFK AS (
  9456. SELECT t.name AS [parent_schema_name],
  9457. OBJECT_NAME(FKC.parent_object_id) [parent_table_name],
  9458. OBJECT_NAME(constraint_object_id) AS [constraint_name],
  9459. t2.name AS [referenced_schema],
  9460. OBJECT_NAME(referenced_object_id) AS [referenced_table_name],
  9461. SUBSTRING((SELECT '','' + RTRIM(COL_NAME(k.parent_object_id,parent_column_id)) AS [data()]
  9462. FROM sys.foreign_key_columns k (NOLOCK)
  9463. INNER JOIN sys.foreign_keys (NOLOCK) ON k.constraint_object_id = [object_id]
  9464. AND k.constraint_object_id = FKC.constraint_object_id
  9465. ORDER BY constraint_column_id
  9466. FOR XML PATH('''')), 2, 8000) AS [parent_columns],
  9467. SUBSTRING((SELECT '','' + RTRIM(COL_NAME(k.referenced_object_id,referenced_column_id)) AS [data()]
  9468. FROM sys.foreign_key_columns k (NOLOCK)
  9469. INNER JOIN sys.foreign_keys (NOLOCK) ON k.constraint_object_id = [object_id]
  9470. AND k.constraint_object_id = FKC.constraint_object_id
  9471. ORDER BY constraint_column_id
  9472. FOR XML PATH('''')), 2, 8000) AS [referenced_columns]
  9473. FROM sys.foreign_key_columns FKC (NOLOCK)
  9474. INNER JOIN sys.objects o (NOLOCK) ON FKC.parent_object_id = o.[object_id]
  9475. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  9476. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9477. INNER JOIN sys.objects so (NOLOCK) ON FKC.referenced_object_id = so.[object_id]
  9478. INNER JOIN sys.tables AS mst2 (NOLOCK) ON mst2.[object_id] = so.[object_id]
  9479. INNER JOIN sys.schemas AS t2 (NOLOCK) ON t2.[schema_id] = mst2.[schema_id]
  9480. WHERE o.type = ''U'' AND so.type = ''U''
  9481. GROUP BY o.[schema_id],so.[schema_id],FKC.parent_object_id,constraint_object_id,referenced_object_id,t.name,t2.name
  9482. ),
  9483. cteIndexCols AS (
  9484. SELECT t.name AS schemaName,
  9485. OBJECT_NAME(mst.[object_id]) AS objectName,
  9486. SUBSTRING(( SELECT '','' + RTRIM(ac.name) FROM sys.tables AS st
  9487. INNER JOIN sys.indexes AS mi ON st.[object_id] = mi.[object_id]
  9488. INNER JOIN sys.index_columns AS ic ON mi.[object_id] = ic.[object_id] AND mi.[index_id] = ic.[index_id]
  9489. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9490. WHERE i.[object_id] = mi.[object_id] AND i.index_id = mi.index_id AND ic.is_included_column = 0
  9491. ORDER BY ac.column_id
  9492. FOR XML PATH('''')), 2, 8000) AS KeyCols
  9493. FROM sys.indexes AS i
  9494. INNER JOIN sys.tables AS mst ON mst.[object_id] = i.[object_id]
  9495. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  9496. WHERE i.[type] IN (1,2,5,6) AND i.is_unique_constraint = 0
  9497. AND mst.is_ms_shipped = 0
  9498. )
  9499. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name, fk.constraint_name AS constraintName,
  9500. fk.parent_schema_name AS schemaName, fk.parent_table_name AS tableName,
  9501. REPLACE(fk.parent_columns,'' ,'','','') AS parentColumns, fk.referenced_schema AS referencedSchemaName,
  9502. fk.referenced_table_name AS referencedTableName, REPLACE(fk.referenced_columns,'' ,'','','') AS referencedColumns
  9503. FROM cteFK fk
  9504. WHERE NOT EXISTS (SELECT 1 FROM cteIndexCols ict
  9505. WHERE fk.parent_schema_name = ict.schemaName
  9506. AND fk.parent_table_name = ict.objectName
  9507. AND REPLACE(fk.parent_columns,'' ,'','','') = ict.KeyCols);'
  9508. BEGIN TRY
  9509. INSERT INTO #tblFK
  9510. EXECUTE sp_executesql @sqlcmd
  9511. END TRY
  9512. BEGIN CATCH
  9513. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9514. SELECT @ErrorMessage = 'Foreign Keys with no Index subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9515. RAISERROR (@ErrorMessage, 16, 1);
  9516. END CATCH
  9517. UPDATE #tmpdbs1
  9518. SET isdone = 1
  9519. WHERE [dbid] = @dbid
  9520. END;
  9521. IF (SELECT COUNT(*) FROM #tblFK) > 0
  9522. BEGIN
  9523. 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]
  9524. SELECT 'Index_and_Stats_checks' AS [Category], 'FK_no_Index' AS [Information], FK.[DatabaseName] AS [Database_Name], constraint_name AS [Constraint_Name],
  9525. FK.parent_schema_name AS [Schema_Name], FK.parent_table_name AS [Table_Name],
  9526. FK.parent_columns AS parentColumns, FK.referenced_schema AS Referenced_Schema_Name,
  9527. FK.referenced_table_name AS Referenced_Table_Name, FK.referenced_columns AS referencedColumns
  9528. FROM #tblFK FK
  9529. ORDER BY [DatabaseName], parent_schema_name, parent_table_name, referenced_schema, referenced_table_name
  9530. IF @gen_scripts = 1
  9531. BEGIN
  9532. DECLARE @strSQL5 NVARCHAR(4000)
  9533. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9534. PRINT CHAR(10) + '--############# FK index creation statements #############' + CHAR(10)
  9535. DECLARE curFKs CURSOR FAST_FORWARD FOR SELECT 'USE ' + [DatabaseName] + CHAR(10) + 'GO' + CHAR(10) +
  9536. 'CREATE INDEX IX_' + REPLACE(constraint_name,' ','_') + ' ON ' + QUOTENAME(parent_schema_name) + '.' + QUOTENAME(parent_table_name) + ' ([' + REPLACE(REPLACE(parent_columns,',','],['),']]',']') + ']);' + CHAR(10) + 'GO' + CHAR(10)
  9537. FROM #tblFK
  9538. ORDER BY [DatabaseName], parent_schema_name, parent_table_name, referenced_schema, referenced_table_name
  9539. OPEN curFKs
  9540. FETCH NEXT FROM curFKs INTO @strSQL5
  9541. WHILE (@@FETCH_STATUS = 0)
  9542. BEGIN
  9543. PRINT @strSQL5
  9544. FETCH NEXT FROM curFKs INTO @strSQL5
  9545. END
  9546. CLOSE curFKs
  9547. DEALLOCATE curFKs
  9548. PRINT '--############# Ended FK index creation statements #############' + CHAR(10)
  9549. END;
  9550. END
  9551. ELSE
  9552. BEGIN
  9553. SELECT 'Index_and_Stats_checks' AS [Category], 'FK_no_Index' AS [Check], '[OK]' AS [Deviation]
  9554. END;
  9555. END;
  9556. --------------------------------------------------------------------------------------------------------------------------------
  9557. -- Indexing per Table subsection
  9558. --------------------------------------------------------------------------------------------------------------------------------
  9559. IF @ptochecks = 1
  9560. BEGIN
  9561. RAISERROR (N' |-Starting Indexing per Table', 10, 1) WITH NOWAIT
  9562. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  9563. DROP TABLE #tblIxs3;
  9564. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  9565. CREATE TABLE #tblIxs3 ([Operation] tinyint, [databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200))
  9566. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  9567. DROP TABLE #tblIxs4;
  9568. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  9569. CREATE TABLE #tblIxs4 ([databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [CntCols] int, [CntIxs] int)
  9570. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  9571. DROP TABLE #tblIxs5;
  9572. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  9573. CREATE TABLE #tblIxs5 ([databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [indexName] VARCHAR(200), [indexLocation] VARCHAR(200))
  9574. UPDATE #tmpdbs1
  9575. SET isdone = 0
  9576. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9577. BEGIN
  9578. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9579. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9580. SELECT 1 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 si.[object_id], t.name, s.name
  9586. HAVING COUNT(index_id) = 1 AND MAX(index_id) = 0
  9587. UNION ALL
  9588. SELECT 2 AS [Check], ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name
  9589. FROM sys.indexes AS si (NOLOCK)
  9590. INNER JOIN sys.tables AS t (NOLOCK) ON si.[object_id] = t.[object_id]
  9591. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9592. WHERE si.is_hypothetical = 0
  9593. GROUP BY t.name, s.name
  9594. HAVING COUNT(index_id) > 1 AND MIN(index_id) = 0;'
  9595. BEGIN TRY
  9596. INSERT INTO #tblIxs3
  9597. EXECUTE sp_executesql @sqlcmd
  9598. END TRY
  9599. BEGIN CATCH
  9600. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9601. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 1 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9602. RAISERROR (@ErrorMessage, 16, 1);
  9603. END CATCH
  9604. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9605. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name, COUNT(c.column_id),
  9606. (SELECT COUNT(si.index_id) FROM sys.tables AS t2 INNER JOIN sys.indexes AS si ON si.[object_id] = t2.[object_id]
  9607. WHERE si.index_id > 0 AND si.[object_id] = t.[object_id] AND si.is_hypothetical = 0
  9608. GROUP BY si.[object_id])
  9609. FROM sys.tables AS t (NOLOCK)
  9610. INNER JOIN sys.columns AS c (NOLOCK) ON t.[object_id] = c.[object_id]
  9611. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9612. GROUP BY s.name, t.name, t.[object_id];'
  9613. BEGIN TRY
  9614. INSERT INTO #tblIxs4
  9615. EXECUTE sp_executesql @sqlcmd
  9616. END TRY
  9617. BEGIN CATCH
  9618. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9619. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 2 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9620. RAISERROR (@ErrorMessage, 16, 1);
  9621. END CATCH
  9622. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9623. SELECT DISTINCT ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name, i.name, ds.name
  9624. FROM sys.tables AS t (NOLOCK)
  9625. INNER JOIN sys.indexes AS i (NOLOCK) ON t.[object_id] = i.[object_id]
  9626. INNER JOIN sys.data_spaces AS ds (NOLOCK) ON ds.data_space_id = i.data_space_id
  9627. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9628. WHERE t.[type] = ''U''
  9629. AND i.[type] IN (1,2)
  9630. AND i.is_hypothetical = 0
  9631. -- Get partitioned tables
  9632. AND t.name IN (SELECT ob.name
  9633. FROM sys.tables AS ob (NOLOCK)
  9634. INNER JOIN sys.indexes AS ind (NOLOCK) ON ind.[object_id] = ob.[object_id]
  9635. INNER JOIN sys.data_spaces AS sds (NOLOCK) ON sds.data_space_id = ind.data_space_id
  9636. WHERE sds.[type] = ''PS''
  9637. GROUP BY ob.name)
  9638. AND ds.[type] <> ''PS'';'
  9639. BEGIN TRY
  9640. INSERT INTO #tblIxs5
  9641. EXECUTE sp_executesql @sqlcmd
  9642. END TRY
  9643. BEGIN CATCH
  9644. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9645. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 3 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9646. RAISERROR (@ErrorMessage, 16, 1);
  9647. END CATCH
  9648. UPDATE #tmpdbs1
  9649. SET isdone = 1
  9650. WHERE [dbid] = @dbid
  9651. END;
  9652. IF (SELECT COUNT(*) FROM #tblIxs3 WHERE [Operation] = 1) > 0
  9653. BEGIN
  9654. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_Indexes' AS [Check], '[WARNING: Some tables do not have indexes]' AS [Deviation]
  9655. 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
  9656. END
  9657. ELSE
  9658. BEGIN
  9659. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_Indexes' AS [Check], '[OK]' AS [Deviation]
  9660. END;
  9661. IF (SELECT COUNT(*) FROM #tblIxs3 WHERE [Operation] = 2) > 0
  9662. BEGIN
  9663. 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]
  9664. 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
  9665. END
  9666. ELSE
  9667. BEGIN
  9668. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_CL_Index' AS [Check], '[OK]' AS [Deviation]
  9669. END;
  9670. IF (SELECT COUNT(*) FROM #tblIxs4 WHERE [CntCols] < [CntIxs]) > 0
  9671. BEGIN
  9672. 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]
  9673. 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]
  9674. END
  9675. ELSE
  9676. BEGIN
  9677. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_more_Indexes_than_Cols' AS [Check], '[OK]' AS [Deviation]
  9678. END;
  9679. IF (SELECT COUNT(*) FROM #tblIxs5) > 0
  9680. BEGIN
  9681. 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]
  9682. 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
  9683. END
  9684. ELSE
  9685. BEGIN
  9686. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_partition_misaligned_Indexes' AS [Check], '[OK]' AS [Deviation]
  9687. END;
  9688. END;
  9689. --------------------------------------------------------------------------------------------------------------------------------
  9690. -- Missing Indexes subsection
  9691. -- Outputs only potentially most relevant, based in scoring method - use at you own discretion)
  9692. --------------------------------------------------------------------------------------------------------------------------------
  9693. IF @ptochecks = 1
  9694. BEGIN
  9695. RAISERROR (N' |-Starting Missing Indexes', 10, 1) WITH NOWAIT
  9696. DECLARE @IC VARCHAR(4000), @ICWI VARCHAR(4000), @editionCheck bit
  9697. /* Refer to http://msdn.microsoft.com/en-us/library/ms174396.aspx */
  9698. IF (SELECT SERVERPROPERTY('EditionID')) IN (1804890536, 1872460670, 610778273, -2117995310)
  9699. SET @editionCheck = 1 -- supports enterprise only features
  9700. ELSE
  9701. SET @editionCheck = 0; -- does not support enterprise only features
  9702. -- Create the helper functions
  9703. 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')
  9704. EXEC ('USE tempdb; EXEC(''
  9705. CREATE FUNCTION dbo.fn_createindex_allcols (@ix_handle int)
  9706. RETURNS NVARCHAR(max)
  9707. AS
  9708. BEGIN
  9709. DECLARE @ReturnCols NVARCHAR(max)
  9710. ;WITH ColumnToPivot ([data()]) AS (
  9711. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9712. FROM sys.dm_db_missing_index_details id
  9713. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9714. WHERE id.index_handle = @ix_handle
  9715. ORDER BY ic.column_id ASC
  9716. FOR XML PATH(''''''''), TYPE
  9717. ),
  9718. XmlRawData (CSVString) AS (
  9719. SELECT (SELECT [data()] AS InputData
  9720. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9721. )
  9722. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9723. FROM XmlRawData
  9724. RETURN (@ReturnCols)
  9725. END'')
  9726. ')
  9727. 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')
  9728. EXEC ('USE tempdb; EXEC(''
  9729. CREATE FUNCTION dbo.fn_createindex_keycols (@ix_handle int)
  9730. RETURNS NVARCHAR(max)
  9731. AS
  9732. BEGIN
  9733. DECLARE @ReturnCols NVARCHAR(max)
  9734. ;WITH ColumnToPivot ([data()]) AS (
  9735. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9736. FROM sys.dm_db_missing_index_details id
  9737. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9738. WHERE id.index_handle = @ix_handle
  9739. AND (ic.column_usage = ''''EQUALITY'''' OR ic.column_usage = ''''INEQUALITY'''')
  9740. ORDER BY ic.column_id ASC
  9741. FOR XML PATH(''''''''), TYPE
  9742. ),
  9743. XmlRawData (CSVString) AS (
  9744. SELECT (SELECT [data()] AS InputData
  9745. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9746. )
  9747. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9748. FROM XmlRawData
  9749. RETURN (@ReturnCols)
  9750. END'')
  9751. ')
  9752. 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')
  9753. EXEC ('USE tempdb; EXEC(''
  9754. CREATE FUNCTION dbo.fn_createindex_includecols (@ix_handle int)
  9755. RETURNS NVARCHAR(max)
  9756. AS
  9757. BEGIN
  9758. DECLARE @ReturnCols NVARCHAR(max)
  9759. ;WITH ColumnToPivot ([data()]) AS (
  9760. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9761. FROM sys.dm_db_missing_index_details id
  9762. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9763. WHERE id.index_handle = @ix_handle
  9764. AND ic.column_usage = ''''INCLUDE''''
  9765. ORDER BY ic.column_id ASC
  9766. FOR XML PATH(''''''''), TYPE
  9767. ),
  9768. XmlRawData (CSVString) AS (
  9769. SELECT (SELECT [data()] AS InputData
  9770. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9771. )
  9772. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9773. FROM XmlRawData
  9774. RETURN (@ReturnCols)
  9775. END'')
  9776. ')
  9777. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  9778. DROP TABLE #IndexCreation;
  9779. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  9780. CREATE TABLE #IndexCreation (
  9781. [database_id] int,
  9782. DBName VARCHAR(255),
  9783. [Table] VARCHAR(255),
  9784. [ix_handle] int,
  9785. [User_Hits_on_Missing_Index] int,
  9786. [Estimated_Improvement_Percent] DECIMAL(5,2),
  9787. [Avg_Total_User_Cost] int,
  9788. [Unique_Compiles] int,
  9789. [Score] NUMERIC(19,3),
  9790. [KeyCols] VARCHAR(1000),
  9791. [IncludedCols] VARCHAR(4000),
  9792. [Ix_Name] VARCHAR(255),
  9793. [AllCols] NVARCHAR(max),
  9794. [KeyColsOrdered] NVARCHAR(max),
  9795. [IncludedColsOrdered] NVARCHAR(max)
  9796. )
  9797. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  9798. DROP TABLE #IndexRedundant;
  9799. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  9800. CREATE TABLE #IndexRedundant (
  9801. DBName VARCHAR(255),
  9802. [Table] VARCHAR(255),
  9803. [Ix_Name] VARCHAR(255),
  9804. [ix_handle] int,
  9805. [KeyCols] VARCHAR(1000),
  9806. [IncludedCols] VARCHAR(4000),
  9807. [Redundant_With] VARCHAR(255)
  9808. )
  9809. INSERT INTO #IndexCreation
  9810. SELECT i.database_id,
  9811. m.[name],
  9812. RIGHT(i.[statement], LEN(i.[statement]) - (LEN(m.[name]) + 3)) AS [Table],
  9813. i.index_handle AS [ix_handle],
  9814. [User_Hits_on_Missing_Index] = (s.user_seeks + s.user_scans),
  9815. s.avg_user_impact, -- Query cost would reduce by this amount in percentage, on average.
  9816. s.avg_total_user_cost, -- Average cost of the user queries that could be reduced by the index in the group.
  9817. s.unique_compiles, -- Number of compilations and recompilations that would benefit from this missing index group.
  9818. (CONVERT(NUMERIC(19,3), s.user_seeks) + CONVERT(NUMERIC(19,3), s.user_scans))
  9819. * CONVERT(NUMERIC(19,3), s.avg_total_user_cost)
  9820. * CONVERT(NUMERIC(19,3), s.avg_user_impact) AS Score, -- The higher the score, higher is the anticipated improvement for user queries.
  9821. CASE WHEN (i.equality_columns IS NOT NULL AND i.inequality_columns IS NULL) THEN i.equality_columns
  9822. WHEN (i.equality_columns IS NULL AND i.inequality_columns IS NOT NULL) THEN i.inequality_columns
  9823. ELSE i.equality_columns + ',' + i.inequality_columns END AS [KeyCols],
  9824. i.included_columns AS [IncludedCols],
  9825. '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),
  9826. 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],
  9827. tempdb.dbo.fn_createindex_allcols(i.index_handle),
  9828. tempdb.dbo.fn_createindex_keycols(i.index_handle),
  9829. tempdb.dbo.fn_createindex_includecols(i.index_handle)
  9830. FROM sys.dm_db_missing_index_details i
  9831. INNER JOIN master.sys.databases m ON i.database_id = m.database_id
  9832. INNER JOIN sys.dm_db_missing_index_groups g ON i.index_handle = g.index_handle
  9833. INNER JOIN sys.dm_db_missing_index_group_stats s ON s.group_handle = g.index_group_handle
  9834. WHERE i.database_id > 4
  9835. INSERT INTO #IndexRedundant
  9836. SELECT I.DBName, I.[Table], I.[Ix_Name], I.[ix_handle], I.[KeyCols], I.[IncludedCols], I2.[Ix_Name]
  9837. FROM #IndexCreation I
  9838. INNER JOIN #IndexCreation I2 ON I.[database_id] = I2.[database_id] AND I.[Table] = I2.[Table] AND I.[Ix_Name] <> I2.[Ix_Name]
  9839. AND (((I.KeyColsOrdered <> I2.KeyColsOrdered OR I.[IncludedColsOrdered] <> I2.[IncludedColsOrdered])
  9840. 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)
  9841. OR I.[AllCols] = I2.[AllCols]))
  9842. OR (I.KeyColsOrdered <> I2.KeyColsOrdered AND I.[IncludedColsOrdered] = I2.[IncludedColsOrdered])
  9843. OR (I.KeyColsOrdered = I2.KeyColsOrdered AND I.[IncludedColsOrdered] <> I2.[IncludedColsOrdered]))
  9844. WHERE I.[Score] >= 100000
  9845. AND I2.[Score] >= 100000
  9846. GROUP BY I.DBName, I.[Table], I.[Ix_Name], I.[ix_handle], I.[KeyCols], I.[IncludedCols], I2.[Ix_Name]
  9847. ORDER BY I.DBName, I.[Table], I.[Ix_Name]
  9848. IF (SELECT COUNT(*) FROM #IndexCreation WHERE [Score] >= 100000) > 0
  9849. BEGIN
  9850. 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]
  9851. 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],
  9852. [Estimated_Improvement_Percent], [Avg_Total_User_Cost], [Unique_Compiles], IC.[KeyCols], IC.[IncludedCols], IC.[Ix_Name] AS [Index_Name],
  9853. SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9854. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9855. ORDER BY IR.[Redundant_With]
  9856. FOR XML PATH('')), 2, 8000) AS [Possibly_Redundant_With],
  9857. CASE WHEN IC.[Score] >= 100000 THEN 'Y' ELSE 'N' END AS [Generate_Script]
  9858. FROM #IndexCreation IC
  9859. --WHERE [Score] >= 100000
  9860. ORDER BY IC.DBName, IC.[Score] DESC, IC.[User_Hits_on_Missing_Index], IC.[Estimated_Improvement_Percent];
  9861. 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],
  9862. I.[Ix_Name] AS [Index_Name], I.[KeyCols], I.[IncludedCols]
  9863. FROM #IndexRedundant I
  9864. ORDER BY I.DBName, I.[Table], I.[Ix_Name]
  9865. IF @gen_scripts = 1
  9866. BEGIN
  9867. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */' + CHAR(10)
  9868. IF (SELECT COUNT(*) FROM #IndexCreation IC
  9869. WHERE IC.[IncludedCols] IS NULL AND IC.[Score] >= 100000
  9870. ) > 0
  9871. BEGIN
  9872. PRINT '--############# Indexes creation statements #############' + CHAR(10)
  9873. DECLARE cIC CURSOR FAST_FORWARD FOR
  9874. SELECT '-- User Hits on Missing Index ' + IC.[Ix_Name] + ': ' + CONVERT(VARCHAR(20),IC.[User_Hits_on_Missing_Index]) + CHAR(10) +
  9875. '-- Estimated Improvement Percent: ' + CONVERT(VARCHAR(6),IC.[Estimated_Improvement_Percent]) + CHAR(10) +
  9876. '-- Average Total User Cost: ' + CONVERT(VARCHAR(50),IC.[Avg_Total_User_Cost]) + CHAR(10) +
  9877. '-- Unique Compiles: ' + CONVERT(VARCHAR(50),IC.[Unique_Compiles]) + CHAR(10) +
  9878. '-- Score: ' + CONVERT(VARCHAR(20),CONVERT(bigint,IC.[Score])) +
  9879. CASE WHEN (SELECT COUNT(IR.[Redundant_With]) FROM #IndexRedundant IR
  9880. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]) > 0
  9881. THEN CHAR(10) + '-- Possibly Redundant with Missing Index(es): ' + SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9882. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9883. FOR XML PATH('')), 2, 8000)
  9884. ELSE '' END +
  9885. CHAR(10) + 'USE ' + QUOTENAME(IC.DBName) + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sysindexes WHERE name = N''' +
  9886. IC.[Ix_Name] + ''') DROP INDEX ' + IC.[Table] + '.' +
  9887. IC.[Ix_Name] + ';' + CHAR(10) + 'GO' + CHAR(10) + 'CREATE INDEX ' +
  9888. IC.[Ix_Name] + ' ON ' + IC.[Table] + ' (' + IC.[KeyCols] + CASE WHEN @editionCheck = 1 THEN ') WITH (ONLINE = ON);' ELSE ');' END + CHAR(10) + 'GO' + CHAR(10)
  9889. FROM #IndexCreation IC
  9890. WHERE IC.[IncludedCols] IS NULL AND IC.[Score] >= 100000
  9891. ORDER BY IC.DBName, IC.[Table], IC.[Ix_Name]
  9892. OPEN cIC
  9893. FETCH NEXT FROM cIC INTO @IC
  9894. WHILE @@FETCH_STATUS = 0
  9895. BEGIN
  9896. PRINT @IC
  9897. FETCH NEXT FROM cIC INTO @IC
  9898. END
  9899. CLOSE cIC
  9900. DEALLOCATE cIC
  9901. END;
  9902. IF (SELECT COUNT(*) FROM #IndexCreation IC
  9903. WHERE IC.[IncludedCols] IS NOT NULL AND IC.[Score] >= 100000
  9904. ) > 0
  9905. BEGIN
  9906. PRINT '--############# Covering indexes creation statements #############' + CHAR(10)
  9907. DECLARE cICWI CURSOR FAST_FORWARD FOR
  9908. SELECT '-- User Hits on Missing Index ' + IC.[Ix_Name] + ': ' + CONVERT(VARCHAR(20),IC.[User_Hits_on_Missing_Index]) + CHAR(10) +
  9909. '-- Estimated Improvement Percent: ' + CONVERT(VARCHAR(6),IC.[Estimated_Improvement_Percent]) + CHAR(10) +
  9910. '-- Average Total User Cost: ' + CONVERT(VARCHAR(50),IC.[Avg_Total_User_Cost]) + CHAR(10) +
  9911. '-- Unique Compiles: ' + CONVERT(VARCHAR(50),IC.[Unique_Compiles]) + CHAR(10) +
  9912. '-- Score: ' + CONVERT(VARCHAR(20),CONVERT(bigint,IC.[Score])) +
  9913. CASE WHEN (SELECT COUNT(IR.[Redundant_With]) FROM #IndexRedundant IR
  9914. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]) > 0
  9915. THEN CHAR(10) + '-- Possibly Redundant with Missing Index(es): ' + SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9916. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9917. FOR XML PATH('')), 2, 8000)
  9918. ELSE '' END +
  9919. CHAR(10) + 'USE ' + QUOTENAME(IC.DBName) + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sysindexes WHERE name = N''' +
  9920. IC.[Ix_Name] + ''') DROP INDEX ' + IC.[Table] + '.' +
  9921. IC.[Ix_Name] + ';' + CHAR(10) + 'GO' + CHAR(10) + 'CREATE INDEX ' +
  9922. 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)
  9923. FROM #IndexCreation IC
  9924. WHERE IC.[IncludedCols] IS NOT NULL AND IC.[Score] >= 100000
  9925. ORDER BY IC.DBName, IC.[Table], IC.[Ix_Name]
  9926. OPEN cICWI
  9927. FETCH NEXT FROM cICWI INTO @ICWI
  9928. WHILE @@FETCH_STATUS = 0
  9929. BEGIN
  9930. PRINT @ICWI
  9931. FETCH NEXT FROM cICWI INTO @ICWI
  9932. END
  9933. CLOSE cICWI
  9934. DEALLOCATE cICWI
  9935. END;
  9936. PRINT '--############# Ended missing indexes creation statements #############' + CHAR(10)
  9937. END;
  9938. END
  9939. ELSE IF (SELECT COUNT(*) FROM #IndexCreation WHERE [Score] < 100000) > 0
  9940. BEGIN
  9941. 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]
  9942. 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],
  9943. [Estimated_Improvement_Percent], [Avg_Total_User_Cost], [Unique_Compiles], IC.[KeyCols], IC.[IncludedCols], IC.[Ix_Name] AS [Index_Name],
  9944. SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9945. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9946. ORDER BY IR.[Redundant_With]
  9947. FOR XML PATH('')), 2, 8000) AS [Possibly_Redundant_With],
  9948. CASE WHEN IC.[Score] >= 100000 THEN 'Y' ELSE 'N' END AS [Generate_Script]
  9949. FROM #IndexCreation IC
  9950. --WHERE [Score] < 100000
  9951. ORDER BY IC.DBName, IC.[Score] DESC, IC.[User_Hits_on_Missing_Index], IC.[Estimated_Improvement_Percent];
  9952. END
  9953. ELSE
  9954. BEGIN
  9955. SELECT 'Index_and_Stats_checks' AS [Category], 'Missing_Indexes' AS [Check], '[OK]' AS [Deviation]
  9956. END
  9957. END;
  9958. --------------------------------------------------------------------------------------------------------------------------------
  9959. -- Objects naming conventions subsection
  9960. -- Refer to BOL for more information
  9961. -- (http://msdn.microsoft.com/en-us/library/dd172115(v=vs.100).aspx)
  9962. -- (http://msdn.microsoft.com/en-us/library/dd172134.aspx)
  9963. -- (http://msdn.microsoft.com/en-us/library/ms189822.aspx)
  9964. --------------------------------------------------------------------------------------------------------------------------------
  9965. RAISERROR (N'|-Starting Objects naming conventions Checks', 10, 1) WITH NOWAIT
  9966. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  9967. DROP TABLE #tmpobjectnames;
  9968. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  9969. CREATE TABLE #tmpobjectnames ([DBName] sysname, [schemaName] VARCHAR(100), [Object] VARCHAR(255), [Col] VARCHAR(255), [type] CHAR(2), type_desc VARCHAR(60));
  9970. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  9971. DROP TABLE #tmpfinalobjectnames;
  9972. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  9973. CREATE TABLE #tmpfinalobjectnames ([Deviation] tinyint, [DBName] sysname, [schemaName] VARCHAR(100), [Object] VARCHAR(255), [Col] VARCHAR(255), type_desc VARCHAR(60), [Comment] VARCHAR(500) NULL);
  9974. UPDATE #tmpdbs1
  9975. SET isdone = 0
  9976. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9977. BEGIN
  9978. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9979. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9980. SELECT ''' + @dbname + ''' AS [DBName], s.name, so.name, NULL, type, type_desc
  9981. FROM sys.objects so
  9982. INNER JOIN sys.schemas s ON so.schema_id = s.schema_id
  9983. WHERE so.is_ms_shipped = 0
  9984. UNION ALL
  9985. SELECT ''' + @dbname + ''' AS [DBName], s.name, so.name, sc.name, ''TC'' AS [type], ''TABLE_COLUMN'' AS [type_desc]
  9986. FROM sys.columns sc
  9987. INNER JOIN sys.objects so ON sc.object_id = so.object_id
  9988. INNER JOIN sys.schemas s ON so.schema_id = s.schema_id
  9989. WHERE so.is_ms_shipped = 0'
  9990. BEGIN TRY
  9991. INSERT INTO #tmpobjectnames
  9992. EXECUTE sp_executesql @sqlcmd
  9993. END TRY
  9994. BEGIN CATCH
  9995. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9996. SELECT @ErrorMessage = 'Object naming conventions subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9997. RAISERROR (@ErrorMessage, 16, 1);
  9998. END CATCH
  9999. UPDATE #tmpdbs1
  10000. SET isdone = 1
  10001. WHERE [dbid] = @dbid
  10002. END;
  10003. UPDATE #tmpdbs1
  10004. SET isdone = 0
  10005. CREATE INDEX IX1 ON #tmpobjectnames([type],[Object]);
  10006. /* http://msdn.microsoft.com/en-us/library/dd172115(v=vs.100).aspx */
  10007. INSERT INTO #tmpfinalobjectnames
  10008. SELECT 1, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10009. FROM #tmpobjectnames
  10010. WHERE [type] = 'P' AND [Object] LIKE 'sp[_]%'
  10011. AND [Object] NOT IN ('sp_alterdiagram','sp_creatediagram','sp_dropdiagram','sp_helpdiagramdefinition','sp_helpdiagrams','sp_renamediagram','sp_upgraddiagrams');
  10012. /* http://msdn.microsoft.com/en-us/library/dd172134.aspx */
  10013. INSERT INTO #tmpfinalobjectnames
  10014. SELECT 2, [DBName], [schemaName], [Object], [Col], type_desc, CASE WHEN [Object] LIKE '% %' THEN 'Space - ' + QUOTENAME([Object]) ELSE NULL END COLLATE database_default AS [Comment]
  10015. FROM #tmpobjectnames
  10016. WHERE [type] <> 'S' AND [type] <> 'TC'
  10017. AND ([Object] LIKE '% %' --space
  10018. OR [Object] LIKE '%[[]%'
  10019. OR [Object] LIKE '%]%'
  10020. OR [Object] LIKE '%-%'
  10021. OR [Object] LIKE '%.%'
  10022. OR [Object] LIKE '%,%'
  10023. OR [Object] LIKE '%;%'
  10024. OR [Object] LIKE '%' + CHAR(34) + '%' --double quote
  10025. OR [Object] LIKE '%' + CHAR(39) + '%'); --single quote
  10026. INSERT INTO #tmpfinalobjectnames
  10027. SELECT 3, [DBName], [schemaName], [Object], [Col], type_desc, CASE WHEN [Col] LIKE '% %' THEN 'Space - ' + QUOTENAME([Col]) ELSE NULL END COLLATE database_default AS [Comment]
  10028. FROM #tmpobjectnames
  10029. WHERE [type] = 'TC'
  10030. AND ([Col] LIKE '% %' --space
  10031. OR [Col] LIKE '%[[]%'
  10032. OR [Col] LIKE '%]%'
  10033. OR [Col] LIKE '%-%'
  10034. OR [Col] LIKE '%.%'
  10035. OR [Col] LIKE '%,%'
  10036. OR [Col] LIKE '%;%'
  10037. OR [Col] LIKE '%' + CHAR(34) + '%' --double quote
  10038. OR [Col] LIKE '%' + CHAR(39) + '%'); --single quote
  10039. /* http://msdn.microsoft.com/en-us/library/ms189822.aspx */
  10040. INSERT INTO #tmpfinalobjectnames
  10041. SELECT 4, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10042. FROM #tmpobjectnames
  10043. WHERE [type] <> 'S'
  10044. AND ([Object] LIKE '% ABSOLUTE %' OR [Object] LIKE '% ABSOLUTE' OR [Object] = 'ABSOLUTE'
  10045. OR [Object] LIKE '% ACTION %' OR [Object] LIKE '% ACTION' OR [Object] = 'ACTION'
  10046. OR [Object] LIKE '% ADA %' OR [Object] LIKE '% ADA' OR [Object] = 'ADA'
  10047. OR [Object] LIKE '% ADD %' OR [Object] LIKE '% ADD' OR [Object] = 'ADD'
  10048. OR [Object] LIKE '% ADMIN %' OR [Object] LIKE '% ADMIN' OR [Object] = 'ADMIN'
  10049. OR [Object] LIKE '% AFTER %' OR [Object] LIKE '% AFTER' OR [Object] = 'AFTER'
  10050. OR [Object] LIKE '% AGGREGATE %' OR [Object] LIKE '% AGGREGATE' OR [Object] = 'AGGREGATE'
  10051. OR [Object] LIKE '% ALIAS %' OR [Object] LIKE '% ALIAS' OR [Object] = 'ALIAS'
  10052. OR [Object] LIKE '% ALL %' OR [Object] LIKE '% ALL' OR [Object] = 'ALL'
  10053. OR [Object] LIKE '% ALLOCATE %' OR [Object] LIKE '% ALLOCATE' OR [Object] = 'ALLOCATE'
  10054. OR [Object] LIKE '% ALTER %' OR [Object] LIKE '% ALTER' OR [Object] = 'ALTER'
  10055. OR [Object] LIKE '% AND %' OR [Object] LIKE '% AND' OR [Object] = 'AND'
  10056. OR [Object] LIKE '% ANY %' OR [Object] LIKE '% ANY' OR [Object] = 'ANY'
  10057. OR [Object] LIKE '% ARE %' OR [Object] LIKE '% ARE' OR [Object] = 'ARE'
  10058. OR [Object] LIKE '% ARRAY %' OR [Object] LIKE '% ARRAY' OR [Object] = 'ARRAY'
  10059. OR [Object] LIKE '% AS %' OR [Object] LIKE '% AS' OR [Object] = 'AS'
  10060. OR [Object] LIKE '% ASC %' OR [Object] LIKE '% ASC' OR [Object] = 'ASC'
  10061. OR [Object] LIKE '% ASSERTION %' OR [Object] LIKE '% ASSERTION' OR [Object] = 'ASSERTION'
  10062. OR [Object] LIKE '% AT %' OR [Object] LIKE '% AT' OR [Object] = 'AT'
  10063. OR [Object] LIKE '% AUTHORIZATION %' OR [Object] LIKE '% AUTHORIZATION' OR [Object] = 'AUTHORIZATION'
  10064. OR [Object] LIKE '% AVG %' OR [Object] LIKE '% AVG' OR [Object] = 'AVG'
  10065. OR [Object] LIKE '% BACKUP %' OR [Object] LIKE '% BACKUP' OR [Object] = 'BACKUP'
  10066. OR [Object] LIKE '% BEFORE %' OR [Object] LIKE '% BEFORE' OR [Object] = 'BEFORE'
  10067. OR [Object] LIKE '% BEGIN %' OR [Object] LIKE '% BEGIN' OR [Object] = 'BEGIN'
  10068. OR [Object] LIKE '% BETWEEN %' OR [Object] LIKE '% BETWEEN' OR [Object] = 'BETWEEN'
  10069. OR [Object] LIKE '% BINARY %' OR [Object] LIKE '% BINARY' OR [Object] = 'BINARY'
  10070. OR [Object] LIKE '% BIT %' OR [Object] LIKE '% BIT' OR [Object] = 'BIT'
  10071. OR [Object] LIKE '% BIT_LENGTH %' OR [Object] LIKE '% BIT_LENGTH' OR [Object] = 'BIT_LENGTH'
  10072. OR [Object] LIKE '% BLOB %' OR [Object] LIKE '% BLOB' OR [Object] = 'BLOB'
  10073. OR [Object] LIKE '% BOOLEAN %' OR [Object] LIKE '% BOOLEAN' OR [Object] = 'BOOLEAN'
  10074. OR [Object] LIKE '% BOTH %' OR [Object] LIKE '% BOTH' OR [Object] = 'BOTH'
  10075. OR [Object] LIKE '% BREADTH %' OR [Object] LIKE '% BREADTH' OR [Object] = 'BREADTH'
  10076. OR [Object] LIKE '% BREAK %' OR [Object] LIKE '% BREAK' OR [Object] = 'BREAK'
  10077. OR [Object] LIKE '% BROWSE %' OR [Object] LIKE '% BROWSE' OR [Object] = 'BROWSE'
  10078. OR [Object] LIKE '% BULK %' OR [Object] LIKE '% BULK' OR [Object] = 'BULK'
  10079. OR [Object] LIKE '% BY %' OR [Object] LIKE '% BY' OR [Object] = 'BY'
  10080. OR [Object] LIKE '% CALL %' OR [Object] LIKE '% CALL' OR [Object] = 'CALL'
  10081. OR [Object] LIKE '% CASCADE %' OR [Object] LIKE '% CASCADE' OR [Object] = 'CASCADE'
  10082. OR [Object] LIKE '% CASCADED %' OR [Object] LIKE '% CASCADED' OR [Object] = 'CASCADED'
  10083. OR [Object] LIKE '% CASE %' OR [Object] LIKE '% CASE' OR [Object] = 'CASE'
  10084. OR [Object] LIKE '% CAST %' OR [Object] LIKE '% CAST' OR [Object] = 'CAST'
  10085. OR [Object] LIKE '% CATALOG %' OR [Object] LIKE '% CATALOG' OR [Object] = 'CATALOG'
  10086. OR [Object] LIKE '% CHAR %' OR [Object] LIKE '% CHAR' OR [Object] = 'CHAR'
  10087. OR [Object] LIKE '% CHAR_LENGTH %' OR [Object] LIKE '% CHAR_LENGTH' OR [Object] = 'CHAR_LENGTH'
  10088. OR [Object] LIKE '% CHARACTER %' OR [Object] LIKE '% CHARACTER' OR [Object] = 'CHARACTER'
  10089. OR [Object] LIKE '% CHARACTER_LENGTH %' OR [Object] LIKE '% CHARACTER_LENGTH' OR [Object] = 'CHARACTER_LENGTH'
  10090. OR [Object] LIKE '% CHECK %' OR [Object] LIKE '% CHECK' OR [Object] = 'CHECK'
  10091. OR [Object] LIKE '% CHECKPOINT %' OR [Object] LIKE '% CHECKPOINT' OR [Object] = 'CHECKPOINT'
  10092. OR [Object] LIKE '% CLASS %' OR [Object] LIKE '% CLASS' OR [Object] = 'CLASS'
  10093. OR [Object] LIKE '% CLOB %' OR [Object] LIKE '% CLOB' OR [Object] = 'CLOB'
  10094. OR [Object] LIKE '% CLOSE %' OR [Object] LIKE '% CLOSE' OR [Object] = 'CLOSE'
  10095. OR [Object] LIKE '% CLUSTERED %' OR [Object] LIKE '% CLUSTERED' OR [Object] = 'CLUSTERED'
  10096. OR [Object] LIKE '% COALESCE %' OR [Object] LIKE '% COALESCE' OR [Object] = 'COALESCE'
  10097. OR [Object] LIKE '% COLLATE %' OR [Object] LIKE '% COLLATE' OR [Object] = 'COLLATE'
  10098. OR [Object] LIKE '% COLLATION %' OR [Object] LIKE '% COLLATION' OR [Object] = 'COLLATION'
  10099. OR [Object] LIKE '% COLUMN %' OR [Object] LIKE '% COLUMN' OR [Object] = 'COLUMN'
  10100. OR [Object] LIKE '% COMMIT %' OR [Object] LIKE '% COMMIT' OR [Object] = 'COMMIT'
  10101. OR [Object] LIKE '% COMPLETION %' OR [Object] LIKE '% COMPLETION' OR [Object] = 'COMPLETION'
  10102. OR [Object] LIKE '% COMPUTE %' OR [Object] LIKE '% COMPUTE' OR [Object] = 'COMPUTE'
  10103. OR [Object] LIKE '% CONNECT %' OR [Object] LIKE '% CONNECT' OR [Object] = 'CONNECT'
  10104. OR [Object] LIKE '% CONNECTION %' OR [Object] LIKE '% CONNECTION' OR [Object] = 'CONNECTION'
  10105. OR [Object] LIKE '% CONSTRAINT %' OR [Object] LIKE '% CONSTRAINT' OR [Object] = 'CONSTRAINT'
  10106. OR [Object] LIKE '% CONSTRAINTS %' OR [Object] LIKE '% CONSTRAINTS' OR [Object] = 'CONSTRAINTS'
  10107. OR [Object] LIKE '% CONSTRUCTOR %' OR [Object] LIKE '% CONSTRUCTOR' OR [Object] = 'CONSTRUCTOR'
  10108. OR [Object] LIKE '% CONTAINS %' OR [Object] LIKE '% CONTAINS' OR [Object] = 'CONTAINS'
  10109. OR [Object] LIKE '% CONTAINSTABLE %' OR [Object] LIKE '% CONTAINSTABLE' OR [Object] = 'CONTAINSTABLE'
  10110. OR [Object] LIKE '% CONTINUE %' OR [Object] LIKE '% CONTINUE' OR [Object] = 'CONTINUE'
  10111. OR [Object] LIKE '% CONVERT %' OR [Object] LIKE '% CONVERT' OR [Object] = 'CONVERT'
  10112. OR [Object] LIKE '% CORRESPONDING %' OR [Object] LIKE '% CORRESPONDING' OR [Object] = 'CORRESPONDING'
  10113. OR [Object] LIKE '% COUNT %' OR [Object] LIKE '% COUNT' OR [Object] = 'COUNT'
  10114. OR [Object] LIKE '% CREATE %' OR [Object] LIKE '% CREATE' OR [Object] = 'CREATE'
  10115. OR [Object] LIKE '% CROSS %' OR [Object] LIKE '% CROSS' OR [Object] = 'CROSS'
  10116. OR [Object] LIKE '% CUBE %' OR [Object] LIKE '% CUBE' OR [Object] = 'CUBE'
  10117. OR [Object] LIKE '% CURRENT %' OR [Object] LIKE '% CURRENT' OR [Object] = 'CURRENT'
  10118. OR [Object] LIKE '% CURRENT_DATE %' OR [Object] LIKE '% CURRENT_DATE' OR [Object] = 'CURRENT_DATE'
  10119. OR [Object] LIKE '% CURRENT_PATH %' OR [Object] LIKE '% CURRENT_PATH' OR [Object] = 'CURRENT_PATH'
  10120. OR [Object] LIKE '% CURRENT_ROLE %' OR [Object] LIKE '% CURRENT_ROLE' OR [Object] = 'CURRENT_ROLE'
  10121. OR [Object] LIKE '% CURRENT_TIME %' OR [Object] LIKE '% CURRENT_TIME' OR [Object] = 'CURRENT_TIME'
  10122. OR [Object] LIKE '% CURRENT_TIMESTAMP %' OR [Object] LIKE '% CURRENT_TIMESTAMP' OR [Object] = 'CURRENT_TIMESTAMP'
  10123. OR [Object] LIKE '% CURRENT_USER %' OR [Object] LIKE '% CURRENT_USER' OR [Object] = 'CURRENT_USER'
  10124. OR [Object] LIKE '% CURSOR %' OR [Object] LIKE '% CURSOR' OR [Object] = 'CURSOR'
  10125. OR [Object] LIKE '% CYCLE %' OR [Object] LIKE '% CYCLE' OR [Object] = 'CYCLE'
  10126. OR [Object] LIKE '% DATA %' OR [Object] LIKE '% DATA' OR [Object] = 'DATA'
  10127. OR [Object] LIKE '% DATABASE %' OR [Object] LIKE '% DATABASE' OR [Object] = 'DATABASE'
  10128. OR [Object] LIKE '% DATE %' OR [Object] LIKE '% DATE' OR [Object] = 'DATE'
  10129. OR [Object] LIKE '% DAY %' OR [Object] LIKE '% DAY' OR [Object] = 'DAY'
  10130. OR [Object] LIKE '% DBCC %' OR [Object] LIKE '% DBCC' OR [Object] = 'DBCC'
  10131. OR [Object] LIKE '% DEALLOCATE %' OR [Object] LIKE '% DEALLOCATE' OR [Object] = 'DEALLOCATE'
  10132. OR [Object] LIKE '% DEC %' OR [Object] LIKE '% DEC' OR [Object] = 'DEC'
  10133. OR [Object] LIKE '% DECIMAL %' OR [Object] LIKE '% DECIMAL' OR [Object] = 'DECIMAL'
  10134. OR [Object] LIKE '% DECLARE %' OR [Object] LIKE '% DECLARE' OR [Object] = 'DECLARE'
  10135. OR [Object] LIKE '% DEFAULT %' OR [Object] LIKE '% DEFAULT' OR [Object] = 'DEFAULT'
  10136. OR [Object] LIKE '% DEFERRABLE %' OR [Object] LIKE '% DEFERRABLE' OR [Object] = 'DEFERRABLE'
  10137. OR [Object] LIKE '% DEFERRED %' OR [Object] LIKE '% DEFERRED' OR [Object] = 'DEFERRED'
  10138. OR [Object] LIKE '% DELETE %' OR [Object] LIKE '% DELETE' OR [Object] = 'DELETE'
  10139. OR [Object] LIKE '% DENY %' OR [Object] LIKE '% DENY' OR [Object] = 'DENY'
  10140. OR [Object] LIKE '% DEPTH %' OR [Object] LIKE '% DEPTH' OR [Object] = 'DEPTH'
  10141. OR [Object] LIKE '% DEREF %' OR [Object] LIKE '% DEREF' OR [Object] = 'DEREF'
  10142. OR [Object] LIKE '% DESC %' OR [Object] LIKE '% DESC' OR [Object] = 'DESC'
  10143. OR [Object] LIKE '% DESCRIBE %' OR [Object] LIKE '% DESCRIBE' OR [Object] = 'DESCRIBE'
  10144. OR [Object] LIKE '% DESCRIPTOR %' OR [Object] LIKE '% DESCRIPTOR' OR [Object] = 'DESCRIPTOR'
  10145. OR [Object] LIKE '% DESTROY %' OR [Object] LIKE '% DESTROY' OR [Object] = 'DESTROY'
  10146. OR [Object] LIKE '% DESTRUCTOR %' OR [Object] LIKE '% DESTRUCTOR' OR [Object] = 'DESTRUCTOR'
  10147. OR [Object] LIKE '% DETERMINISTIC %' OR [Object] LIKE '% DETERMINISTIC' OR [Object] = 'DETERMINISTIC'
  10148. OR [Object] LIKE '% DIAGNOSTICS %' OR [Object] LIKE '% DIAGNOSTICS' OR [Object] = 'DIAGNOSTICS'
  10149. OR [Object] LIKE '% DICTIONARY %' OR [Object] LIKE '% DICTIONARY' OR [Object] = 'DICTIONARY'
  10150. OR [Object] LIKE '% DISCONNECT %' OR [Object] LIKE '% DISCONNECT' OR [Object] = 'DISCONNECT'
  10151. OR [Object] LIKE '% DISK %' OR [Object] LIKE '% DISK' OR [Object] = 'DISK'
  10152. OR [Object] LIKE '% DISTINCT %' OR [Object] LIKE '% DISTINCT' OR [Object] = 'DISTINCT'
  10153. OR [Object] LIKE '% DISTRIBUTED %' OR [Object] LIKE '% DISTRIBUTED' OR [Object] = 'DISTRIBUTED'
  10154. OR [Object] LIKE '% DOMAIN %' OR [Object] LIKE '% DOMAIN' OR [Object] = 'DOMAIN'
  10155. OR [Object] LIKE '% DOUBLE %' OR [Object] LIKE '% DOUBLE' OR [Object] = 'DOUBLE'
  10156. OR [Object] LIKE '% DROP %' OR [Object] LIKE '% DROP' OR [Object] = 'DROP'
  10157. OR [Object] LIKE '% DUMMY %' OR [Object] LIKE '% DUMMY' OR [Object] = 'DUMMY'
  10158. OR [Object] LIKE '% DUMP %' OR [Object] LIKE '% DUMP' OR [Object] = 'DUMP'
  10159. OR [Object] LIKE '% DYNAMIC %' OR [Object] LIKE '% DYNAMIC' OR [Object] = 'DYNAMIC'
  10160. OR [Object] LIKE '% EACH %' OR [Object] LIKE '% EACH' OR [Object] = 'EACH'
  10161. OR [Object] LIKE '% ELSE %' OR [Object] LIKE '% ELSE' OR [Object] = 'ELSE'
  10162. OR [Object] LIKE '% END %' OR [Object] LIKE '% END' OR [Object] = 'END'
  10163. OR [Object] LIKE '% END-EXEC %' OR [Object] LIKE '% END-EXEC' OR [Object] = 'END-EXEC'
  10164. OR [Object] LIKE '% EQUALS %' OR [Object] LIKE '% EQUALS' OR [Object] = 'EQUALS'
  10165. OR [Object] LIKE '% ERRLVL %' OR [Object] LIKE '% ERRLVL' OR [Object] = 'ERRLVL'
  10166. OR [Object] LIKE '% ESCAPE %' OR [Object] LIKE '% ESCAPE' OR [Object] = 'ESCAPE'
  10167. OR [Object] LIKE '% EVERY %' OR [Object] LIKE '% EVERY' OR [Object] = 'EVERY'
  10168. OR [Object] LIKE '% EXCEPT %' OR [Object] LIKE '% EXCEPT' OR [Object] = 'EXCEPT'
  10169. OR [Object] LIKE '% EXCEPTION %' OR [Object] LIKE '% EXCEPTION' OR [Object] = 'EXCEPTION'
  10170. OR [Object] LIKE '% EXEC %' OR [Object] LIKE '% EXEC' OR [Object] = 'EXEC'
  10171. OR [Object] LIKE '% EXECUTE %' OR [Object] LIKE '% EXECUTE' OR [Object] = 'EXECUTE'
  10172. OR [Object] LIKE '% EXISTS %' OR [Object] LIKE '% EXISTS' OR [Object] = 'EXISTS'
  10173. OR [Object] LIKE '% EXIT %' OR [Object] LIKE '% EXIT' OR [Object] = 'EXIT'
  10174. OR [Object] LIKE '% EXTERNAL %' OR [Object] LIKE '% EXTERNAL' OR [Object] = 'EXTERNAL'
  10175. OR [Object] LIKE '% EXTRACT %' OR [Object] LIKE '% EXTRACT' OR [Object] = 'EXTRACT'
  10176. OR [Object] LIKE '% FALSE %' OR [Object] LIKE '% FALSE' OR [Object] = 'FALSE'
  10177. OR [Object] LIKE '% FETCH %' OR [Object] LIKE '% FETCH' OR [Object] = 'FETCH'
  10178. OR [Object] LIKE '% FILE %' OR [Object] LIKE '% FILE' OR [Object] = 'FILE'
  10179. OR [Object] LIKE '% FILLFACTOR %' OR [Object] LIKE '% FILLFACTOR' OR [Object] = 'FILLFACTOR'
  10180. OR [Object] LIKE '% FIRST %' OR [Object] LIKE '% FIRST' OR [Object] = 'FIRST'
  10181. OR [Object] LIKE '% FLOAT %' OR [Object] LIKE '% FLOAT' OR [Object] = 'FLOAT'
  10182. OR [Object] LIKE '% FOR %' OR [Object] LIKE '% FOR' OR [Object] = 'FOR'
  10183. OR [Object] LIKE '% FOREIGN %' OR [Object] LIKE '% FOREIGN' OR [Object] = 'FOREIGN'
  10184. OR [Object] LIKE '% FORTRAN %' OR [Object] LIKE '% FORTRAN' OR [Object] = 'FORTRAN'
  10185. OR [Object] LIKE '% FOUND %' OR [Object] LIKE '% FOUND' OR [Object] = 'FOUND'
  10186. OR [Object] LIKE '% FREE %' OR [Object] LIKE '% FREE' OR [Object] = 'FREE'
  10187. OR [Object] LIKE '% FREETEXT %' OR [Object] LIKE '% FREETEXT' OR [Object] = 'FREETEXT'
  10188. OR [Object] LIKE '% FREETEXTTABLE %' OR [Object] LIKE '% FREETEXTTABLE' OR [Object] = 'FREETEXTTABLE'
  10189. OR [Object] LIKE '% FROM %' OR [Object] LIKE '% FROM' OR [Object] = 'FROM'
  10190. OR [Object] LIKE '% FULL %' OR [Object] LIKE '% FULL' OR [Object] = 'FULL'
  10191. OR [Object] LIKE '% FULLTEXTTABLE %' OR [Object] LIKE '% FULLTEXTTABLE' OR [Object] = 'FULLTEXTTABLE'
  10192. OR [Object] LIKE '% FUNCTION %' OR [Object] LIKE '% FUNCTION' OR [Object] = 'FUNCTION'
  10193. OR [Object] LIKE '% GENERAL %' OR [Object] LIKE '% GENERAL' OR [Object] = 'GENERAL'
  10194. OR [Object] LIKE '% GET %' OR [Object] LIKE '% GET' OR [Object] = 'GET'
  10195. OR [Object] LIKE '% GLOBAL %' OR [Object] LIKE '% GLOBAL' OR [Object] = 'GLOBAL'
  10196. OR [Object] LIKE '% GO %' OR [Object] LIKE '% GO' OR [Object] = 'GO'
  10197. OR [Object] LIKE '% GOTO %' OR [Object] LIKE '% GOTO' OR [Object] = 'GOTO'
  10198. OR [Object] LIKE '% GRANT %' OR [Object] LIKE '% GRANT' OR [Object] = 'GRANT'
  10199. OR [Object] LIKE '% GROUP %' OR [Object] LIKE '% GROUP' OR [Object] = 'GROUP'
  10200. OR [Object] LIKE '% GROUPING %' OR [Object] LIKE '% GROUPING' OR [Object] = 'GROUPING'
  10201. OR [Object] LIKE '% HAVING %' OR [Object] LIKE '% HAVING' OR [Object] = 'HAVING'
  10202. OR [Object] LIKE '% HOLDLOCK %' OR [Object] LIKE '% HOLDLOCK' OR [Object] = 'HOLDLOCK'
  10203. OR [Object] LIKE '% HOST %' OR [Object] LIKE '% HOST' OR [Object] = 'HOST'
  10204. OR [Object] LIKE '% HOUR %' OR [Object] LIKE '% HOUR' OR [Object] = 'HOUR'
  10205. OR [Object] LIKE '% IDENTITY %' OR [Object] LIKE '% IDENTITY' OR [Object] = 'IDENTITY'
  10206. OR [Object] LIKE '% IDENTITY_INSERT %' OR [Object] LIKE '% IDENTITY_INSERT' OR [Object] = 'IDENTITY_INSERT'
  10207. OR [Object] LIKE '% IDENTITYCOL %' OR [Object] LIKE '% IDENTITYCOL' OR [Object] = 'IDENTITYCOL'
  10208. OR [Object] LIKE '% IF %' OR [Object] LIKE '% IF' OR [Object] = 'IF'
  10209. OR [Object] LIKE '% IGNORE %' OR [Object] LIKE '% IGNORE' OR [Object] = 'IGNORE'
  10210. OR [Object] LIKE '% IMMEDIATE %' OR [Object] LIKE '% IMMEDIATE' OR [Object] = 'IMMEDIATE'
  10211. OR [Object] LIKE '% IN %' OR [Object] LIKE '% IN' OR [Object] = 'IN'
  10212. OR [Object] LIKE '% INCLUDE %' OR [Object] LIKE '% INCLUDE' OR [Object] = 'INCLUDE'
  10213. OR [Object] LIKE '% INDEX %' OR [Object] LIKE '% INDEX' OR [Object] = 'INDEX'
  10214. OR [Object] LIKE '% INDICATOR %' OR [Object] LIKE '% INDICATOR' OR [Object] = 'INDICATOR'
  10215. OR [Object] LIKE '% INITIALIZE %' OR [Object] LIKE '% INITIALIZE' OR [Object] = 'INITIALIZE'
  10216. OR [Object] LIKE '% INITIALLY %' OR [Object] LIKE '% INITIALLY' OR [Object] = 'INITIALLY'
  10217. OR [Object] LIKE '% INNER %' OR [Object] LIKE '% INNER' OR [Object] = 'INNER'
  10218. OR [Object] LIKE '% INOUT %' OR [Object] LIKE '% INOUT' OR [Object] = 'INOUT'
  10219. OR [Object] LIKE '% INPUT %' OR [Object] LIKE '% INPUT' OR [Object] = 'INPUT'
  10220. OR [Object] LIKE '% INSENSITIVE %' OR [Object] LIKE '% INSENSITIVE' OR [Object] = 'INSENSITIVE'
  10221. OR [Object] LIKE '% INSERT %' OR [Object] LIKE '% INSERT' OR [Object] = 'INSERT'
  10222. OR [Object] LIKE '% INT %' OR [Object] LIKE '% INT' OR [Object] = 'INT'
  10223. OR [Object] LIKE '% INTEGER %' OR [Object] LIKE '% INTEGER' OR [Object] = 'INTEGER'
  10224. OR [Object] LIKE '% INTERSECT %' OR [Object] LIKE '% INTERSECT' OR [Object] = 'INTERSECT'
  10225. OR [Object] LIKE '% INTERVAL %' OR [Object] LIKE '% INTERVAL' OR [Object] = 'INTERVAL'
  10226. OR [Object] LIKE '% INTO %' OR [Object] LIKE '% INTO' OR [Object] = 'INTO'
  10227. OR [Object] LIKE '% IS %' OR [Object] LIKE '% IS' OR [Object] = 'IS'
  10228. OR [Object] LIKE '% ISOLATION %' OR [Object] LIKE '% ISOLATION' OR [Object] = 'ISOLATION'
  10229. OR [Object] LIKE '% ITERATE %' OR [Object] LIKE '% ITERATE' OR [Object] = 'ITERATE'
  10230. OR [Object] LIKE '% JOIN %' OR [Object] LIKE '% JOIN' OR [Object] = 'JOIN'
  10231. OR [Object] LIKE '% KEY %' OR [Object] LIKE '% KEY' OR [Object] = 'KEY'
  10232. OR [Object] LIKE '% KILL %' OR [Object] LIKE '% KILL' OR [Object] = 'KILL'
  10233. OR [Object] LIKE '% LANGUAGE %' OR [Object] LIKE '% LANGUAGE' OR [Object] = 'LANGUAGE'
  10234. OR [Object] LIKE '% LARGE %' OR [Object] LIKE '% LARGE' OR [Object] = 'LARGE'
  10235. OR [Object] LIKE '% LAST %' OR [Object] LIKE '% LAST' OR [Object] = 'LAST'
  10236. OR [Object] LIKE '% LATERAL %' OR [Object] LIKE '% LATERAL' OR [Object] = 'LATERAL'
  10237. OR [Object] LIKE '% LEADING %' OR [Object] LIKE '% LEADING' OR [Object] = 'LEADING'
  10238. OR [Object] LIKE '% LEFT %' OR [Object] LIKE '% LEFT' OR [Object] = 'LEFT'
  10239. OR [Object] LIKE '% LESS %' OR [Object] LIKE '% LESS' OR [Object] = 'LESS'
  10240. OR [Object] LIKE '% LEVEL %' OR [Object] LIKE '% LEVEL' OR [Object] = 'LEVEL'
  10241. OR [Object] LIKE '% LIKE %' OR [Object] LIKE '% LIKE' OR [Object] = 'LIKE'
  10242. OR [Object] LIKE '% LIMIT %' OR [Object] LIKE '% LIMIT' OR [Object] = 'LIMIT'
  10243. OR [Object] LIKE '% LINENO %' OR [Object] LIKE '% LINENO' OR [Object] = 'LINENO'
  10244. OR [Object] LIKE '% LOAD %' OR [Object] LIKE '% LOAD' OR [Object] = 'LOAD'
  10245. OR [Object] LIKE '% LOCAL %' OR [Object] LIKE '% LOCAL' OR [Object] = 'LOCAL'
  10246. OR [Object] LIKE '% LOCALTIME %' OR [Object] LIKE '% LOCALTIME' OR [Object] = 'LOCALTIME'
  10247. OR [Object] LIKE '% LOCALTIMESTAMP %' OR [Object] LIKE '% LOCALTIMESTAMP' OR [Object] = 'LOCALTIMESTAMP'
  10248. OR [Object] LIKE '% LOCATOR %' OR [Object] LIKE '% LOCATOR' OR [Object] = 'LOCATOR'
  10249. OR [Object] LIKE '% LOWER %' OR [Object] LIKE '% LOWER' OR [Object] = 'LOWER'
  10250. OR [Object] LIKE '% MAP %' OR [Object] LIKE '% MAP' OR [Object] = 'MAP'
  10251. OR [Object] LIKE '% MATCH %' OR [Object] LIKE '% MATCH' OR [Object] = 'MATCH'
  10252. OR [Object] LIKE '% MAX %' OR [Object] LIKE '% MAX' OR [Object] = 'MAX'
  10253. OR [Object] LIKE '% MIN %' OR [Object] LIKE '% MIN' OR [Object] = 'MIN'
  10254. OR [Object] LIKE '% MINUTE %' OR [Object] LIKE '% MINUTE' OR [Object] = 'MINUTE'
  10255. OR [Object] LIKE '% MODIFIES %' OR [Object] LIKE '% MODIFIES' OR [Object] = 'MODIFIES'
  10256. OR [Object] LIKE '% MODIFY %' OR [Object] LIKE '% MODIFY' OR [Object] = 'MODIFY'
  10257. OR [Object] LIKE '% MODULE %' OR [Object] LIKE '% MODULE' OR [Object] = 'MODULE'
  10258. OR [Object] LIKE '% MONTH %' OR [Object] LIKE '% MONTH' OR [Object] = 'MONTH'
  10259. OR [Object] LIKE '% NAMES %' OR [Object] LIKE '% NAMES' OR [Object] = 'NAMES'
  10260. OR [Object] LIKE '% NATIONAL %' OR [Object] LIKE '% NATIONAL' OR [Object] = 'NATIONAL'
  10261. OR [Object] LIKE '% NATURAL %' OR [Object] LIKE '% NATURAL' OR [Object] = 'NATURAL'
  10262. OR [Object] LIKE '% NCHAR %' OR [Object] LIKE '% NCHAR' OR [Object] = 'NCHAR'
  10263. OR [Object] LIKE '% NCLOB %' OR [Object] LIKE '% NCLOB' OR [Object] = 'NCLOB'
  10264. OR [Object] LIKE '% NEW %' OR [Object] LIKE '% NEW' OR [Object] = 'NEW'
  10265. OR [Object] LIKE '% NEXT %' OR [Object] LIKE '% NEXT' OR [Object] = 'NEXT'
  10266. OR [Object] LIKE '% NO %' OR [Object] LIKE '% NO' OR [Object] = 'NO'
  10267. OR [Object] LIKE '% NOCHECK %' OR [Object] LIKE '% NOCHECK' OR [Object] = 'NOCHECK'
  10268. OR [Object] LIKE '% NONCLUSTERED %' OR [Object] LIKE '% NONCLUSTERED' OR [Object] = 'NONCLUSTERED'
  10269. OR [Object] LIKE '% NONE %' OR [Object] LIKE '% NONE' OR [Object] = 'NONE'
  10270. OR [Object] LIKE '% NOT %' OR [Object] LIKE '% NOT' OR [Object] = 'NOT'
  10271. OR [Object] LIKE '% NULL %' OR [Object] LIKE '% NULL' OR [Object] = 'NULL'
  10272. OR [Object] LIKE '% NULLIF %' OR [Object] LIKE '% NULLIF' OR [Object] = 'NULLIF'
  10273. OR [Object] LIKE '% NUMERIC %' OR [Object] LIKE '% NUMERIC' OR [Object] = 'NUMERIC'
  10274. OR [Object] LIKE '% OBJECT %' OR [Object] LIKE '% OBJECT' OR [Object] = 'OBJECT'
  10275. OR [Object] LIKE '% OCTET_LENGTH %' OR [Object] LIKE '% OCTET_LENGTH' OR [Object] = 'OCTET_LENGTH'
  10276. OR [Object] LIKE '% OF %' OR [Object] LIKE '% OF' OR [Object] = 'OF'
  10277. OR [Object] LIKE '% OFF %' OR [Object] LIKE '% OFF' OR [Object] = 'OFF'
  10278. OR [Object] LIKE '% OFFSETS %' OR [Object] LIKE '% OFFSETS' OR [Object] = 'OFFSETS'
  10279. OR [Object] LIKE '% OLD %' OR [Object] LIKE '% OLD' OR [Object] = 'OLD'
  10280. OR [Object] LIKE '% ON %' OR [Object] LIKE '% ON' OR [Object] = 'ON'
  10281. OR [Object] LIKE '% ONLY %' OR [Object] LIKE '% ONLY' OR [Object] = 'ONLY'
  10282. OR [Object] LIKE '% OPEN %' OR [Object] LIKE '% OPEN' OR [Object] = 'OPEN'
  10283. OR [Object] LIKE '% OPENDATASOURCE %' OR [Object] LIKE '% OPENDATASOURCE' OR [Object] = 'OPENDATASOURCE'
  10284. OR [Object] LIKE '% OPENQUERY %' OR [Object] LIKE '% OPENQUERY' OR [Object] = 'OPENQUERY'
  10285. OR [Object] LIKE '% OPENROWSET %' OR [Object] LIKE '% OPENROWSET' OR [Object] = 'OPENROWSET'
  10286. OR [Object] LIKE '% OPENXML %' OR [Object] LIKE '% OPENXML' OR [Object] = 'OPENXML'
  10287. OR [Object] LIKE '% OPERATION %' OR [Object] LIKE '% OPERATION' OR [Object] = 'OPERATION'
  10288. OR [Object] LIKE '% OPTION %' OR [Object] LIKE '% OPTION' OR [Object] = 'OPTION'
  10289. OR [Object] LIKE '% OR %' OR [Object] LIKE '% OR' OR [Object] = 'OR'
  10290. OR [Object] LIKE '% ORDER %' OR [Object] LIKE '% ORDER' OR [Object] = 'ORDER'
  10291. OR [Object] LIKE '% ORDINALITY %' OR [Object] LIKE '% ORDINALITY' OR [Object] = 'ORDINALITY'
  10292. OR [Object] LIKE '% OUT %' OR [Object] LIKE '% OUT' OR [Object] = 'OUT'
  10293. OR [Object] LIKE '% OUTER %' OR [Object] LIKE '% OUTER' OR [Object] = 'OUTER'
  10294. OR [Object] LIKE '% OUTPUT %' OR [Object] LIKE '% OUTPUT' OR [Object] = 'OUTPUT'
  10295. OR [Object] LIKE '% OVER %' OR [Object] LIKE '% OVER' OR [Object] = 'OVER'
  10296. OR [Object] LIKE '% OVERLAPS %' OR [Object] LIKE '% OVERLAPS' OR [Object] = 'OVERLAPS'
  10297. OR [Object] LIKE '% PAD %' OR [Object] LIKE '% PAD' OR [Object] = 'PAD'
  10298. OR [Object] LIKE '% PARAMETER %' OR [Object] LIKE '% PARAMETER' OR [Object] = 'PARAMETER'
  10299. OR [Object] LIKE '% PARAMETERS %' OR [Object] LIKE '% PARAMETERS' OR [Object] = 'PARAMETERS'
  10300. OR [Object] LIKE '% PARTIAL %' OR [Object] LIKE '% PARTIAL' OR [Object] = 'PARTIAL'
  10301. OR [Object] LIKE '% PASCAL %' OR [Object] LIKE '% PASCAL' OR [Object] = 'PASCAL'
  10302. OR [Object] LIKE '% PATH %' OR [Object] LIKE '% PATH' OR [Object] = 'PATH'
  10303. OR [Object] LIKE '% PERCENT %' OR [Object] LIKE '% PERCENT' OR [Object] = 'PERCENT'
  10304. OR [Object] LIKE '% PLAN %' OR [Object] LIKE '% PLAN' OR [Object] = 'PLAN'
  10305. OR [Object] LIKE '% POSITION %' OR [Object] LIKE '% POSITION' OR [Object] = 'POSITION'
  10306. OR [Object] LIKE '% POSTFIX %' OR [Object] LIKE '% POSTFIX' OR [Object] = 'POSTFIX'
  10307. OR [Object] LIKE '% PRECISION %' OR [Object] LIKE '% PRECISION' OR [Object] = 'PRECISION'
  10308. OR [Object] LIKE '% PREFIX %' OR [Object] LIKE '% PREFIX' OR [Object] = 'PREFIX'
  10309. OR [Object] LIKE '% PREORDER %' OR [Object] LIKE '% PREORDER' OR [Object] = 'PREORDER'
  10310. OR [Object] LIKE '% PREPARE %' OR [Object] LIKE '% PREPARE' OR [Object] = 'PREPARE'
  10311. OR [Object] LIKE '% PRESERVE %' OR [Object] LIKE '% PRESERVE' OR [Object] = 'PRESERVE'
  10312. OR [Object] LIKE '% PRIMARY %' OR [Object] LIKE '% PRIMARY' OR [Object] = 'PRIMARY'
  10313. OR [Object] LIKE '% PRINT %' OR [Object] LIKE '% PRINT' OR [Object] = 'PRINT'
  10314. OR [Object] LIKE '% PRIOR %' OR [Object] LIKE '% PRIOR' OR [Object] = 'PRIOR'
  10315. OR [Object] LIKE '% PRIVILEGES %' OR [Object] LIKE '% PRIVILEGES' OR [Object] = 'PRIVILEGES'
  10316. OR [Object] LIKE '% PROC %' OR [Object] LIKE '% PROC' OR [Object] = 'PROC'
  10317. OR [Object] LIKE '% PROCEDURE %' OR [Object] LIKE '% PROCEDURE' OR [Object] = 'PROCEDURE'
  10318. OR [Object] LIKE '% PUBLIC %' OR [Object] LIKE '% PUBLIC' OR [Object] = 'PUBLIC'
  10319. OR [Object] LIKE '% RAISERROR %' OR [Object] LIKE '% RAISERROR' OR [Object] = 'RAISERROR'
  10320. OR [Object] LIKE '% READ %' OR [Object] LIKE '% READ' OR [Object] = 'READ'
  10321. OR [Object] LIKE '% READS %' OR [Object] LIKE '% READS' OR [Object] = 'READS'
  10322. OR [Object] LIKE '% READTEXT %' OR [Object] LIKE '% READTEXT' OR [Object] = 'READTEXT'
  10323. OR [Object] LIKE '% REAL %' OR [Object] LIKE '% REAL' OR [Object] = 'REAL'
  10324. OR [Object] LIKE '% RECONFIGURE %' OR [Object] LIKE '% RECONFIGURE' OR [Object] = 'RECONFIGURE'
  10325. OR [Object] LIKE '% RECURSIVE %' OR [Object] LIKE '% RECURSIVE' OR [Object] = 'RECURSIVE'
  10326. OR [Object] LIKE '% REF %' OR [Object] LIKE '% REF' OR [Object] = 'REF'
  10327. OR [Object] LIKE '% REFERENCES %' OR [Object] LIKE '% REFERENCES' OR [Object] = 'REFERENCES'
  10328. OR [Object] LIKE '% REFERENCING %' OR [Object] LIKE '% REFERENCING' OR [Object] = 'REFERENCING'
  10329. OR [Object] LIKE '% RELATIVE %' OR [Object] LIKE '% RELATIVE' OR [Object] = 'RELATIVE'
  10330. OR [Object] LIKE '% REPLICATION %' OR [Object] LIKE '% REPLICATION' OR [Object] = 'REPLICATION'
  10331. OR [Object] LIKE '% RESTORE %' OR [Object] LIKE '% RESTORE' OR [Object] = 'RESTORE'
  10332. OR [Object] LIKE '% RESTRICT %' OR [Object] LIKE '% RESTRICT' OR [Object] = 'RESTRICT'
  10333. OR [Object] LIKE '% RESULT %' OR [Object] LIKE '% RESULT' OR [Object] = 'RESULT'
  10334. OR [Object] LIKE '% RETURN %' OR [Object] LIKE '% RETURN' OR [Object] = 'RETURN'
  10335. OR [Object] LIKE '% RETURNS %' OR [Object] LIKE '% RETURNS' OR [Object] = 'RETURNS'
  10336. OR [Object] LIKE '% REVOKE %' OR [Object] LIKE '% REVOKE' OR [Object] = 'REVOKE'
  10337. OR [Object] LIKE '% RIGHT %' OR [Object] LIKE '% RIGHT' OR [Object] = 'RIGHT'
  10338. OR [Object] LIKE '% ROLE %' OR [Object] LIKE '% ROLE' OR [Object] = 'ROLE'
  10339. OR [Object] LIKE '% ROLLBACK %' OR [Object] LIKE '% ROLLBACK' OR [Object] = 'ROLLBACK'
  10340. OR [Object] LIKE '% ROLLUP %' OR [Object] LIKE '% ROLLUP' OR [Object] = 'ROLLUP'
  10341. OR [Object] LIKE '% ROUTINE %' OR [Object] LIKE '% ROUTINE' OR [Object] = 'ROUTINE'
  10342. OR [Object] LIKE '% ROW %' OR [Object] LIKE '% ROW' OR [Object] = 'ROW'
  10343. OR [Object] LIKE '% ROWCOUNT %' OR [Object] LIKE '% ROWCOUNT' OR [Object] = 'ROWCOUNT'
  10344. OR [Object] LIKE '% ROWGUIDCOL %' OR [Object] LIKE '% ROWGUIDCOL' OR [Object] = 'ROWGUIDCOL'
  10345. OR [Object] LIKE '% ROWS %' OR [Object] LIKE '% ROWS' OR [Object] = 'ROWS'
  10346. OR [Object] LIKE '% RULE %' OR [Object] LIKE '% RULE' OR [Object] = 'RULE'
  10347. OR [Object] LIKE '% SAVE %' OR [Object] LIKE '% SAVE' OR [Object] = 'SAVE'
  10348. OR [Object] LIKE '% SAVEPOINT %' OR [Object] LIKE '% SAVEPOINT' OR [Object] = 'SAVEPOINT'
  10349. OR [Object] LIKE '% SCHEMA %' OR [Object] LIKE '% SCHEMA' OR [Object] = 'SCHEMA'
  10350. OR [Object] LIKE '% SCOPE %' OR [Object] LIKE '% SCOPE' OR [Object] = 'SCOPE'
  10351. OR [Object] LIKE '% SCROLL %' OR [Object] LIKE '% SCROLL' OR [Object] = 'SCROLL'
  10352. OR [Object] LIKE '% SEARCH %' OR [Object] LIKE '% SEARCH' OR [Object] = 'SEARCH'
  10353. OR [Object] LIKE '% SECOND %' OR [Object] LIKE '% SECOND' OR [Object] = 'SECOND'
  10354. OR [Object] LIKE '% SECTION %' OR [Object] LIKE '% SECTION' OR [Object] = 'SECTION'
  10355. OR [Object] LIKE '% SELECT %' OR [Object] LIKE '% SELECT' OR [Object] = 'SELECT'
  10356. OR [Object] LIKE '% SEQUENCE %' OR [Object] LIKE '% SEQUENCE' OR [Object] = 'SEQUENCE'
  10357. OR [Object] LIKE '% SESSION %' OR [Object] LIKE '% SESSION' OR [Object] = 'SESSION'
  10358. OR [Object] LIKE '% SESSION_USER %' OR [Object] LIKE '% SESSION_USER' OR [Object] = 'SESSION_USER'
  10359. OR [Object] LIKE '% SET %' OR [Object] LIKE '% SET' OR [Object] = 'SET'
  10360. OR [Object] LIKE '% SETS %' OR [Object] LIKE '% SETS' OR [Object] = 'SETS'
  10361. OR [Object] LIKE '% SETUSER %' OR [Object] LIKE '% SETUSER' OR [Object] = 'SETUSER'
  10362. OR [Object] LIKE '% SHUTDOWN %' OR [Object] LIKE '% SHUTDOWN' OR [Object] = 'SHUTDOWN'
  10363. OR [Object] LIKE '% SIZE %' OR [Object] LIKE '% SIZE' OR [Object] = 'SIZE'
  10364. OR [Object] LIKE '% SMALLINT %' OR [Object] LIKE '% SMALLINT' OR [Object] = 'SMALLINT'
  10365. OR [Object] LIKE '% SOME %' OR [Object] LIKE '% SOME' OR [Object] = 'SOME'
  10366. OR [Object] LIKE '% SPACE %' OR [Object] LIKE '% SPACE' OR [Object] = 'SPACE'
  10367. OR [Object] LIKE '% SPECIFIC %' OR [Object] LIKE '% SPECIFIC' OR [Object] = 'SPECIFIC'
  10368. OR [Object] LIKE '% SPECIFICTYPE %' OR [Object] LIKE '% SPECIFICTYPE' OR [Object] = 'SPECIFICTYPE'
  10369. OR [Object] LIKE '% SQL %' OR [Object] LIKE '% SQL' OR [Object] = 'SQL'
  10370. OR [Object] LIKE '% SQLCA %' OR [Object] LIKE '% SQLCA' OR [Object] = 'SQLCA'
  10371. OR [Object] LIKE '% SQLCODE %' OR [Object] LIKE '% SQLCODE' OR [Object] = 'SQLCODE'
  10372. OR [Object] LIKE '% SQLERROR %' OR [Object] LIKE '% SQLERROR' OR [Object] = 'SQLERROR'
  10373. OR [Object] LIKE '% SQLEXCEPTION %' OR [Object] LIKE '% SQLEXCEPTION' OR [Object] = 'SQLEXCEPTION'
  10374. OR [Object] LIKE '% SQLSTATE %' OR [Object] LIKE '% SQLSTATE' OR [Object] = 'SQLSTATE'
  10375. OR [Object] LIKE '% SQLWARNING %' OR [Object] LIKE '% SQLWARNING' OR [Object] = 'SQLWARNING'
  10376. OR [Object] LIKE '% START %' OR [Object] LIKE '% START' OR [Object] = 'START'
  10377. OR [Object] LIKE '% STATE %' OR [Object] LIKE '% STATE' OR [Object] = 'STATE'
  10378. OR [Object] LIKE '% STATEMENT %' OR [Object] LIKE '% STATEMENT' OR [Object] = 'STATEMENT'
  10379. OR [Object] LIKE '% STATIC %' OR [Object] LIKE '% STATIC' OR [Object] = 'STATIC'
  10380. OR [Object] LIKE '% STATISTICS %' OR [Object] LIKE '% STATISTICS' OR [Object] = 'STATISTICS'
  10381. OR [Object] LIKE '% STRUCTURE %' OR [Object] LIKE '% STRUCTURE' OR [Object] = 'STRUCTURE'
  10382. OR [Object] LIKE '% SUBSTRING %' OR [Object] LIKE '% SUBSTRING' OR [Object] = 'SUBSTRING'
  10383. OR [Object] LIKE '% SUM %' OR [Object] LIKE '% SUM' OR [Object] = 'SUM'
  10384. OR [Object] LIKE '% SYSTEM_USER %' OR [Object] LIKE '% SYSTEM_USER' OR [Object] = 'SYSTEM_USER'
  10385. OR [Object] LIKE '% TABLE %' OR [Object] LIKE '% TABLE' OR [Object] = 'TABLE'
  10386. OR [Object] LIKE '% TEMPORARY %' OR [Object] LIKE '% TEMPORARY' OR [Object] = 'TEMPORARY'
  10387. OR [Object] LIKE '% TERMINATE %' OR [Object] LIKE '% TERMINATE' OR [Object] = 'TERMINATE'
  10388. OR [Object] LIKE '% TEXTSIZE %' OR [Object] LIKE '% TEXTSIZE' OR [Object] = 'TEXTSIZE'
  10389. OR [Object] LIKE '% THAN %' OR [Object] LIKE '% THAN' OR [Object] = 'THAN'
  10390. OR [Object] LIKE '% THEN %' OR [Object] LIKE '% THEN' OR [Object] = 'THEN'
  10391. OR [Object] LIKE '% TIME %' OR [Object] LIKE '% TIME' OR [Object] = 'TIME'
  10392. OR [Object] LIKE '% TIMESTAMP %' OR [Object] LIKE '% TIMESTAMP' OR [Object] = 'TIMESTAMP'
  10393. OR [Object] LIKE '% TIMEZONE_HOUR %' OR [Object] LIKE '% TIMEZONE_HOUR' OR [Object] = 'TIMEZONE_HOUR'
  10394. OR [Object] LIKE '% TIMEZONE_MINUTE %' OR [Object] LIKE '% TIMEZONE_MINUTE' OR [Object] = 'TIMEZONE_MINUTE'
  10395. OR [Object] LIKE '% TO %' OR [Object] LIKE '% TO' OR [Object] = 'TO'
  10396. OR [Object] LIKE '% TOP %' OR [Object] LIKE '% TOP' OR [Object] = 'TOP'
  10397. OR [Object] LIKE '% TRAILING %' OR [Object] LIKE '% TRAILING' OR [Object] = 'TRAILING'
  10398. OR [Object] LIKE '% TRAN %' OR [Object] LIKE '% TRAN' OR [Object] = 'TRAN'
  10399. OR [Object] LIKE '% TRANSACTION %' OR [Object] LIKE '% TRANSACTION' OR [Object] = 'TRANSACTION'
  10400. OR [Object] LIKE '% TRANSLATE %' OR [Object] LIKE '% TRANSLATE' OR [Object] = 'TRANSLATE'
  10401. OR [Object] LIKE '% TRANSLATION %' OR [Object] LIKE '% TRANSLATION' OR [Object] = 'TRANSLATION'
  10402. OR [Object] LIKE '% TREAT %' OR [Object] LIKE '% TREAT' OR [Object] = 'TREAT'
  10403. OR [Object] LIKE '% TRIGGER %' OR [Object] LIKE '% TRIGGER' OR [Object] = 'TRIGGER'
  10404. OR [Object] LIKE '% TRIM %' OR [Object] LIKE '% TRIM' OR [Object] = 'TRIM'
  10405. OR [Object] LIKE '% TRUE %' OR [Object] LIKE '% TRUE' OR [Object] = 'TRUE'
  10406. OR [Object] LIKE '% TRUNCATE %' OR [Object] LIKE '% TRUNCATE' OR [Object] = 'TRUNCATE'
  10407. OR [Object] LIKE '% UNDER %' OR [Object] LIKE '% UNDER' OR [Object] = 'UNDER'
  10408. OR [Object] LIKE '% UNION %' OR [Object] LIKE '% UNION' OR [Object] = 'UNION'
  10409. OR [Object] LIKE '% UNIQUE %' OR [Object] LIKE '% UNIQUE' OR [Object] = 'UNIQUE'
  10410. OR [Object] LIKE '% UNKNOWN %' OR [Object] LIKE '% UNKNOWN' OR [Object] = 'UNKNOWN'
  10411. OR [Object] LIKE '% UNNEST %' OR [Object] LIKE '% UNNEST' OR [Object] = 'UNNEST'
  10412. OR [Object] LIKE '% UPDATE %' OR [Object] LIKE '% UPDATE' OR [Object] = 'UPDATE'
  10413. OR [Object] LIKE '% UPDATETEXT %' OR [Object] LIKE '% UPDATETEXT' OR [Object] = 'UPDATETEXT'
  10414. OR [Object] LIKE '% UPPER %' OR [Object] LIKE '% UPPER' OR [Object] = 'UPPER'
  10415. OR [Object] LIKE '% USAGE %' OR [Object] LIKE '% USAGE' OR [Object] = 'USAGE'
  10416. OR [Object] LIKE '% USE %' OR [Object] LIKE '% USE' OR [Object] = 'USE'
  10417. OR [Object] LIKE '% USER %' OR [Object] LIKE '% USER' OR [Object] = 'USER'
  10418. OR [Object] LIKE '% USING %' OR [Object] LIKE '% USING' OR [Object] = 'USING'
  10419. OR [Object] LIKE '% VALUE %' OR [Object] LIKE '% VALUE' OR [Object] = 'VALUE'
  10420. OR [Object] LIKE '% VALUES %' OR [Object] LIKE '% VALUES' OR [Object] = 'VALUES'
  10421. OR [Object] LIKE '% VARCHAR %' OR [Object] LIKE '% VARCHAR' OR [Object] = 'VARCHAR'
  10422. OR [Object] LIKE '% VARIABLE %' OR [Object] LIKE '% VARIABLE' OR [Object] = 'VARIABLE'
  10423. OR [Object] LIKE '% VARYING %' OR [Object] LIKE '% VARYING' OR [Object] = 'VARYING'
  10424. OR [Object] LIKE '% VIEW %' OR [Object] LIKE '% VIEW' OR [Object] = 'VIEW'
  10425. OR [Object] LIKE '% WAITFOR %' OR [Object] LIKE '% WAITFOR' OR [Object] = 'WAITFOR'
  10426. OR [Object] LIKE '% WHEN %' OR [Object] LIKE '% WHEN' OR [Object] = 'WHEN'
  10427. OR [Object] LIKE '% WHENEVER %' OR [Object] LIKE '% WHENEVER' OR [Object] = 'WHENEVER'
  10428. OR [Object] LIKE '% WHERE %' OR [Object] LIKE '% WHERE' OR [Object] = 'WHERE'
  10429. OR [Object] LIKE '% WHILE %' OR [Object] LIKE '% WHILE' OR [Object] = 'WHILE'
  10430. OR [Object] LIKE '% WITH %' OR [Object] LIKE '% WITH' OR [Object] = 'WITH'
  10431. OR [Object] LIKE '% WITHOUT %' OR [Object] LIKE '% WITHOUT' OR [Object] = 'WITHOUT'
  10432. OR [Object] LIKE '% WORK %' OR [Object] LIKE '% WORK' OR [Object] = 'WORK'
  10433. OR [Object] LIKE '% WRITE %' OR [Object] LIKE '% WRITE' OR [Object] = 'WRITE'
  10434. OR [Object] LIKE '% WRITETEXT %' OR [Object] LIKE '% WRITETEXT' OR [Object] = 'WRITETEXT'
  10435. OR [Object] LIKE '% YEAR %' OR [Object] LIKE '% YEAR' OR [Object] = 'YEAR'
  10436. OR [Object] LIKE '% ZONE %' OR [Object] LIKE '% ZONE' OR [Object] = 'ZONE');
  10437. /* http://msdn.microsoft.com/en-us/library/ms186755.aspx */
  10438. INSERT INTO #tmpfinalobjectnames
  10439. SELECT 5, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10440. FROM #tmpobjectnames
  10441. WHERE [type] IN ('FN','FS','TF','IF') AND [Object] LIKE 'fn[_]%'
  10442. AND [Object] NOT IN ('fn_diagram_objects');
  10443. IF (SELECT COUNT(*) FROM #tmpfinalobjectnames) > 0
  10444. BEGIN
  10445. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check], '[WARNING: Reserved words or special characters have been found in object names]' AS [Deviation]
  10446. END
  10447. ELSE
  10448. BEGIN
  10449. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check], '[OK]' AS [Deviation]
  10450. END;
  10451. IF (SELECT COUNT(*) FROM #tmpfinalobjectnames) > 0
  10452. BEGIN
  10453. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check],
  10454. CASE [Deviation] WHEN 1 THEN '[sp_ as prefix for stored procedures]'
  10455. WHEN 2 THEN '[Special character as part of object name]'
  10456. WHEN 3 THEN '[Special character as part of column name]'
  10457. WHEN 4 THEN '[Reserved words as part of object name]'
  10458. WHEN 5 THEN '[fn_ as prefix for user defined functions]'
  10459. END AS [Deviation],
  10460. [DBName] AS [Database_Name], [schemaName] AS [Schema_Name], [Object] AS [Object_Name], QUOTENAME([Col]) AS [Col], [type_desc] AS [Object_Type]
  10461. FROM #tmpfinalobjectnames
  10462. ORDER BY [Deviation], type_desc, [DBName], [schemaName], [Object];
  10463. END;
  10464. RAISERROR (N'|-Starting Security Checks', 10, 1) WITH NOWAIT
  10465. --------------------------------------------------------------------------------------------------------------------------------
  10466. -- Password check subsection
  10467. --------------------------------------------------------------------------------------------------------------------------------
  10468. RAISERROR (N' |-Starting Password check', 10, 1) WITH NOWAIT
  10469. DECLARE @passwords TABLE ([Deviation] VARCHAR(15), [Name] sysname, [CreateDate] DATETIME)
  10470. DECLARE @word TABLE (word NVARCHAR(50))
  10471. INSERT INTO @word values (0)
  10472. INSERT INTO @word values (1)
  10473. INSERT INTO @word values (12)
  10474. INSERT INTO @word values (123)
  10475. INSERT INTO @word values (1234)
  10476. INSERT INTO @word values (12345)
  10477. INSERT INTO @word values (123456)
  10478. INSERT INTO @word values (1234567)
  10479. INSERT INTO @word values (12345678)
  10480. INSERT INTO @word values (123456789)
  10481. INSERT INTO @word values (1234567890)
  10482. INSERT INTO @word values (11111)
  10483. INSERT INTO @word values (111111)
  10484. INSERT INTO @word values (1111111)
  10485. INSERT INTO @word values (11111111)
  10486. INSERT INTO @word values (21)
  10487. INSERT INTO @word values (321)
  10488. INSERT INTO @word values (4321)
  10489. INSERT INTO @word values (54321)
  10490. INSERT INTO @word values (654321)
  10491. INSERT INTO @word values (7654321)
  10492. INSERT INTO @word values (87654321)
  10493. INSERT INTO @word values (987654321)
  10494. INSERT INTO @word values (0987654321)
  10495. INSERT INTO @word values ('pwd')
  10496. INSERT INTO @word values ('Password')
  10497. INSERT INTO @word values ('password')
  10498. INSERT INTO @word values ('P@ssw0rd')
  10499. INSERT INTO @word values ('p@ssw0rd')
  10500. INSERT INTO @word values ('Teste')
  10501. INSERT INTO @word values ('teste')
  10502. INSERT INTO @word values ('Test')
  10503. INSERT INTO @word values ('test')
  10504. INSERT INTO @word values ('')
  10505. INSERT INTO @word values ('p@wd')
  10506. INSERT INTO @passwords
  10507. SELECT DISTINCT 'Weak_Password' AS Deviation, RTRIM(s.name) AS [Name], createdate AS [CreateDate]
  10508. FROM @word d
  10509. INNER JOIN master.sys.syslogins s ON PWDCOMPARE(RTRIM(RTRIM(d.word)), s.[password]) = 1
  10510. UNION ALL
  10511. SELECT 'NULL_Passwords' AS Deviation, RTRIM(name) AS [Name], createdate AS [CreateDate]
  10512. FROM master.sys.syslogins
  10513. WHERE [password] IS NULL
  10514. AND isntname = 0
  10515. AND name NOT IN ('MSCRMSqlClrLogin','##MS_SmoExtendedSigningCertificate##','##MS_PolicySigningCertificate##','##MS_SQLResourceSigningCertificate##','##MS_SQLReplicationSigningCertificate##','##MS_SQLAuthenticatorCertificate##','##MS_AgentSigningCertificate##','##MS_SQLEnableSystemAssemblyLoadingUser##')
  10516. UNION ALL
  10517. SELECT DISTINCT 'Name=Password' AS Deviation, RTRIM(s.name) AS [Name], createdate AS [CreateDate]
  10518. FROM master.sys.syslogins s
  10519. WHERE PWDCOMPARE(RTRIM(RTRIM(s.name)), s.[password]) = 1
  10520. ORDER BY [Deviation], [Name]
  10521. IF (SELECT COUNT([Deviation]) FROM @passwords) > 0
  10522. BEGIN
  10523. 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]
  10524. SELECT 'Security_checks' AS [Category], 'Password_checks' AS [Information], [Deviation], [Name], [CreateDate]
  10525. FROM @passwords
  10526. ORDER BY [Deviation], [Name]
  10527. END
  10528. ELSE
  10529. BEGIN
  10530. SELECT 'Security_checks' AS [Category], 'Password_checks' AS [Check], '[OK]' AS [Deviation]
  10531. END;
  10532. RAISERROR (N'|-Starting Maintenance and Monitoring Checks', 10, 1) WITH NOWAIT
  10533. --------------------------------------------------------------------------------------------------------------------------------
  10534. -- SQL Agent alerts for severe errors subsection
  10535. --------------------------------------------------------------------------------------------------------------------------------
  10536. RAISERROR (N' |-Starting SQL Agent alerts for severe errors', 10, 1) WITH NOWAIT
  10537. IF (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 1) = 0 AND (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 2) = 0
  10538. BEGIN
  10539. 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')
  10540. --RETURN
  10541. END
  10542. ELSE
  10543. BEGIN
  10544. 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]
  10545. FROM msdb.dbo.sysalerts
  10546. WHERE [message_id] IN (825,833,855,856,3452,3619,17179,17883,17884,17887,17888,17890,28036) OR severity = 10
  10547. UNION ALL
  10548. 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]
  10549. FROM msdb.dbo.sysalerts
  10550. WHERE [message_id] IN (610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300) OR severity = 16
  10551. UNION ALL
  10552. 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]
  10553. FROM msdb.dbo.sysalerts
  10554. WHERE [message_id] IN (802,845,1101,1105,1121,1214,8642,9002) OR severity = 17
  10555. UNION ALL
  10556. 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]
  10557. FROM msdb.dbo.sysalerts
  10558. WHERE [message_id] IN (701) OR severity = 19
  10559. UNION ALL
  10560. 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]
  10561. FROM msdb.dbo.sysalerts
  10562. WHERE [message_id] IN (3624) OR severity = 20
  10563. UNION ALL
  10564. 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]
  10565. FROM msdb.dbo.sysalerts
  10566. WHERE [message_id] IN (605) OR severity = 21
  10567. UNION ALL
  10568. 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]
  10569. FROM msdb.dbo.sysalerts
  10570. WHERE [message_id] IN (5180,8966) OR severity = 22
  10571. UNION ALL
  10572. 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]
  10573. FROM msdb.dbo.sysalerts
  10574. WHERE [message_id] IN (5572,9100) OR severity = 23
  10575. UNION ALL
  10576. 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]
  10577. FROM msdb.dbo.sysalerts
  10578. WHERE [message_id] IN (823,824,832) OR severity = 24
  10579. 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
  10580. 610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300, -- Sev 16
  10581. 802,845,1101,1105,1121,1214,8642,9002, -- Sev 17
  10582. 701, -- Sev 19
  10583. 3624, -- Sev 20
  10584. 605, -- Sev 21
  10585. 5180,8966, -- Sev 22
  10586. 5572,9100, -- Sev 23
  10587. 823,824,832 -- Sev 24
  10588. ) OR [severity] >= 17)) > 0
  10589. BEGIN
  10590. 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]
  10591. FROM msdb.dbo.sysalerts
  10592. WHERE ([message_id] IN (825,833,855,856,3452,3619,17179,17883,17884,17887,17888,17890,28036, -- Sev 10
  10593. 610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300, -- Sev 16
  10594. 802,845,1101,1105,1121,1214,8642,9002, -- Sev 17
  10595. 701, -- Sev 19
  10596. 3624, -- Sev 20
  10597. 605, -- Sev 21
  10598. 5180,8966, -- Sev 22
  10599. 5572,9100, -- Sev 23
  10600. 823,824,832 -- Sev 24
  10601. ) OR [severity] >= 17);
  10602. END
  10603. END;
  10604. --------------------------------------------------------------------------------------------------------------------------------
  10605. -- DBCC CHECKDB, Direct Catalog Updates and Data Purity subsection
  10606. --------------------------------------------------------------------------------------------------------------------------------
  10607. RAISERROR (N' |-Starting DBCC CHECKDB, Direct Catalog Updates and Data Purity', 10, 1) WITH NOWAIT
  10608. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  10609. DROP TABLE #output_dbinfo;
  10610. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  10611. CREATE TABLE #output_dbinfo (ParentObject VARCHAR(255), [Object] VARCHAR(255), Field VARCHAR(255), [value] VARCHAR(255))
  10612. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  10613. DROP TABLE #dbinfo;
  10614. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  10615. 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)
  10616. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1)
  10617. BEGIN
  10618. --DECLARE @dbname NVARCHAR(255);
  10619. DECLARE @dbcc bit, @catupd bit, @purity bit;
  10620. DECLARE curDBs CURSOR FAST_FORWARD FOR SELECT name FROM master.sys.databases (NOLOCK) WHERE is_read_only = 0 AND [state] = 0
  10621. OPEN curDBs
  10622. FETCH NEXT FROM curDBs INTO @dbname
  10623. WHILE (@@FETCH_STATUS = 0)
  10624. BEGIN
  10625. SET @dbname = RTRIM(LTRIM(@dbname))
  10626. INSERT INTO #output_dbinfo
  10627. EXEC('DBCC DBINFO(''' + @dbname + ''') WITH TABLERESULTS, NO_INFOMSGS')
  10628. INSERT INTO #dbinfo (dbname, lst_known_checkdb)
  10629. SELECT @dbname, [value] FROM #output_dbinfo WHERE Field LIKE 'dbi_dbccLastKnownGood%';
  10630. UPDATE #dbinfo
  10631. SET #dbinfo.updSysCatalog = #output_dbinfo.[value]
  10632. FROM #output_dbinfo
  10633. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_updSysCatalog%';
  10634. UPDATE #dbinfo
  10635. SET #dbinfo.dbi_createVersion = #output_dbinfo.[value]
  10636. FROM #output_dbinfo
  10637. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_createVersion%';
  10638. UPDATE #dbinfo
  10639. SET #dbinfo.dbi_dbccFlags = #output_dbinfo.[value]
  10640. FROM #output_dbinfo
  10641. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_dbccFlags%';
  10642. TRUNCATE TABLE #output_dbinfo;
  10643. FETCH NEXT FROM curDBs INTO @dbname
  10644. END
  10645. CLOSE curDBs
  10646. DEALLOCATE curDBs;
  10647. ;WITH cte_dbcc (name, lst_known_checkdb) AS (SELECT sd.name, tmpdbi.lst_known_checkdb
  10648. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10649. WHERE sd.database_id <> 2 AND is_read_only = 0 AND [state] = 0)
  10650. SELECT @dbcc = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10651. FROM cte_dbcc WHERE DATEDIFF(dd, lst_known_checkdb, GETDATE()) > 7 OR lst_known_checkdb IS NULL;
  10652. ;WITH cte_catupd (name, updSysCatalog) AS (SELECT sd.name, tmpdbi.updSysCatalog
  10653. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10654. WHERE sd.database_id <> 2 AND is_read_only = 0 AND [state] = 0)
  10655. SELECT @catupd = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10656. FROM cte_catupd WHERE updSysCatalog > '1900-01-01 00:00:00.000';
  10657. ;WITH cte_purity (name, dbi_createVersion, dbi_dbccFlags) AS (SELECT sd.name, tmpdbi.dbi_createVersion, tmpdbi.dbi_dbccFlags
  10658. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10659. WHERE sd.database_id > 4 AND is_read_only = 0 AND [state] = 0)
  10660. SELECT @purity = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10661. FROM cte_purity WHERE dbi_createVersion <= 611 AND dbi_dbccFlags = 0; -- <= SQL Server 2005
  10662. IF @dbcc = 1
  10663. BEGIN
  10664. 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]
  10665. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'DBCC_CHECKDB' AS [Information], [name] AS [Database_Name], MAX(lst_known_checkdb) AS Last_Known_CHECKDB
  10666. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10667. WHERE database_id <> 2 AND is_read_only = 0 AND [state] = 0
  10668. GROUP BY [name]
  10669. HAVING DATEDIFF(dd, MAX(lst_known_checkdb), GETDATE()) > 7 OR MAX(lst_known_checkdb) IS NULL
  10670. ORDER BY [name]
  10671. END
  10672. ELSE
  10673. BEGIN
  10674. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'DBCC_CHECKDB' AS [Check], '[OK]' AS [Deviation]
  10675. END;
  10676. IF @catupd = 1
  10677. BEGIN
  10678. SELECT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Check], '[WARNING: Microsoft does not support direct catalog updates to databases.]' AS [Deviation]
  10679. SELECT DISTINCT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Information], [name] AS [Database_Name], MAX(updSysCatalog) AS Last_Direct_Catalog_Update
  10680. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10681. WHERE database_id <> 2 AND is_read_only = 0 AND [state] = 0
  10682. GROUP BY [name]
  10683. HAVING (MAX(updSysCatalog) > '1900-01-01 00:00:00.000')
  10684. ORDER BY [name]
  10685. END
  10686. ELSE
  10687. BEGIN
  10688. SELECT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Check], '[OK]' AS [Deviation]
  10689. END;
  10690. -- http://support.microsoft.com/kb/923247/en-us
  10691. -- http://www.sqlskills.com/blogs/paul/checkdb-from-every-angle-how-to-tell-if-data-purity-checks-will-be-run
  10692. IF @purity = 1
  10693. BEGIN
  10694. 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]
  10695. 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
  10696. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10697. WHERE database_id > 4 AND dbi_createVersion <= 611 AND dbi_dbccFlags = 0 AND is_read_only = 0 AND [state] = 0
  10698. ORDER BY [name]
  10699. END
  10700. ELSE
  10701. BEGIN
  10702. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Databases_need_data_purity_check' AS [Check], '[OK]' AS [Deviation]
  10703. END;
  10704. END
  10705. ELSE
  10706. BEGIN
  10707. RAISERROR('[WARNING: Only a sysadmin can run the "DBCC CHECKDB, Direct Catalog Updates and Data Purity" checks. Bypassing check]', 16, 1, N'sysadmin')
  10708. --RETURN
  10709. END;
  10710. --------------------------------------------------------------------------------------------------------------------------------
  10711. -- AlwaysOn/Mirroring automatic page repair subsection
  10712. -- Refer to "Automatic Page Repair" BOL entry for more information (http://msdn.microsoft.com/en-us/library/bb677167.aspx)
  10713. --------------------------------------------------------------------------------------------------------------------------------
  10714. IF @sqlmajorver > 9
  10715. BEGIN
  10716. RAISERROR (N' |-Starting AlwaysOn/Mirroring automatic page repair', 10, 1) WITH NOWAIT
  10717. IF @sqlmajorver > 10
  10718. BEGIN
  10719. DECLARE @HadrRep int--, @sqlcmd NVARCHAR(4000), @params NVARCHAR(500)
  10720. SET @sqlcmd = N'SELECT @HadrRepOUT = COUNT(*) FROM sys.dm_hadr_auto_page_repair';
  10721. SET @params = N'@HadrRepOUT int OUTPUT';
  10722. EXECUTE sp_executesql @sqlcmd, @params, @HadrRepOUT=@HadrRep OUTPUT;
  10723. END
  10724. ELSE
  10725. BEGIN
  10726. SET @HadrRep = 0
  10727. END;
  10728. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  10729. DROP TABLE #pagerepair;
  10730. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  10731. 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)
  10732. IF (SELECT COUNT(*) FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)) > 0
  10733. BEGIN
  10734. INSERT INTO #pagerepair
  10735. SELECT DB_NAME(database_id) AS [Database_Name], [file_id], [page_id], [error_type], page_status, MAX(modification_time), 'Mirroring' AS [Repair_Source]
  10736. FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)
  10737. GROUP BY database_id, [file_id], [page_id], [error_type], page_status
  10738. END
  10739. IF @HadrRep > 0
  10740. BEGIN
  10741. INSERT INTO #pagerepair
  10742. 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]')
  10743. END;
  10744. IF (SELECT COUNT(*) FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)) > 0
  10745. OR @HadrRep > 0
  10746. BEGIN
  10747. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Check], '[WARNING: Page repairs have been found. Check for suspect pages]' AS [Deviation]
  10748. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Information], dbname AS [Database_Name],
  10749. [file_id] AS [File_ID],
  10750. [page_id] AS [Page_ID],
  10751. CASE [error_type]
  10752. WHEN -1 THEN 'Error 823'
  10753. WHEN 1 THEN 'Unspecified Error 824'
  10754. WHEN 2 THEN 'Bad Checksum'
  10755. WHEN 3 THEN 'Torn Page'
  10756. ELSE NULL
  10757. END AS [Error_Type],
  10758. CASE page_status
  10759. WHEN 2 THEN 'Queued for request from partner'
  10760. WHEN 3 THEN 'Request sent to partner'
  10761. WHEN 4 THEN 'Queued for automatic page repair'
  10762. WHEN 5 THEN 'Automatic page repair succeeded'
  10763. WHEN 6 THEN 'Irreparable'
  10764. END AS [Page_Status],
  10765. lst_modification_time AS [Last_Modification_Time], [Repair_Source]
  10766. FROM #pagerepair
  10767. END
  10768. ELSE
  10769. BEGIN
  10770. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Check], '[None]' AS [Deviation], '' AS [Source]
  10771. END
  10772. END;
  10773. --------------------------------------------------------------------------------------------------------------------------------
  10774. -- Suspect pages subsection
  10775. -- Refer to "Manage the suspect_pages Table" BOL entry for more information (http://msdn.microsoft.com/en-us/library/ms191301.aspx)
  10776. --------------------------------------------------------------------------------------------------------------------------------
  10777. RAISERROR (N' |-Starting Suspect pages', 10, 1) WITH NOWAIT
  10778. IF (SELECT COUNT(*) FROM msdb.dbo.suspect_pages WHERE (event_type = 1 OR event_type = 2 OR event_type = 3)) > 0
  10779. BEGIN
  10780. 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]
  10781. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Suspect_Pages' AS [Information], DB_NAME(database_id) AS [Database_Name],
  10782. [file_id] AS [File_ID],
  10783. [page_id] AS [Page_ID],
  10784. CASE event_type
  10785. WHEN 1 THEN 'Error 823 or unspecified Error 824'
  10786. WHEN 2 THEN 'Bad Checksum'
  10787. WHEN 3 THEN 'Torn Page'
  10788. ELSE NULL
  10789. END AS [Event_Type],
  10790. error_count AS [Error_Count],
  10791. last_update_date AS [Last_Update_Date]
  10792. FROM msdb.dbo.suspect_pages (NOLOCK)
  10793. WHERE (event_type = 1 OR event_type = 2 OR event_type = 3)
  10794. ORDER BY DB_NAME(database_id), last_update_date DESC, [file_id], [page_id]
  10795. END
  10796. ELSE
  10797. BEGIN
  10798. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Suspect_Pages' AS [Check], '[None]' AS [Deviation]
  10799. END;
  10800. --------------------------------------------------------------------------------------------------------------------------------
  10801. -- Replication Errors subsection
  10802. --------------------------------------------------------------------------------------------------------------------------------
  10803. IF @replication = 1 AND (SELECT COUNT(*) FROM master.sys.databases (NOLOCK) WHERE [name] = 'distribution') > 0
  10804. BEGIN
  10805. RAISERROR (N' |-Starting Replication Errors', 10, 1) WITH NOWAIT
  10806. IF (SELECT COUNT(*) FROM distribution.dbo.MSdistribution_history AS msh
  10807. INNER JOIN distribution.dbo.MSrepl_errors AS mse ON mse.id = msh.error_id
  10808. INNER JOIN distribution.dbo.MSdistribution_agents AS msa ON msh.agent_id = msa.id
  10809. WHERE mse.time >= DATEADD(hh, - 24, GETDATE())) > 0
  10810. BEGIN
  10811. 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]
  10812. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Lst_24H' AS [Information],
  10813. msa.[name] AS [Distribution_Agent], msa.publisher_db AS [Publisher_DB],
  10814. msa.publication AS [Publication], msa.subscriber_db AS [Subscriber_DB], mse.error_code
  10815. FROM distribution.dbo.MSdistribution_history AS msh
  10816. INNER JOIN distribution.dbo.MSrepl_errors AS mse ON mse.id = msh.error_id
  10817. INNER JOIN distribution.dbo.MSdistribution_agents AS msa ON msh.agent_id = msa.id
  10818. WHERE mse.time >= DATEADD(hh, - 24, GETDATE())
  10819. GROUP BY msa.[name], msa.publisher_db, msa.publication, msa.subscriber_db, mse.error_code
  10820. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Details' AS [Information], msh.time,
  10821. msa.[name] AS [Distribution_Agent], msa.publisher_db AS [Publisher_DB],
  10822. msa.publication AS [Publication], msa.subscriber_db AS [Subscriber_DB],
  10823. mse.error_code, mse.error_text
  10824. FROM distribution.dbo.MSdistribution_history AS msh (NOLOCK)
  10825. INNER JOIN distribution.dbo.MSrepl_errors AS mse (NOLOCK) ON mse.id = msh.error_id AND mse.time = msh.time
  10826. INNER JOIN distribution.dbo.MSdistribution_agents AS msa (NOLOCK) ON msh.agent_id = msa.id
  10827. WHERE (mse.time >= DATEADD(hh, - 24, GETDATE()))
  10828. ORDER BY msh.time
  10829. END
  10830. ELSE
  10831. BEGIN
  10832. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Lst_24H' AS [Check], '[None]' AS [Deviation]
  10833. END
  10834. END;
  10835. --------------------------------------------------------------------------------------------------------------------------------
  10836. -- Errorlog based checks subsection
  10837. -- Because it is a string based search, add other search conditions as deemed fit.
  10838. --------------------------------------------------------------------------------------------------------------------------------
  10839. RAISERROR (N' |-Starting Errorlog based checks', 10, 1) WITH NOWAIT
  10840. --DECLARE @lognumber int, @logcount int
  10841. DECLARE @langid smallint
  10842. SELECT @langid = lcid FROM sys.syslanguages WHERE name = @@LANGUAGE
  10843. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  10844. OR ISNULL(IS_SRVROLEMEMBER(N'securityadmin'), 0) = 1 -- Is securityadmin
  10845. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_readerrorlog') > 0
  10846. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_readerrorlog') > 0
  10847. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_enumerrorlogs') > 0)
  10848. BEGIN
  10849. SET @lognumber = 0
  10850. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10851. DROP TABLE #dbcc;
  10852. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10853. CREATE TABLE #dbcc (rowid int IDENTITY(1,1) PRIMARY KEY, logid int NULL, logdate DATETIME, spid VARCHAR(50), logmsg VARCHAR(4000))
  10854. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10855. CREATE INDEX [dbcc_logmsg] ON dbo.[#dbcc](logid)
  10856. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  10857. DROP TABLE #avail_logs;
  10858. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  10859. CREATE TABLE #avail_logs (lognum int, logdate DATETIME, logsize int)
  10860. -- Get the number of available logs
  10861. INSERT INTO #avail_logs
  10862. EXEC xp_enumerrorlogs
  10863. SELECT @logcount = MAX(lognum) FROM #avail_logs
  10864. WHILE @lognumber < @logcount
  10865. BEGIN
  10866. -- Cycle thru sql error logs
  10867. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''15 seconds'''
  10868. BEGIN TRY
  10869. INSERT INTO #dbcc (logdate, spid, logmsg)
  10870. EXECUTE (@sqlcmd);
  10871. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10872. END TRY
  10873. BEGIN CATCH
  10874. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10875. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  10876. RAISERROR (@ErrorMessage, 16, 1);
  10877. END CATCH
  10878. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''deadlock'''
  10879. BEGIN TRY
  10880. INSERT INTO #dbcc (logdate, spid, logmsg)
  10881. EXECUTE (@sqlcmd);
  10882. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10883. END TRY
  10884. BEGIN CATCH
  10885. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10886. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  10887. RAISERROR (@ErrorMessage, 16, 1);
  10888. END CATCH
  10889. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''stack dump'''
  10890. BEGIN TRY
  10891. INSERT INTO #dbcc (logdate, spid, logmsg)
  10892. EXECUTE (@sqlcmd);
  10893. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10894. END TRY
  10895. BEGIN CATCH
  10896. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10897. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  10898. RAISERROR (@ErrorMessage, 16, 1);
  10899. END CATCH
  10900. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''Error:'''
  10901. BEGIN TRY
  10902. INSERT INTO #dbcc (logdate, spid, logmsg)
  10903. EXECUTE (@sqlcmd);
  10904. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10905. END TRY
  10906. BEGIN CATCH
  10907. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10908. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 4. ' + ERROR_MESSAGE()
  10909. RAISERROR (@ErrorMessage, 16, 1);
  10910. END CATCH
  10911. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''A significant part of sql server process memory has been paged out'''
  10912. BEGIN TRY
  10913. INSERT INTO #dbcc (logdate, spid, logmsg)
  10914. EXECUTE (@sqlcmd);
  10915. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10916. END TRY
  10917. BEGIN CATCH
  10918. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10919. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 5. ' + ERROR_MESSAGE()
  10920. RAISERROR (@ErrorMessage, 16, 1);
  10921. END CATCH
  10922. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''cachestore flush'''
  10923. BEGIN TRY
  10924. INSERT INTO #dbcc (logdate, spid, logmsg)
  10925. EXECUTE (@sqlcmd);
  10926. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10927. END TRY
  10928. BEGIN CATCH
  10929. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10930. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 6. ' + ERROR_MESSAGE()
  10931. RAISERROR (@ErrorMessage, 16, 1);
  10932. END CATCH
  10933. -- Next log
  10934. --SET @lognumber = @lognumber + 1
  10935. SELECT @lognumber = MIN(lognum) FROM #avail_logs WHERE lognum > @lognumber
  10936. END
  10937. IF (SELECT COUNT([rowid]) FROM #dbcc) > 0
  10938. BEGIN
  10939. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog' AS [Check], '[WARNING: Errorlog contains important messages.]' AS [Deviation];
  10940. ;WITH cte_dbcc (err, errcnt, logdate, logmsg)
  10941. AS (SELECT CASE WHEN logmsg LIKE 'Error: %' THEN RIGHT(LEFT(#dbcc.logmsg, CHARINDEX(',', #dbcc.logmsg)-1), CHARINDEX(',', #dbcc.logmsg)-8)
  10942. WHEN logmsg LIKE 'SQL Server has encountered % longer than 15 seconds %' THEN CONVERT(CHAR(3),833)
  10943. WHEN logmsg LIKE 'A significant part of sql server process memory has been paged out%' THEN CONVERT(CHAR(5),17890)
  10944. ELSE '' END AS err,
  10945. COUNT(logmsg) AS errcnt,
  10946. logdate,
  10947. 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'
  10948. 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.'
  10949. ELSE logmsg END AS logmsg
  10950. FROM #dbcc
  10951. GROUP BY logmsg, logdate
  10952. )
  10953. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog_Summary' AS [Information],
  10954. err AS [Error_Number],
  10955. SUM(errcnt) AS Error_Count,
  10956. MIN(logdate) AS [First_Logged_Date],
  10957. MAX(logdate) AS [Last_Logged_Date],
  10958. logmsg AS [Logged_Message],
  10959. CASE WHEN logmsg LIKE 'Error: 825%' THEN 'IO transient failure. Possible corruption'
  10960. 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'
  10961. WHEN logmsg LIKE 'Error: 855%' OR logmsg LIKE 'Error: 856%' THEN 'Hardware memory corruption'
  10962. WHEN logmsg LIKE 'Error: 3452%' THEN 'Metadata inconsistency in DB. Run DBCC CHECKIDENT'
  10963. WHEN logmsg LIKE 'Error: 3619%' THEN 'Chkpoint failed. No Log space available'
  10964. WHEN logmsg LIKE 'Error: 9002%' THEN 'No Log space available'
  10965. WHEN logmsg LIKE 'Error: 17204%' OR logmsg LIKE 'Error: 17207%' THEN 'Error opening file during startup process'
  10966. WHEN logmsg LIKE 'Error: 17179%' THEN 'No AWE - LPIM related'
  10967. WHEN logmsg LIKE 'Error: 17890%' THEN 'sqlservr process paged out'
  10968. WHEN logmsg LIKE 'Error: 2508%' THEN 'Catalog views inaccuracies in DB. Run DBCC UPDATEUSAGE'
  10969. WHEN logmsg LIKE 'Error: 2511%' THEN 'Index Keys errors'
  10970. WHEN logmsg LIKE 'Error: 3271%' THEN 'IO nonrecoverable error'
  10971. WHEN logmsg LIKE 'Error: 5228%' OR logmsg LIKE 'Error: 5229%' THEN 'Online Index operation errors'
  10972. WHEN logmsg LIKE 'Error: 5242%' THEN 'Page structural inconsistency'
  10973. WHEN logmsg LIKE 'Error: 5243%' THEN 'In-memory structural inconsistency'
  10974. WHEN logmsg LIKE 'Error: 5250%' THEN 'Corrupt page. Error cannot be fixed'
  10975. WHEN logmsg LIKE 'Error: 5901%' THEN 'Chkpoint failed. Possible corruption'
  10976. WHEN logmsg LIKE 'Error: 17130%' THEN 'No lock memory'
  10977. WHEN logmsg LIKE 'Error: 17300%' THEN 'Unable to run new system task'
  10978. WHEN logmsg LIKE 'Error: 802%' THEN 'No BP memory'
  10979. WHEN logmsg LIKE 'Error: 845%' OR logmsg LIKE 'Error: 1105%' OR logmsg LIKE 'Error: 1121%' THEN 'No disk space available'
  10980. WHEN logmsg LIKE 'Error: 1214%' THEN 'Internal parallelism error'
  10981. WHEN logmsg LIKE 'Error: 823%' OR logmsg LIKE 'Error: 824%' THEN 'IO failure. Possible corruption'
  10982. WHEN logmsg LIKE 'Error: 832%' THEN 'Page checksum error. Possible corruption'
  10983. 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'
  10984. WHEN logmsg LIKE 'Error: 5572%' THEN 'Possible FILESTREAM corruption'
  10985. WHEN logmsg LIKE 'Error: 9100%' THEN 'Possible index corruption'
  10986. -- How To Diagnose and Correct Errors 17883, 17884, 17887, and 17888 (http://technet.microsoft.com/en-us/library/cc917684.aspx)
  10987. WHEN logmsg LIKE 'Error: 17883%' THEN 'Non-yielding scheduler: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10988. WHEN logmsg LIKE 'Error: 17884%' OR logmsg LIKE 'Error: 17888%' THEN 'Deadlocked scheduler: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10989. WHEN logmsg LIKE 'Error: 17887%' THEN 'IO completion error: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10990. WHEN logmsg LIKE 'Error: 1205%' THEN 'Deadlocked transaction'
  10991. WHEN logmsg LIKE 'Error: 610%' THEN 'Page header invalid. Possible corruption'
  10992. WHEN logmsg LIKE 'Error: 8621%' THEN 'QP stack overflow during optimization. Please simplify the query'
  10993. WHEN logmsg LIKE 'Error: 8642%' THEN 'QP insufficient threads for parallelism'
  10994. WHEN logmsg LIKE 'Error: 701%' THEN 'Insufficient memory'
  10995. -- How to troubleshoot SQL Server error 8645 (http://support.microsoft.com/kb/309256)
  10996. WHEN logmsg LIKE 'Error: 8645%' THEN 'Insufficient memory: http://support.microsoft.com/kb/309256'
  10997. WHEN logmsg LIKE 'Error: 605%' THEN 'Page retrieval failed. Possible corruption'
  10998. -- How to troubleshoot Msg 5180 (http://support.microsoft.com/kb/2015747)
  10999. WHEN logmsg LIKE 'Error: 5180%' THEN 'Invalid file ID. Possible corruption: http://support.microsoft.com/kb/2015747'
  11000. WHEN logmsg LIKE 'Error: 8966%' THEN 'Unable to read and latch on a PFS or GAM page'
  11001. WHEN logmsg LIKE 'Error: 9001%' OR logmsg LIKE 'Error: 9002%' THEN 'Transaction log errors.'
  11002. WHEN logmsg LIKE 'Error: 9003%' OR logmsg LIKE 'Error: 9004%' OR logmsg LIKE 'Error: 9015%' THEN 'Transaction log errors. Possible corruption'
  11003. -- How to reduce paging of buffer pool memory in the 64-bit version of SQL Server (http://support.microsoft.com/kb/918483)
  11004. 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'
  11005. WHEN logmsg LIKE '%cachestore flush%' THEN 'CacheStore flush'
  11006. ELSE '' END AS [Comment],
  11007. 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','%'), '%%%', '%')
  11008. 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)
  11009. ELSE '' END AS [Look_for_Message_example]
  11010. FROM cte_dbcc
  11011. GROUP BY err, logmsg
  11012. ORDER BY SUM(errcnt) DESC;
  11013. IF @logdetail = 1
  11014. BEGIN
  11015. 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],
  11016. CASE WHEN logmsg LIKE 'Error: 825%' THEN 'IO transient failure. Possible corruption'
  11017. WHEN logmsg LIKE 'Error: 833%' OR logmsg LIKE 'SQL Server has encountered % longer than 15 seconds %' THEN 'Long IO detected'
  11018. WHEN logmsg LIKE 'Error: 855%' OR logmsg LIKE 'Error: 856%' THEN 'Hardware memory corruption'
  11019. WHEN logmsg LIKE 'Error: 3452%' THEN 'Metadata inconsistency in DB. Run DBCC CHECKIDENT'
  11020. WHEN logmsg LIKE 'Error: 3619%' THEN 'Chkpoint failed. No Log space available'
  11021. WHEN logmsg LIKE 'Error: 9002%' THEN 'No Log space available'
  11022. WHEN logmsg LIKE 'Error: 17179%' THEN 'No AWE - LPIM related'
  11023. WHEN logmsg LIKE 'Error: 17890%' THEN 'sqlservr process paged out'
  11024. WHEN logmsg LIKE 'Error: 17204%' OR logmsg LIKE 'Error: 17207%' THEN 'Error opening file during startup process'
  11025. WHEN logmsg LIKE 'Error: 2508%' THEN 'Catalog views inaccuracies in DB. Run DBCC UPDATEUSAGE'
  11026. WHEN logmsg LIKE 'Error: 2511%' THEN 'Index Keys errors'
  11027. WHEN logmsg LIKE 'Error: 3271%' THEN 'IO nonrecoverable error'
  11028. WHEN logmsg LIKE 'Error: 5228%' OR logmsg LIKE 'Error: 5229%' THEN 'Online Index operation errors'
  11029. WHEN logmsg LIKE 'Error: 5242%' THEN 'Page structural inconsistency'
  11030. WHEN logmsg LIKE 'Error: 5243%' THEN 'In-memory structural inconsistency'
  11031. WHEN logmsg LIKE 'Error: 5250%' THEN 'Corrupt page. Error cannot be fixed'
  11032. WHEN logmsg LIKE 'Error: 5901%' THEN 'Chkpoint failed. Possible corruption'
  11033. WHEN logmsg LIKE 'Error: 17130%' THEN 'No lock memory'
  11034. WHEN logmsg LIKE 'Error: 17300%' THEN 'Unable to run new system task'
  11035. WHEN logmsg LIKE 'Error: 802%' THEN 'No BP memory'
  11036. WHEN logmsg LIKE 'Error: 845%' OR logmsg LIKE 'Error: 1105%' OR logmsg LIKE 'Error: 1121%' THEN 'No disk space available'
  11037. WHEN logmsg LIKE 'Error: 1214%' THEN 'Internal parallelism error'
  11038. WHEN logmsg LIKE 'Error: 823%' OR logmsg LIKE 'Error: 824%' THEN 'IO failure. Possible corruption'
  11039. WHEN logmsg LIKE 'Error: 832%' THEN 'Page checksum error. Possible corruption'
  11040. 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'
  11041. WHEN logmsg LIKE 'Error: 5572%' THEN 'Possible FILESTREAM corruption'
  11042. WHEN logmsg LIKE 'Error: 9100%' THEN 'Possible index corruption'
  11043. -- How To Diagnose and Correct Errors 17883, 17884, 17887, and 17888 (http://technet.microsoft.com/en-us/library/cc917684.aspx)
  11044. WHEN logmsg LIKE 'Error: 17883%' THEN 'Non-yielding scheduler'
  11045. WHEN logmsg LIKE 'Error: 17884%' OR logmsg LIKE 'Error: 17888%' THEN 'Deadlocked scheduler'
  11046. WHEN logmsg LIKE 'Error: 17887%' THEN 'IO completion error'
  11047. WHEN logmsg LIKE 'Error: 1205%' THEN 'Deadlocked transaction'
  11048. WHEN logmsg LIKE 'Error: 610%' THEN 'Page header invalid. Possible corruption'
  11049. WHEN logmsg LIKE 'Error: 8621%' THEN 'QP stack overflow during optimization. Please simplify the query'
  11050. WHEN logmsg LIKE 'Error: 8642%' THEN 'QP insufficient threads for parallelism'
  11051. WHEN logmsg LIKE 'Error: 701%' THEN 'Insufficient memory'
  11052. -- How to troubleshoot SQL Server error 8645 (http://support.microsoft.com/kb/309256)
  11053. WHEN logmsg LIKE 'Error: 8645%' THEN 'Insufficient memory'
  11054. WHEN logmsg LIKE 'Error: 605%' THEN 'Page retrieval failed. Possible corruption'
  11055. -- How to troubleshoot Msg 5180 (http://support.microsoft.com/kb/2015747)
  11056. WHEN logmsg LIKE 'Error: 5180%' THEN 'Invalid file ID. Possible corruption'
  11057. WHEN logmsg LIKE 'Error: 8966%' THEN 'Unable to read and latch on a PFS or GAM page'
  11058. WHEN logmsg LIKE 'Error: 9001%' OR logmsg LIKE 'Error: 9002%' THEN 'Transaction log errors.'
  11059. WHEN logmsg LIKE 'Error: 9003%' OR logmsg LIKE 'Error: 9004%' OR logmsg LIKE 'Error: 9015%' THEN 'Transaction log errors. Possible corruption'
  11060. -- How to reduce paging of buffer pool memory in the 64-bit version of SQL Server (http://support.microsoft.com/kb/918483)
  11061. 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'
  11062. WHEN logmsg LIKE '%cachestore flush%' THEN 'CacheStore flush'
  11063. ELSE '' END AS [Comment]
  11064. FROM #dbcc
  11065. ORDER BY logdate DESC
  11066. END
  11067. END
  11068. ELSE
  11069. BEGIN
  11070. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog' AS [Check], '[OK]' AS [Deviation]
  11071. END;
  11072. END
  11073. ELSE
  11074. BEGIN
  11075. RAISERROR('[WARNING: Only a sysadmin or securityadmin can run the "Errorlog" check. Bypassing check]', 16, 1, N'permissions')
  11076. 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')
  11077. --RETURN
  11078. END;
  11079. --------------------------------------------------------------------------------------------------------------------------------
  11080. -- System health error checks subsection
  11081. --------------------------------------------------------------------------------------------------------------------------------
  11082. IF @sqlmajorver > 10
  11083. BEGIN
  11084. RAISERROR (N' |-Starting System health checks', 10, 1) WITH NOWAIT
  11085. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11086. DROP TABLE #SystemHealthSessionData;
  11087. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11088. CREATE TABLE #SystemHealthSessionData (target_data XML)
  11089. -- Store the XML data in a temporary table
  11090. INSERT INTO #SystemHealthSessionData
  11091. SELECT CAST(xet.target_data AS XML)
  11092. FROM sys.dm_xe_session_targets xet
  11093. INNER JOIN sys.dm_xe_sessions xe ON xe.address = xet.event_session_address
  11094. WHERE xe.name = 'system_health'
  11095. IF (SELECT COUNT(*) FROM #SystemHealthSessionData a WHERE CONVERT(VARCHAR(max), target_data) LIKE '%error_reported%') > 0
  11096. BEGIN
  11097. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors' AS [Check], '[WARNING: System Health Session contains important messages.]' AS [Deviation];
  11098. -- Get statistical information about all the errors reported
  11099. ;WITH cteHealthSession (EventXML) AS (SELECT C.query('.') EventXML
  11100. FROM #SystemHealthSessionData a
  11101. CROSS APPLY a.target_data.nodes('/RingBufferTarget/event') AS T(C)
  11102. ),
  11103. cteErrorReported (EventTime, ErrorNumber) AS (SELECT EventXML.value('(/event/@timestamp)[1]', 'datetime') AS EventTime,
  11104. EventXML.value('(/event/data[@name="error_number"]/value)[1]', 'int') AS ErrorNumber
  11105. FROM cteHealthSession
  11106. WHERE EventXML.value('(/event/@name)[1]', 'VARCHAR(500)') = 'error_reported'
  11107. )
  11108. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors_Summary' AS [Information],
  11109. ErrorNumber AS [Error_Number],
  11110. MIN(EventTime) AS [First_Logged_Date],
  11111. MAX(EventTime) AS [Last_Logged_Date],
  11112. COUNT(ErrorNumber) AS Error_Count,
  11113. 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]
  11114. FROM cteErrorReported a
  11115. INNER JOIN sys.messages b ON a.ErrorNumber = b.message_id
  11116. WHERE b.language_id = @langid
  11117. GROUP BY a.ErrorNumber, b.[text]
  11118. -- Get detailed information about all the errors reported
  11119. ;WITH cteHealthSession AS (SELECT C.query('.').value('(/event/@timestamp)[1]', 'datetime') AS EventTime,
  11120. C.query('.').value('(/event/data[@name="error_number"]/value)[1]', 'int') AS ErrorNumber,
  11121. C.query('.').value('(/event/data[@name="severity"]/value)[1]', 'int') AS ErrorSeverity,
  11122. C.query('.').value('(/event/data[@name="state"]/value)[1]', 'int') AS ErrorState,
  11123. C.query('.').value('(/event/data[@name="message"]/value)[1]', 'VARCHAR(MAX)') AS ErrorText,
  11124. C.query('.').value('(/event/action[@name="session_id"]/value)[1]', 'int') AS SessionID,
  11125. C.query('.').value('(/event/data[@name="category"]/text)[1]', 'VARCHAR(10)') AS ErrorCategory
  11126. FROM #SystemHealthSessionData a
  11127. CROSS APPLY a.target_data.nodes('/RingBufferTarget/event') AS T(C)
  11128. WHERE C.query('.').value('(/event/@name)[1]', 'VARCHAR(500)') = 'error_reported')
  11129. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors_Detail' AS [Information],
  11130. EventTime AS [Logged_Date],
  11131. ErrorNumber AS [Error_Number],
  11132. ErrorSeverity AS [Error_Sev],
  11133. ErrorState AS [Error_State],
  11134. ErrorText AS [Logged_Message],
  11135. SessionID
  11136. FROM cteHealthSession
  11137. ORDER BY EventTime
  11138. END
  11139. ELSE
  11140. BEGIN
  11141. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors' AS [Check], '[OK]' AS [Deviation]
  11142. END;
  11143. END;
  11144. --------------------------------------------------------------------------------------------------------------------------------
  11145. -- Clean up temp objects
  11146. --------------------------------------------------------------------------------------------------------------------------------
  11147. RAISERROR (N'Clearing up temporary objects', 10, 1) WITH NOWAIT
  11148. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  11149. DROP TABLE #dbinfo;
  11150. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  11151. DROP TABLE #output_dbinfo;
  11152. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  11153. DROP TABLE #tblIOStall;
  11154. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  11155. DROP TABLE #tmpdbs1;
  11156. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  11157. DROP TABLE #tmpdbs0;
  11158. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  11159. DROP TABLE #tblPerfCount;
  11160. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  11161. DROP TABLE tempdb.dbo.tblPerfThresholds;
  11162. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  11163. DROP TABLE #tblHypObj;
  11164. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  11165. DROP TABLE #tblIxs1;
  11166. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  11167. DROP TABLE #tblIxs2;
  11168. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  11169. DROP TABLE #tblIxs3;
  11170. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  11171. DROP TABLE #tblIxs4;
  11172. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  11173. DROP TABLE #tblIxs5;
  11174. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  11175. DROP TABLE #tblIxs6;
  11176. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  11177. DROP TABLE #tblFK;
  11178. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  11179. DROP TABLE #dbcc;
  11180. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  11181. DROP TABLE #avail_logs;
  11182. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  11183. DROP TABLE #log_info1;
  11184. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  11185. DROP TABLE #log_info2;
  11186. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  11187. DROP TABLE #tmpobjectnames;
  11188. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  11189. DROP TABLE #tmpfinalobjectnames;
  11190. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  11191. DROP TABLE #tblWaits;
  11192. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  11193. DROP TABLE #tblFinalWaits;
  11194. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  11195. DROP TABLE #tblLatches;
  11196. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  11197. DROP TABLE #tblFinalLatches;
  11198. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  11199. DROP TABLE #IndexCreation;
  11200. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  11201. DROP TABLE #IndexRedundant;
  11202. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  11203. DROP TABLE #tblBlkChains;
  11204. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  11205. DROP TABLE #tblStatsSamp;
  11206. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  11207. DROP TABLE #tblSpinlocksBefore;
  11208. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  11209. DROP TABLE #tblSpinlocksAfter;
  11210. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  11211. DROP TABLE #tblFinalSpinlocks;
  11212. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  11213. DROP TABLE #pagerepair;
  11214. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  11215. DROP TABLE #tmp_dm_io_virtual_file_stats;
  11216. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  11217. DROP TABLE #tmp_dm_exec_query_stats;
  11218. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  11219. DROP TABLE #dm_exec_query_stats;
  11220. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  11221. DROP TABLE #tblPendingIOReq;
  11222. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  11223. DROP TABLE #tblPendingIO;
  11224. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  11225. DROP TABLE #qpwarnings;
  11226. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  11227. DROP TABLE #tblStatsUpd;
  11228. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  11229. DROP TABLE #tblPerSku;
  11230. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  11231. DROP TABLE #tblColStoreIXs;
  11232. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11233. DROP TABLE #SystemHealthSessionData;
  11234. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  11235. DROP TABLE #tmpdbfiledetail;
  11236. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  11237. DROP TABLE #tblHints;
  11238. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  11239. DROP TABLE #tblTriggers;
  11240. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  11241. DROP TABLE #tmpIPS;
  11242. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  11243. DROP TABLE #tblCode;
  11244. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  11245. DROP TABLE #tblWorking;
  11246. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  11247. DROP TABLE #tmpdbs_userchoice;
  11248. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  11249. DROP TABLE #xp_cmdshell_CluNodesOutput;
  11250. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  11251. DROP TABLE #xp_cmdshell_CluOutput;
  11252. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  11253. DROP TABLE #xp_cmdshell_Nodes;
  11254. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  11255. DROP TABLE #xp_cmdshell_QFEOutput;
  11256. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  11257. DROP TABLE #xp_cmdshell_QFEFinal;
  11258. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#RegResult'))
  11259. DROP TABLE #RegResult;
  11260. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ServiceStatus'))
  11261. DROP TABLE #ServiceStatus;
  11262. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  11263. DROP TABLE #xp_cmdshell_AcctSPNoutput;
  11264. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  11265. DROP TABLE #xp_cmdshell_DupSPNoutput;
  11266. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  11267. DROP TABLE #FinalDupSPN;
  11268. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  11269. DROP TABLE #ScopedDupSPN;
  11270. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  11271. DROP TABLE #tblDRI;
  11272. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  11273. DROP TABLE #tblInMemDBs;
  11274. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  11275. DROP TABLE #tmpXIS;
  11276. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  11277. DROP TABLE #tmpXNCIS;
  11278. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  11279. DROP TABLE #tmpIPS_CI;
  11280. 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')
  11281. 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')
  11282. 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')
  11283. 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')
  11284. RAISERROR (N'All done!', 10, 1) WITH NOWAIT
  11285. GO