1
0

Check_BP_Servers.sql 777 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143
  1. USE [master]
  2. GO
  3. DECLARE @custompath NVARCHAR(500), @allow_xpcmdshell bit, @ptochecks bit, @duration tinyint, @logdetail bit, @diskfrag bit, @ixfrag bit, @ixfragscanmode VARCHAR(8), @bpool_consumer bit, @gen_scripts bit, @dbScope VARCHAR(256), @spn_check bit
  4. /* Best Practices Check - [email protected] (http://aka.ms/BPCheck; http://aka.ms/sqlinsights)
  5. READ ME - Important options for executing BPCheck
  6. Set @duration to the number of seconds between data collection points regarding perf counters, waits and latches.
  7. Duration must be between 10s and 255s (4m 15s), with a default of 90s.
  8. Set @ptochecks to OFF if you want to skip more performance tuning and optimization oriented checks.
  9. Uncomment @custompath below and set the custom desired path for .ps1 files.
  10. If not, default location for .ps1 files is the Log folder.
  11. Set @allow_xpcmdshell to OFF if you want to skip checks that are dependant on xp_cmdshell.
  12. Note that original server setting for xp_cmdshell would be left unchanged if tests were allowed.
  13. Set @spn_check to OFF if you want to skip SPN checks.
  14. Set @diskfrag to ON if you want to check for disk physical fragmentation.
  15. Can take some time in large disks. Requires elevated privileges.
  16. Set @ixfrag to ON if you want to check for index fragmentation.
  17. Can take some time to collect data depending on number of databases and indexes, as well as the scan mode chosen in @ixfragscanmode.
  18. Set @ixfragscanmode to the scanning mode you prefer.
  19. More detail on scanning modes available at http://msdn.microsoft.com/en-us/library/ms188917.aspx
  20. Set @logdetail to OFF if you want to get just the summary info on issues in the Errorlog, rather than the full detail.
  21. Set @bpool_consumer to OFF if you want to list what are the Buffer Pool Consumers from Buffer Descriptors.
  22. Mind that it may take some time in servers with large caches.
  23. Set @gen_scripts to ON if you want to generate index related scripts.
  24. These include drops for Duplicate, Redundant, Hypothetical and Rarely Used indexes, as well as creation statements for FK and Missing Indexes.
  25. Set @dbScope to the appropriate list of database IDs if there's a need to have a specific scope for database specific checks.
  26. Valid input should be numeric value(s) between single quotes, as follows: '1,6,15,123'
  27. Leave NULL for all databases
  28. */
  29. SET @duration = 90
  30. SET @ptochecks = 1 --(1 = ON; 0 = OFF)
  31. --SET @custompath = 'C:\<temp_location>'
  32. SET @allow_xpcmdshell = 1 --(1 = ON; 0 = OFF)
  33. SET @spn_check = 0 --(1 = ON; 0 = OFF)
  34. SET @diskfrag = 1 --(1 = ON; 0 = OFF)
  35. SET @ixfrag = 1 --(1 = ON; 0 = OFF)
  36. SET @ixfragscanmode = 'LIMITED' --(Valid inputs are DEFAULT, NULL, LIMITED, SAMPLED, or DETAILED. The default (NULL) is LIMITED)
  37. SET @logdetail = 0 --(1 = ON; 0 = OFF)
  38. SET @bpool_consumer = 1 --(1 = ON; 0 = OFF)
  39. SET @gen_scripts = 0 --(1 = ON; 0 = OFF)
  40. SET @dbScope = NULL --(NULL = All DBs)
  41. /*
  42. DESCRIPTION: This script checks for skews in the most common best practices from SQL Server 2005 onwards.
  43. DISCLAIMER:
  44. This code is not supported under any Microsoft standard support program or service.
  45. This code and information are provided "AS IS" without warranty of any kind, either expressed or implied.
  46. The entire risk arising out of the use or performance of the script and documentation remains with you.
  47. Furthermore, Microsoft or the author shall not be liable for any damages you may sustain by using this information, whether direct,
  48. indirect, special, incidental or consequential, including, without limitation, damages for loss of business profits, business interruption, loss of business information
  49. or other pecuniary loss even if it has been advised of the possibility of such damages.
  50. Read all the implementation and usage notes thoroughly.
  51. v1 - 28-07-2011 - Initial release
  52. v1.1 - 28-01-2012 - Added some SQL 2012 support.
  53. v1.2 - 08-03-2012 - Added information to Database Information subsection;
  54. Added I/O stall in excess of 50% in database files subsection.
  55. v1.2.1 - 20-03-2012 - Added redundant index subsection;
  56. Added more SQL 2012 support;
  57. Changed database loop method.
  58. v1.2.2 - 22-03-2012 - Added check for Direct Catalog Updates.
  59. v1.2.3 - 05-04-2012 - Added unused index subsection;
  60. Fixed some collation issues.
  61. v1.2.4 - 07-04-2012 - Split in separate listings the unused indexes from rarely used indexes;
  62. Split in separate listings the real duplicates from possibly redundant indexes.
  63. v1.2.5 - 08-04-2012 - Added power plan check, by Aaron Bertrand (http://www.mssqltips.com/tip.asp?tip=2225&ctc).
  64. v1.2.6 - 13-04-2012 - Added NTFS block size check;
  65. Fixed issue in Data and Log locations check.
  66. v1.2.7 - 16-04-2012 - Added Errorlog based checks section.
  67. v1.2.8 - 21-04-2012 - Fixed issue with NTFS block size check;
  68. Added Replication Components installation check;
  69. Scan for Startup Procs checks for Replication Components installation.
  70. v1.2.9 - 04-05-2012 - Fixed issues when running on SQL Server 2005;
  71. COM object creation was revised.
  72. v1.3 - 08-05-2012 - Added support for customizing save location for .ps1 files;
  73. Default location is the Log folder. Optionally, uncomment line where @custompath is set and insert the desired path.
  74. v1.3.2 - 09-05-2012 - Added descriptive column to Database_Options test, to clear what are the Non-optimal_Settings for each database;
  75. Corrected bug with powershell files default save location, in case default location has changed since SQL Server install.
  76. v1.3.3 - 31-05-2012 - Fixed issue with DBCC CHECKDB test and offline databases.
  77. v1.3.4 - 03-06-2012 - Added more system configuration checks.
  78. v1.3.5 - 07-06-2012 - Added suspect pages check;
  79. Added more permissions checks in pre-requisites section;
  80. Added search for Errors in Errorlog checks.
  81. v1.3.6 - 08-06-2012 - Revised support for account checks in SQL 2012.
  82. v1.3.7 - 14-06-2012 - Fixed issue with large Object_Names;
  83. Fixed issue with Powershell 3.0 script;
  84. Data and log in same volume only lists affected objects now;
  85. Fixed blocking issue with hypothetical objects drop statements;
  86. Added duplicate indexes drop statements (all but the 1st of duplicates);
  87. Added tempDB in same location as user DBs check;
  88. Added backup checks.
  89. v1.3.8 - 19-06-2012 - Fixed issue with Errorlog based checks;
  90. Fixed issue with Data and Log locations.
  91. v1.3.9 - 05-07-2012 - Fixed issue with CPUs vs. MaxDOP check.
  92. v1.4.0 - 10-07-2012 - Added LPIM check;
  93. Added info to trace flags subsection.
  94. v1.4.1 - 18-07-2012 - Added information to CPUs vs. MaxDOP check.
  95. Added information about all backups since last Full (Database, File or Partial).
  96. v1.4.2 - 02-08-2012 - Added Processor Affinity information to instance info.
  97. v1.4.3 - 19-09-2012 - Fixed issue with large integer in DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled) subsection.
  98. v1.4.4 - 23-09-2012 - Added events to monitor to SQL Agent alerts for severe errors subsection;
  99. Added comment column for specific errors foun in Errorlog based checks subsection.
  100. v1.4.5 - 24-09-2012 - Fixed issue with Errorlog based checks subsection search.
  101. v1.4.6 - 17-10-2012 - Fixed issue with large percentages in Stall IO check.
  102. v1.4.7 - 24-10-2012 - Fixed issue with Data files and Logs in same physical volume check, where data and fulltext on the same volume raised an issue;
  103. Fixed issue with Service Accounts and Status check where LocalSystem would not raise issues;
  104. Widened search for Redundant Indexes.
  105. v1.4.8 - 01-11-2012 - Added generation of drop statements for existing Rarely Used indexes.
  106. v1.5.0 - 11-11-2012 - Fixed cpu affinity shows all zeros when auto affinity was used;
  107. Fixed issue with duplicate indexes check introduced with v1.4.8;
  108. Fixed issue with Errorlog based checks subsection search where no comments where shown;
  109. Added aggregates to CPU information subsection;
  110. Simplified logic in CPU Affinity in NUMA architecture subsection;
  111. Added checks to Server Memory information subsection;
  112. Added checks to System configurations subsection;
  113. Added a Deprecated features subsection;
  114. Changed perf counters collection method in Perf counters subsection;
  115. Added more counters to Perf counters subsection.
  116. v1.5.1 - 11-11-2012 - Fixed perf counters collection collecting from default instances only.
  117. v1.5.2 - 15-11-2012 - Fixed issue with long mountpoint paths;
  118. Fixed issue with Backup checks subsection;
  119. Added output from sys.messages to Errorlog based checks.
  120. v1.5.4 - 18-11-2012 - Added sql server process trimming to Errorlog based checks;
  121. Added more checks to System configurations subsection;
  122. Added HA information subsection;
  123. Added optimal nr of VLFs and log size to VLF subsection, based on current findings;
  124. Added even file number check for tempDB;
  125. Added minimum file number check for tempDB when < 4;
  126. Added summary to Errorlog based checks;
  127. Added column about IFI status in autogrow sections;
  128. Added further info to VLF section.
  129. v1.5.5 - 19-11-2012 - Added info to Instance Information subsection;
  130. Added Processor Summary subsection aggregating all CPU information;
  131. Added RM task output notifications;
  132. Format binary affinity mask by node for better reading.
  133. v1.5.6 - 24-11-2012 - Changed collection for several tests that can be supported by DMVs on SQL Server 2008 R2 SP1 and above (was implemented for SQL Server 2012 only);
  134. Added checks and information to Server Memory subsection.
  135. v1.5.7 - 10-12-2012 - Changed collection for Index checks to cope with large database names;
  136. Added support for collection through SQLDiag custom collector.
  137. v1.5.9 - 30-12-2012 - Added schema to index script generation;
  138. Fixed conversion issue with Max Worker Threads option;
  139. Added extended pagefile checks;
  140. Added Replication error checks;
  141. Added check for Indexes with large keys (> 900 bytes).
  142. v1.6.1 - 21-01-2013 - Fixed issue with SQL Server 2005 in Server Memory subsection;
  143. Fixed conversion issues with large msticks values;
  144. Fixed issue with Memory reference values.
  145. v1.6.2 - 02-02-2013 - Fixed issues with case sensitive collations;
  146. Expanded search for redundant indexes;
  147. Expanded system configuration checks;
  148. Added Plan use ratio checks;
  149. Added Hints usage check;
  150. Added Linked servers information;
  151. Added AlwaysOn/Mirroring automatic page repairs check;
  152. Added check for user DBs with Auto_Update_Statistics_Asynch enabled and Auto_Update_Statistics disabled;
  153. Extended I/O Stall checks to verify I/O latencies.
  154. v1.6.3 - 13-02-2013 - Added option to skip PS based tests where activating xp_cmdshell is strictly forbidden (See Readme at the top).
  155. v1.6.4 - 18-02-2013 - Added Buffer Node to performance counters collection;
  156. Added information to RM Notifications section;
  157. Added Cached Query Plans issues checks (Top 25 by CPU, IO and Recompiles with plan warnings);
  158. Added Object Naming Convention checks
  159. v1.6.5 - 27-02-2013 - Added check for databases that need to run DBCC CHECKDB (...) WITH DATA_PURITY;
  160. Added Waits and Latches information;
  161. Added check for statistics that need to be updated;
  162. Optimized performance counters collection;
  163. Extended performance counters collection to 90s;
  164. Removed alternate keys from search for Unused and Rarely used indexes;
  165. Added parameter to enable/disable performance tuning and optimization oriented checks;
  166. Added parameter to enable/disable best practices oriented checks;
  167. v1.6.6 - 05-03-2013 - Removed MS Shipped objects from duplicate and redundant indexes check;
  168. Added search for tables with no indexes, tables with no clustered indexes and tables with more indexes than columns.
  169. v1.6.7 - 01-04-2013 - Fixed issue with AlwaysOn/Mirroring automatic page repair subsection in SQL 2008R2 or below;
  170. Fixed issue with Cached Query Plans issues subsection in SQL 2008R2 RTM;
  171. Added more database files information;
  172. Fixed false positives with DBs Autogrowth > 1GB check;
  173. Added check for TF834 (Large Page Support for BP) when Column Store Indexes are used;
  174. Fixed false positives with Power plan subsection.
  175. v1.6.8.1 - 03-04-2013 - Added min server memory setting checks;
  176. Added information to Errorlog checks;
  177. Fixed false negatives with "Data files and Logs / tempDB and user Databases in same volume" checks when PS is not available;
  178. Added check for tempDB Files with different autogrow setting.
  179. v1.6.9 - 11-04-2013 - Added Worker threads exhaustion check;
  180. Added support for sys.dm_db_stats_properties in Statistics update subsection, if on SQL 2008R2 SP2 or SQL 2012 SP1 or higher.
  181. Made changes to latch checks;
  182. Fixed false positives with Indexes with large keys (> 900 bytes) subsection.
  183. v1.7.0.2 - 07-05-2013 - Fixed Statistics update subsection for SQL 2005;
  184. Changed Errorlog aggregates;
  185. Added Historical Latches without BUFFER class;
  186. Added page file size check for WS2003;
  187. Added information to "Tables with more Indexes than Columns" check.
  188. v1.7.1 - 10-05-2013 - Added "Tables with partition misaligned indexes" check.
  189. v1.7.2 - 18-05-2013 - Added windows service pack level to machine information section;
  190. Changed information available in "Database_File_Information", namely pages calculated in MB;
  191. Added Enterprise features usage information per database;
  192. Added batch performance counters (SQL Server 2012);
  193. Rewrote all database loops.
  194. v1.7.3 - 24-05-2013 - "Query Plan Warnings" check now ignores workload in master and mssqlsystemresource databases;
  195. Fixed issue with running BPchecks without PTOChecks.
  196. v1.7.4 - 01-06-2013 - Added FK with no indexes check;
  197. Fixed issue with Statistics update check in prior to 2008R2 SP2 and 2012 SP1.
  198. v1.7.5 - 25-06-2013 - Added information to Enterprise features usage subsection;
  199. Split Unused indexes section into Unused_Indexes_With_Updates and Unused_Indexes_No_Updates;
  200. Extended Objects naming conventions checks;
  201. Added Disabled indexes subsection;
  202. Added indexes with low fill factor subsection;
  203. Added Non-unique clustered indexes subsection;
  204. Fixed issue with Cached Query Plans issues subsection.
  205. v1.7.6 - 20-07-2013 - Added check for AlwaysOn AG replication status per database (http://support.microsoft.com/kb/2857849);
  206. Fixed issue with large values in I/O Stall subsection;
  207. Added search parameters to Objects naming conventions subsection.
  208. v1.7.6.1-24-07-2013 - Fixed issue with Objects naming conventions checks.
  209. v1.7.6.2-30-07-2013 - Fixed issue with Objects naming conventions checks.
  210. v1.7.7 - 05-09-2013 - Added Missing Indexes output (most relevant - score based - use at you own discretion);
  211. Changed Processor Usage info from 1h to 2h.
  212. v1.7.8 - 21-09-2013 - Changed system database exclusion choices;
  213. Added information to User DBs with non-default options subsection;
  214. VLF section shows added information only on databases failing threshold.
  215. v1.7.9 - 09-10-2013 - Fixed issue with false positives in Purity Check;
  216. Added logic to exclude standard names of MS shipped databases from database design related checks;
  217. Added performance counters to collection.
  218. v1.8 - 25-10-2013 - Added blocking chains (over 5s);
  219. Added monitoring duration as parameter;
  220. Added more file related info to Autogrowth checks;
  221. Fixed CPU Affinity bit mask issue on 16 CPU+ servers;
  222. Extended password checks;
  223. Extended logic to exclude MS shipped databases, based on notable schema objects.
  224. v1.8.0.1 - 28-10-2013 - Fixed issues with logic to exclude MS shipped databases.
  225. v1.8.1 - 03-11-2013 - Added owner info to Database Information subsection;
  226. Fixed issue where no warning was raised for DBs that never had a Log Backup, but had Full/Diff Backups in Full or Bulk-logged RM;
  227. Added Statistics sampling < 25 pct check on SQL 2008R2 SP2 / SQL 2012 and above;
  228. Added Pending I/O Requests check;
  229. Added info to Windows Version and Architecture subsection;
  230. Added spinlocks info;
  231. Added Clustered Indexes with GUIDs in key checks;
  232. Extended trace flag checks.
  233. v1.8.2.1 - 11-11-2013 - Removed cursor from VLF checks;
  234. Added checks to System Configurations;
  235. Added checks to TempDB subsection;
  236. Fixed index statement generation in Foreign Keys with no Index subsection;
  237. Fixed issue with Statistics update subsection up to SQL 2008R2 SP2;
  238. Fixed duplicate key issue in Pending I/O Requests check;
  239. Fixed duplicate entries in redundant indexes of Missing Indexes checks;
  240. Fixed syntax issue in Foreign Keys with no Index subsection.
  241. v1.8.2.2 - 14-11-2013 - Added Dynamics GP database exclusions;
  242. Fixed syntax issue in System Configurations checks.
  243. v1.8.3 - 19-12-2013 - Fixed presentation issue in Pending I/O Requests subsection;
  244. Fixed conversion issue in Statistics Update subsection.
  245. v1.8.4 - 13-01-2014 - Fixed issue with database exclusions;
  246. Fixed issue with Service Accounts section in WS2003;
  247. Removed unwarranted information from DBCC CHECKDB, Direct Catalog Updates and Data Purity subsection.
  248. v1.8.4.1 - 06-02-2014- Added Service Accounts and SPN registration checks;
  249. Fixed issue with Redundant index checks on servers with CS collations.
  250. v1.8.5 - 21-02-2014 - Added LowMemoryThreshold and OOM information to Server Memory subsection;
  251. Extended Min Server Memory checks to Server Memory subsection;
  252. Added DBs with Sparse files checks;
  253. Added System health error checks;
  254. Added Resource Governor information;
  255. Added logdetail parameter to control listing the detail of all relevant Errorlog entries - which can sometimes bloat the output file to several hundred MBs;
  256. Fixed blocking chains (over 5s) showing on SP_SERVER_DIAGNOSTICS_SLEEP wait;
  257. Fixed backup size conversion issue;
  258. Fixed false positives in log backup checks;
  259. Fixed tempDB file size check and Database file information subsections based in sys.master_files may cause issues not to be reported;
  260. Fixed arithmetic overflow error in Statistics update check.
  261. v1.8.6 - 14-03-2014 - Duplicate script generation includes logic to account for PK when several IXs are unique;
  262. Optimized database discovery cycle;
  263. Fixed execution issue in AG DBs when no connections are allowed to the databases in the secondary replica, and the databases are not available for read access.
  264. v1.8.7 - 01-04-2014 - Fixed issue in Hypothetical objects drop script generation;
  265. Fixed issue in several subsections when offline DBs exist;
  266. Fixed issue introduced in v1.8.6 version where some checks would skip user DBs;
  267. Added information on clock hand notifications to Server Memory subsection;
  268. Added thresholds to some Performance Counters -> this does NOT replace a longer perf counter data collection and analysis.
  269. v1.8.7.1 - 03-04-2014 - Added Service Pack Supportability check;
  270. Fixed overflow issue in clock hand notifications;
  271. Fixed issue with clock hand notifications and SQL 2005.
  272. v1.8.8 - 23-04-2014 - Changed Pagefile free space check;
  273. Fixed missing index script creation of covering indexes;
  274. Fixed divide by zero errors in perf counters;
  275. Fixed issue with statistics checks in DBs with cmpt level 80;
  276. Fixed tempDB data file size issue - check was ok, but listed information might not be accurate;
  277. Added category column to all outputs (preparation for future developments).
  278. v1.8.9 - 09-05-2014 - Detailed categorization of memory related waits;
  279. Detailed MaxMem recommendation output;
  280. Added recommended MaxDOP value to Parallelism_MaxDOP check output;
  281. Fixed issue with No_Full_Backups check.
  282. v1.9 - 04-06-2014 - Refined search for duplicate and redundant indexes;
  283. Added partition misalign test (offset < 64KB);
  284. Added Buffer Pool Extension info subsection.
  285. v1.9.1 - 09-06-2014 - Fixed issue with duplicate and redundant index script generation.
  286. v1.9.2 - 13-06-2014 - Fixed calculation in page file checks;
  287. Added process paged out check (besides existing based in errorlog search).
  288. v1.9.3 - 08-07-2014 - Fixed backup checks reporting wrong size;
  289. Changed backup chain based checks to ignore copy_only backups;
  290. Updated Service Pack Supportability check;
  291. Added Cluster Quorum Model check;
  292. Added Cluster QFE node equality check.
  293. v1.9.4 - 16-07-2014 - Added Backups and Database files in same location check;
  294. Enhanced Hints Usage check with info from sql modules;
  295. Fixed Objects naming conventions checks not reporting issues.
  296. v1.9.5 - 17-09-2014 - Changed Hypothetical object search scope to all DBs, including MS shipped;
  297. Changed missing index check to include all missing by order of score, but still generating script only when score >= 100000;
  298. Added features to Enterprise features check;
  299. Expanded TF checks.
  300. v1.9.6.1 - 20-10-2014 - Fixed hypothetical statistics search;
  301. Fixed Parallelism_MaxDOP check on large NUMA nodes and specific MaxDOP settings;
  302. Fixed Cluster Quorum Model false positive when PS is not available;
  303. Changed Powershell availability verification to single step;
  304. Added user objects in master check;
  305. Added logon triggers information;
  306. Added database triggers information;
  307. Added Database file autogrows last 72h information;
  308. Added Cluster NIC Binding order check;
  309. Added Disk Fragmentation Analysis (only if running with elevated privs and enabled with variable @diskfrag);
  310. Added Index Fragmentation Analysis (only if enabled with variable @ixfrag);
  311. Fixed trace flag checks recommending trace flags that did not apply to server hardware.
  312. v1.9.6.2 - 23-10-2014 - Fixed false positive on Cluster NIC Binding order check;
  313. v1.9.6.3 - 25-10-2014 - Fixed syntax error on Cluster NIC Binding order check;
  314. v1.9.7 - 12-11-2014 - Changed Cluster Quorum Model check output;
  315. Fixed conversion issue with Buffer Pool Consumers section;
  316. Fixed issue on server that has only AG secondary replicas;
  317. Added model information to Machine Information section;
  318. Added @bpool_consumer option to skip listing Buffer Pool Consumers;
  319. Added @gen_scripts option to skip generating scripts (disabled by default);
  320. Added listing of which duplicate indexes are eligible for deletion;
  321. Added search for which of the duplicate indexes that are eligible for deletion are hard coded in sql modules.
  322. v1.9.8 - 10-12-2014 - Fixed issue with Cluster NIC Binding order subsection on case sensitive instances;
  323. Fixed issue with Database file autogrows last 72h subsection on case sensitive instances;
  324. Fixed issues with PS based checks running in PS v1;
  325. Fixed illegal characters issue in XML conversion;
  326. Fixed syntax error in SQL 2014 Memory Consumers from In-Memory OLTP Engine.
  327. v1.9.8.1 - 16-12-2014 - Fixed issues in Enterprise features usage subsection on SQL 2012 and AlwaysOn in use.
  328. v1.9.9 - 30-01-2015 - Fixed conversion issue in Plan_use_ratio check;
  329. Added HADR info to Database Information subsection;
  330. Added NUMA info to Server Memory subsection.
  331. v1.9.9.1 - 06-02-2015 - Fixed NUMA info collection issue up to SQL 2008R2 introduced in v1.9.9.
  332. v1.9.9.2 - 13-02-2015 - Fixed NUMA info collection issue on SQL 2012 and above introduced in v1.9.9;
  333. Added support to scope only specific databases by ID.
  334. v1.9.9.3 - 15-03-2015 - Fixed some information in "Database Information" section not being collected, introduced in v1.9.9.2.
  335. v1.9.9.5 - 11-04-2015 - Fixed System health error checks conversion error;
  336. Extended Memory Allocations from Memory Clerks checks;
  337. Extended logic to exclude MS shipped databases;
  338. Fixed overflow error in Blocking Chains check if larger than Integer supports;
  339. Fixed insert error in Pending I/O Requests check.
  340. v2.0.0 - 22-04-2015 - Added Declarative Referential Integrity - Untrusted Constraints checks;
  341. Added XTP Index Health Analysis;
  342. Added CCI Index Health Analysis: pseudo-fragmentation for CCI is the ratio of deleted_rows to total_rows;
  343. Renamed "Index Fragmentation Analysis" to "Index Health Analysis" subsection;
  344. Added storage analysis for In-Memory OLTP Engine in Database Information subsection;
  345. Fixed sp_server_diagnostics showing up as blocked session with long blocking time;
  346. Extended AO cluster information;
  347. Database filter now always includes sys DBs.
  348. v2.0.1 - 23-04-2015 - Fixed issue with SQL 2012 in Index Health analysis.
  349. v2.0.2 - 14-05-2015 - Added Default data collections (check for default trace, blackbox trace, SystemHealth xEvent session, sp_server_diagnostics xEvent session);
  350. Extended Objects naming conventions checks to functions;
  351. Added info on Inefficient Plans by CPU and Read I/O;
  352. Improved search for hypothetical objects;
  353. Added script generation to fix issues from Declarative Referential Integrity - Untrusted Constraints checks.
  354. v2.0.2.1 - 18-05-2015 - Fixed Declarative Referential Integrity script generation.
  355. v2.0.3 - 10-09-2015 - Added information about current PMO to Global Trace Flags check when 8048 may be missing.
  356. v2.0.3.1 - 11-09-2015 - Fixed PMO check up to 2008R2.
  357. v2.1 - 9/30/2016 - Fixed issue with LPIM check in SQL Server 2005;
  358. Tuned Memory Allocations from In-Memory OLTP Engine checks;
  359. Tuned I/O stall checks to separate overall stall time from avg latency tests;
  360. Fixed issue with DBs Autogrowth > 1GB check missing files if IFI is enabled;
  361. Updated Cached Query Plans section with new DMV columns;
  362. Workaround for windows version not correct under W10/WS2016;
  363. Added Disk space information;
  364. Added overall support for SQL Server 2012 SP3, 2014 SP2 and 2016 in multiple checks;
  365. Added plans with Inefficient Memory Use to Performance checks.
  366. v2.1.1 - 10/01/2016 - Fixed issues with Database Information subsection in SQL 2005 to 2008R2.
  367. v2.1.2 - 10/25/2016 - Added incremental stats as default to Database Options check;
  368. Added W10 Aniversary Edition to OS versions;
  369. Fixed Indexing per Table subsection accounting for hypotheical indexes.
  370. v2.1.3 - 10/26/2016 - Fixed conversion issue with Account checks;
  371. Fixed negative CPU usage in avg cpu usage last 2h check.
  372. v2.1.4 - 11/08/2016 - Fixed autogrows in last 72h shown in MB instead of KB.
  373. v2.1.5 - 11/17/2016 - Added support for SQLS erver 2016 SP1 (Enterprise_features_usage, LPIM and IFI checks).
  374. v2.1.5.1 - 11/23/2016 - Fixed User DBs with non-default options subsection in SQL 2012.
  375. PURPOSE: Checks SQL Server in scope for some of most common skewed Best Practices. Valid from SQL Server 2005 onwards.
  376. - Contains the following information:
  377. |- Uptime
  378. |- Windows Version and Architecture
  379. |- Disk space
  380. |- HA Information
  381. |- Linked servers info
  382. |- Instance info
  383. |- Resource Governor info
  384. |- Logon triggers
  385. |- Database Information
  386. |- Database file autogrows last 72h
  387. |- Database triggers
  388. |- Enterprise features usage
  389. |- Backups
  390. |- System Configuration
  391. - And performs the following checks (* means only when @ptochecks is ON):
  392. |- Processor
  393. |- Number of available Processors for this instance vs. MaxDOP setting
  394. |- Processor Affinity in NUMA architecture
  395. |- Additional Processor information
  396. |- Processor utilization rate in the last 2 hours *
  397. |- Memory
  398. |- Server Memory
  399. |- RM Task *
  400. |- Clock hands *
  401. |- Buffer Pool Consumers from Buffer Descriptors *
  402. |- Memory Allocations from Memory Clerks *
  403. |- Memory Consumers from In-Memory OLTP Engine *
  404. |- Memory Allocations from In-Memory OLTP Engine *
  405. |- OOM
  406. |- LPIM
  407. |- Pagefile
  408. |- Pagefile
  409. |- I/O
  410. |- I/O Stall subsection (wait for 5s) *
  411. |- Pending disk I/O Requests subsection (wait for a max of 5s) *
  412. |- Server
  413. |- Power plan
  414. |- NTFS block size in volumes that hold database files <> 64KB
  415. |- Disk Fragmentation Analysis (if enabled)
  416. |- Cluster Quorum Model
  417. |- Cluster QFE node equality
  418. |- Cluster NIC Binding order
  419. |- Service Accounts
  420. |- Service Accounts Status
  421. |- Service Accounts and SPN registration
  422. |- Instance
  423. |- Recommended build check
  424. |- Backups
  425. |- Global trace flags
  426. |- System configurations
  427. |- IFI
  428. |- Full Text Configurations
  429. |- Deprecated features *
  430. |- Default data collections (default trace, blackbox trace, SystemHealth xEvent session, sp_server_diagnostics xEvent session)
  431. |- Database and tempDB
  432. |- User objects in master
  433. |- DBs with collation <> master
  434. |- DBs with skewed compatibility level
  435. |- User DBs with non-default options
  436. |- DBs with Sparse files
  437. |- DBs Autogrow in percentage
  438. |- DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled)
  439. |- VLF
  440. |- Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware)
  441. |- tempDB data file configurations
  442. |- tempDB Files autogrow of equal size
  443. |- Performance
  444. |- Perf counters, Waits and Latches (wait for 90s) *
  445. |- Worker thread exhaustion *
  446. |- Blocking Chains *
  447. |- Plan use ratio *
  448. |- Hints usage *
  449. |- Cached Query Plans issues *
  450. |- Inefficient Query Plans *
  451. |- Declarative Referential Integrity - Untrusted Constraints *
  452. |- Indexes and Statistics
  453. |- Statistics update *
  454. |- Statistics sampling *
  455. |- Hypothetical objects *
  456. |- Row Index Fragmentation Analysis (if enabled) *
  457. |- CS Index Health Analysis (if enabled) *
  458. |- XTP Index Health Analysis (if enabled) *
  459. |- Duplicate or Redundant indexes *
  460. |- Unused and rarely used indexes *
  461. |- Indexes with large keys (> 900 bytes) *
  462. |- Indexes with fill factor < 80 pct *
  463. |- Disabled indexes *
  464. |- Non-unique clustered indexes *
  465. |- Clustered Indexes with GUIDs in key *
  466. |- Foreign Keys with no Index *
  467. |- Indexing per Table *
  468. |- Missing Indexes *
  469. |- Naming Convention
  470. |- Objects naming conventions
  471. |- Security
  472. |- Password check
  473. |- Maintenance and Monitoring
  474. |- SQL Agent alerts for severe errors
  475. |- DBCC CHECKDB, Direct Catalog Updates and Data Purity
  476. |- AlwaysOn/Mirroring automatic page repair
  477. |- Suspect pages
  478. |- Replication Errors
  479. |- Errorlog based checks
  480. |- System health checks
  481. DISCLAIMER:
  482. This code and information are provided "AS IS" without warranty of any kind, either expressed or implied.
  483. 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.
  484. IMPORTANT pre-requisites:
  485. - Only a sysadmin/local host admin will be able to perform all checks.
  486. - If you want to perform all checks under non-sysadmin credentials, then that login must be:
  487. Member of serveradmin server role or have the ALTER SETTINGS server permission;
  488. Member of MSDB SQLAgentOperatorRole role, or have SELECT permission on the sysalerts table in MSDB;
  489. Granted EXECUTE permissions on the following extended sprocs to run checks: sp_OACreate, sp_OADestroy, sp_OAGetErrorInfo, xp_enumerrorlogs, xp_fileexist and xp_regenumvalues;
  490. Granted EXECUTE permissions on xp_msver;
  491. Granted the VIEW SERVER STATE permission;
  492. Granted the VIEW DATABASE STATE permission;
  493. Granted EXECUTE permissions on xp_cmdshell or a xp_cmdshell proxy account should exist to run checks that access disk or OS security configurations.
  494. Member of securityadmin role, or have EXECUTE permissions on sp_readerrorlog.
  495. Otherwise some checks will be bypassed and warnings will be shown.
  496. - Powershell must be installed to run checks that access disk configurations, as well as allow execution of remote signed or unsigned scripts.
  497. */
  498. SET NOCOUNT ON;
  499. SET ANSI_WARNINGS ON;
  500. SET QUOTED_IDENTIFIER ON;
  501. SET DATEFORMAT mdy;
  502. RAISERROR (N'Starting Pre-requisites section', 10, 1) WITH NOWAIT
  503. --------------------------------------------------------------------------------------------------------------------------------
  504. -- Pre-requisites section
  505. --------------------------------------------------------------------------------------------------------------------------------
  506. DECLARE @sqlcmd NVARCHAR(max), @params NVARCHAR(500), @sqlmajorver int
  507. /*
  508. Reference: SERVERPROPERTY for sql major, minor and build versions supported after:
  509. @sqlmajorver >= 13 OR (@sqlmajorver = 12 AND @sqlbuild >= 2556 AND @sqlbuild < 4100) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427)
  510. */
  511. SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  512. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 0)
  513. BEGIN
  514. RAISERROR('[WARNING: Only a sysadmin can run ALL the checks]', 16, 1, N'sysadmin')
  515. --RETURN
  516. END;
  517. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 0)
  518. BEGIN
  519. DECLARE @pid int, @pname sysname, @msdbpid int, @masterpid int
  520. DECLARE @permstbl TABLE ([name] sysname);
  521. DECLARE @permstbl_msdb TABLE ([id] tinyint IDENTITY(1,1), [perm] tinyint)
  522. SET @params = '@msdbpid_in int'
  523. SELECT @pid = principal_id, @pname=name FROM master.sys.server_principals (NOLOCK) WHERE sid = SUSER_SID()
  524. SELECT @masterpid = principal_id FROM master.sys.database_principals (NOLOCK) WHERE sid = SUSER_SID()
  525. SELECT @msdbpid = principal_id FROM msdb.sys.database_principals (NOLOCK) WHERE sid = SUSER_SID()
  526. -- Perms 1
  527. IF (ISNULL(IS_SRVROLEMEMBER(N'serveradmin'), 0) <> 1) AND ((SELECT COUNT(l.name)
  528. FROM master.sys.server_permissions p (NOLOCK) INNER JOIN master.sys.server_principals l (NOLOCK)
  529. ON p.grantee_principal_id = l.principal_id
  530. AND p.class = 100 -- Server
  531. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  532. AND l.is_disabled = 0
  533. AND p.permission_name = 'ALTER SETTINGS'
  534. AND QUOTENAME(l.name) = QUOTENAME(@pname)) = 0)
  535. BEGIN
  536. 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')
  537. RETURN
  538. END
  539. ELSE IF (ISNULL(IS_SRVROLEMEMBER(N'serveradmin'), 0) <> 1) AND ((SELECT COUNT(l.name)
  540. FROM master.sys.server_permissions p (NOLOCK) INNER JOIN sys.server_principals l (NOLOCK)
  541. ON p.grantee_principal_id = l.principal_id
  542. AND p.class = 100 -- Server
  543. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  544. AND l.is_disabled = 0
  545. AND p.permission_name = 'VIEW SERVER STATE'
  546. AND QUOTENAME(l.name) = QUOTENAME(@pname)) = 0)
  547. BEGIN
  548. 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')
  549. RETURN
  550. END
  551. -- Perms 2
  552. INSERT INTO @permstbl
  553. SELECT a.name
  554. FROM master.sys.all_objects a (NOLOCK) INNER JOIN master.sys.database_permissions b (NOLOCK) ON a.[OBJECT_ID] = b.major_id
  555. WHERE a.type IN ('P', 'X') AND b.grantee_principal_id <>0
  556. AND b.grantee_principal_id <>2
  557. AND b.grantee_principal_id = @masterpid;
  558. INSERT INTO @permstbl_msdb ([perm])
  559. EXECUTE sp_executesql N'USE msdb; SELECT COUNT([name])
  560. FROM msdb.sys.sysusers (NOLOCK) WHERE [uid] IN (SELECT [groupuid]
  561. FROM msdb.sys.sysmembers (NOLOCK) WHERE [memberuid] = @msdbpid_in)
  562. AND [name] = ''SQLAgentOperatorRole''', @params, @msdbpid_in = @msdbpid;
  563. INSERT INTO @permstbl_msdb ([perm])
  564. EXECUTE sp_executesql N'USE msdb; SELECT COUNT(dp.grantee_principal_id)
  565. FROM msdb.sys.tables AS tbl (NOLOCK)
  566. INNER JOIN msdb.sys.database_permissions AS dp (NOLOCK) ON dp.major_id=tbl.object_id AND dp.class=1
  567. INNER JOIN msdb.sys.database_principals AS grantor_principal (NOLOCK) ON grantor_principal.principal_id = dp.grantor_principal_id
  568. INNER JOIN msdb.sys.database_principals AS grantee_principal (NOLOCK) ON grantee_principal.principal_id = dp.grantee_principal_id
  569. WHERE dp.state = ''G''
  570. AND dp.grantee_principal_id = @msdbpid_in
  571. AND dp.type = ''SL''', @params, @msdbpid_in = @msdbpid;
  572. IF (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 1) = 0 AND (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 2) = 0
  573. BEGIN
  574. 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')
  575. --RETURN
  576. END
  577. 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)
  578. BEGIN
  579. 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')
  580. --RETURN
  581. END
  582. 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
  583. BEGIN
  584. 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')
  585. --RETURN
  586. END
  587. ELSE IF (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') = 0 OR
  588. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') = 0 OR
  589. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') = 0 OR
  590. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') = 0 OR
  591. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') = 0 OR
  592. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 0 OR
  593. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 0 OR
  594. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_servicecontrol') = 0
  595. BEGIN
  596. 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')
  597. --RETURN
  598. END
  599. ELSE IF (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_msver') = 0 AND @sqlmajorver < 11
  600. BEGIN
  601. RAISERROR('[WARNING: Must be granted EXECUTE permissions on xp_msver to run full scope of checks]', 16, 1, N'extended_sprocs')
  602. --RETURN
  603. END
  604. END;
  605. -- Declare Global Variables
  606. DECLARE @UpTime VARCHAR(12),@StartDate DATETIME
  607. DECLARE @agt smallint, @ole smallint, @sao smallint, @xcmd smallint
  608. DECLARE @ErrorSeverity int, @ErrorState int, @ErrorMessage NVARCHAR(4000)
  609. DECLARE @CMD NVARCHAR(4000)
  610. DECLARE @path NVARCHAR(2048)
  611. DECLARE @sqlminorver int, @sqlbuild int, @clustered bit, @winver VARCHAR(5), @server VARCHAR(128), @instancename NVARCHAR(128), @arch smallint, @winsp VARCHAR(25), @SystemManufacturer VARCHAR(128)
  612. DECLARE @existout int, @FSO int, @FS int, @OLEResult int, @FileID int
  613. DECLARE @FileName VARCHAR(200), @Text1 VARCHAR(2000), @CMD2 VARCHAR(100)
  614. DECLARE @src VARCHAR(255), @desc VARCHAR(255), @psavail VARCHAR(20), @psver tinyint
  615. DECLARE @dbid int, @dbname VARCHAR(1000)
  616. SELECT @instancename = CONVERT(VARCHAR(128),SERVERPROPERTY('InstanceName'))
  617. SELECT @server = RTRIM(CONVERT(VARCHAR(128), SERVERPROPERTY('MachineName')))
  618. --SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  619. SELECT @sqlminorver = CONVERT(int, (@@microsoftversion / 0x10000) & 0xff);
  620. SELECT @sqlbuild = CONVERT(int, @@microsoftversion & 0xffff);
  621. SELECT @clustered = CONVERT(bit,ISNULL(SERVERPROPERTY('IsClustered'),0))
  622. -- Test Powershell policy
  623. IF @allow_xpcmdshell = 1
  624. BEGIN
  625. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  626. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  627. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  628. AND (SELECT COUNT(l.name)
  629. FROM sys.server_permissions p JOIN sys.server_principals l
  630. ON p.grantee_principal_id = l.principal_id
  631. AND p.class = 100 -- Server
  632. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  633. AND l.is_disabled = 0
  634. AND p.permission_name = 'ALTER SETTINGS'
  635. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  636. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  637. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  638. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0)))
  639. BEGIN
  640. DECLARE @pstbl_avail TABLE ([KeyExist] int)
  641. BEGIN TRY
  642. INSERT INTO @pstbl_avail
  643. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\PowerShell\1' -- check if Powershell is installed
  644. END TRY
  645. BEGIN CATCH
  646. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  647. SELECT @ErrorMessage = 'Could not determine if Powershell is installed - Error raised in TRY block. ' + ERROR_MESSAGE()
  648. RAISERROR (@ErrorMessage, 16, 1);
  649. END CATCH
  650. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  651. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  652. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  653. RAISERROR ('|-Configuration options set for Powershell enablement verification', 10, 1) WITH NOWAIT
  654. IF @sao = 0
  655. BEGIN
  656. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  657. END
  658. IF @xcmd = 0
  659. BEGIN
  660. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  661. END
  662. IF @ole = 0
  663. BEGIN
  664. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  665. END
  666. IF (SELECT [KeyExist] FROM @pstbl_avail) = 1
  667. BEGIN
  668. DECLARE @psavail_output TABLE ([PS_OUTPUT] VARCHAR(2048));
  669. INSERT INTO @psavail_output
  670. EXEC master.dbo.xp_cmdshell N'%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Get-ExecutionPolicy"'
  671. SELECT @psavail = [PS_OUTPUT] FROM @psavail_output WHERE [PS_OUTPUT] IS NOT NULL;
  672. END
  673. ELSE
  674. BEGIN
  675. RAISERROR (' [WARNING: Powershell is not installed. Install WinRM to proceed with PS based checks]',16,1);
  676. END
  677. IF (@psavail IS NOT NULL AND @psavail NOT IN ('RemoteSigned','Unrestricted'))
  678. RAISERROR (' [WARNING: Execution of Powershell scripts is disabled on this system.
  679. To change the execution policy, type the following command in Powershell console: Set-ExecutionPolicy RemoteSigned
  680. 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:
  681. Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  682. AllSigned - Only scripts signed by a trusted publisher can be run.
  683. RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  684. |- REQUIRED by BP Check
  685. Unrestricted - No restrictions; all Windows PowerShell scripts can be run.]',16,1);
  686. IF (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  687. BEGIN
  688. RAISERROR ('|- [INFORMATION: Powershell is installed and enabled for script execution]', 10, 1) WITH NOWAIT
  689. DECLARE @psver_output TABLE ([PS_OUTPUT] VARCHAR(1024));
  690. INSERT INTO @psver_output
  691. EXEC master.dbo.xp_cmdshell N'%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Get-Host | Format-Table -Property Version"'
  692. -- Gets PS version, as commands issued to PS v1 do not support -File
  693. SELECT @psver = ISNULL(LEFT([PS_OUTPUT],1),2) FROM @psver_output WHERE [PS_OUTPUT] IS NOT NULL AND ISNUMERIC(LEFT([PS_OUTPUT],1)) = 1;
  694. SET @ErrorMessage = '|- [INFORMATION: Installed Powershell is version ' + CONVERT(CHAR(1), @psver) + ']'
  695. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  696. END;
  697. IF @xcmd = 0
  698. BEGIN
  699. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  700. END
  701. IF @ole = 0
  702. BEGIN
  703. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  704. END
  705. IF @sao = 0
  706. BEGIN
  707. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  708. END;
  709. END
  710. ELSE
  711. BEGIN
  712. RAISERROR(' [WARNING: Missing permissions for Powershell enablement verification]', 16, 1, N'sysadmin')
  713. --RETURN
  714. END
  715. END;
  716. --------------------------------------------------------------------------------------------------------------------------------
  717. -- Information section
  718. --------------------------------------------------------------------------------------------------------------------------------
  719. RAISERROR (N'Starting Information section', 10, 1) WITH NOWAIT
  720. --------------------------------------------------------------------------------------------------------------------------------
  721. -- Uptime subsection
  722. --------------------------------------------------------------------------------------------------------------------------------
  723. RAISERROR (N'|-Starting Uptime', 10, 1) WITH NOWAIT
  724. IF @sqlmajorver < 10
  725. BEGIN
  726. SET @sqlcmd = N'SELECT @UpTimeOUT = DATEDIFF(mi, login_time, GETDATE()), @StartDateOUT = login_time FROM master..sysprocesses (NOLOCK) WHERE spid = 1';
  727. END
  728. ELSE
  729. BEGIN
  730. SET @sqlcmd = N'SELECT @UpTimeOUT = DATEDIFF(mi,sqlserver_start_time,GETDATE()), @StartDateOUT = sqlserver_start_time FROM sys.dm_os_sys_info (NOLOCK)';
  731. END
  732. SET @params = N'@UpTimeOUT VARCHAR(12) OUTPUT, @StartDateOUT DATETIME OUTPUT';
  733. EXECUTE sp_executesql @sqlcmd, @params, @UpTimeOUT=@UpTime OUTPUT, @StartDateOUT=@StartDate OUTPUT;
  734. 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
  735. --------------------------------------------------------------------------------------------------------------------------------
  736. -- Windows Version and Architecture subsection
  737. --------------------------------------------------------------------------------------------------------------------------------
  738. RAISERROR (N'|-Starting Windows Version and Architecture', 10, 1) WITH NOWAIT
  739. IF @sqlmajorver >= 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  740. BEGIN
  741. 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)';
  742. SET @params = N'@winverOUT VARCHAR(5) OUTPUT, @winspOUT VARCHAR(25) OUTPUT, @archOUT smallint OUTPUT';
  743. EXECUTE sp_executesql @sqlcmd, @params, @winverOUT=@winver OUTPUT, @winspOUT=@winsp OUTPUT, @archOUT=@arch OUTPUT;
  744. END
  745. ELSE
  746. BEGIN
  747. BEGIN TRY
  748. DECLARE @str VARCHAR(500), @str2 VARCHAR(500), @str3 VARCHAR(500)
  749. DECLARE @sysinfo TABLE (id int,
  750. [Name] NVARCHAR(256),
  751. Internal_Value bigint,
  752. Character_Value NVARCHAR(256));
  753. INSERT INTO @sysinfo
  754. EXEC xp_msver;
  755. 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
  756. FROM @sysinfo
  757. WHERE [Name] LIKE 'WindowsVersion%';
  758. SELECT @arch = CASE WHEN RTRIM(Character_Value) LIKE '%x64%' OR RTRIM(Character_Value) LIKE '%AMD64%' THEN 64
  759. WHEN RTRIM(Character_Value) LIKE '%x86%' OR RTRIM(Character_Value) LIKE '%32%' THEN 32
  760. WHEN RTRIM(Character_Value) LIKE '%IA64%' THEN 128 END
  761. FROM @sysinfo
  762. WHERE [Name] LIKE 'Platform%';
  763. SET @str = (SELECT @@VERSION)
  764. SELECT @str2 = RIGHT(@str, LEN(@str)-CHARINDEX('Windows',@str) + 1)
  765. SELECT @str3 = RIGHT(@str2, LEN(@str2)-CHARINDEX(': ',@str2))
  766. SELECT @winsp = LTRIM(LEFT(@str3, CHARINDEX(')',@str3) -1))
  767. END TRY
  768. BEGIN CATCH
  769. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  770. SELECT @ErrorMessage = 'Windows Version and Architecture subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  771. RAISERROR (@ErrorMessage, 16, 1);
  772. END CATCH
  773. END;
  774. DECLARE @machineinfo TABLE ([Value] NVARCHAR(256), [Data] NVARCHAR(256))
  775. INSERT INTO @machineinfo
  776. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemManufacturer';
  777. INSERT INTO @machineinfo
  778. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemProductName';
  779. INSERT INTO @machineinfo
  780. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemFamily';
  781. INSERT INTO @machineinfo
  782. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSVendor';
  783. INSERT INTO @machineinfo
  784. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSVersion';
  785. INSERT INTO @machineinfo
  786. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSReleaseDate';
  787. INSERT INTO @machineinfo
  788. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\CentralProcessor\0','ProcessorNameString';
  789. SELECT @SystemManufacturer = [Data] FROM @machineinfo WHERE [Value] = 'SystemManufacturer';
  790. SELECT 'Information' AS [Category], 'Machine' AS [Information],
  791. CASE @winver WHEN '5.2' THEN 'XP/WS2003'
  792. WHEN '6.0' THEN 'Vista/WS2008'
  793. WHEN '6.1' THEN 'W7/WS2008R2'
  794. WHEN '6.2' THEN 'W8/WS2012'
  795. WHEN '6.3' THEN 'W8.1/WS2012R2'
  796. WHEN '10.0' THEN 'W10/WS2016'
  797. END AS [Windows_Version],
  798. @winsp AS [Service_Pack_Level],
  799. @arch AS [Architecture],
  800. SERVERPROPERTY('MachineName') AS [Machine_Name],
  801. SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [NetBIOS_Name],
  802. @SystemManufacturer AS [System_Manufacturer],
  803. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'SystemFamily') AS [System_Family],
  804. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'SystemProductName') AS [System_ProductName],
  805. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSVendor') AS [BIOS_Vendor],
  806. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSVersion') AS [BIOS_Version],
  807. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSReleaseDate') AS [BIOS_Release_Date],
  808. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'ProcessorNameString') AS [Processor_Name];
  809. --------------------------------------------------------------------------------------------------------------------------------
  810. -- Disk space subsection
  811. --------------------------------------------------------------------------------------------------------------------------------
  812. RAISERROR (N'|-Starting Disk space', 10, 1) WITH NOWAIT
  813. SELECT DISTINCT 'Information' AS [Category], 'Disk_Space' AS [Information], vs.logical_volume_name,
  814. vs.volume_mount_point, vs.file_system_type, CONVERT(int,vs.total_bytes/1048576.0) AS TotalSpace_MB,
  815. CONVERT(int,vs.available_bytes/1048576.0) AS FreeSpace_MB, vs.is_compressed
  816. FROM sys.master_files mf
  817. CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) vs
  818. ORDER BY FreeSpace_MB ASC;
  819. --------------------------------------------------------------------------------------------------------------------------------
  820. -- HA Information subsection
  821. --------------------------------------------------------------------------------------------------------------------------------
  822. RAISERROR (N'|-Starting HA Information', 10, 1) WITH NOWAIT
  823. IF @clustered = 1
  824. BEGIN
  825. IF @sqlmajorver < 11
  826. BEGIN
  827. EXEC ('SELECT ''Information'' AS [Category], ''Cluster'' AS [Information], NodeName AS node_name FROM sys.dm_os_cluster_nodes (NOLOCK)')
  828. END
  829. ELSE
  830. BEGIN
  831. EXEC ('SELECT ''Information'' AS [Category], ''Cluster'' AS [Information], NodeName AS node_name, status_description, is_current_owner FROM sys.dm_os_cluster_nodes (NOLOCK)')
  832. END
  833. SELECT 'Information' AS [Category], 'Cluster' AS [Information], DriveName AS cluster_shared_drives FROM sys.dm_io_cluster_shared_drives (NOLOCK)
  834. END
  835. ELSE
  836. BEGIN
  837. SELECT 'Information' AS [Category], 'Cluster' AS [Information], 'NOT_CLUSTERED' AS [Status]
  838. END;
  839. IF @sqlmajorver > 10
  840. BEGIN
  841. DECLARE @IsHadrEnabled tinyint, @HadrManagerStatus tinyint
  842. SELECT @IsHadrEnabled = CONVERT(tinyint, SERVERPROPERTY('IsHadrEnabled'))
  843. SELECT @HadrManagerStatus = CONVERT(tinyint, SERVERPROPERTY('HadrManagerStatus'))
  844. SELECT 'Information' AS [Category], 'AlwaysOn_AG' AS [Information],
  845. CASE @IsHadrEnabled WHEN 0 THEN 'Disabled'
  846. WHEN 1 THEN 'Enabled' END AS [AlwaysOn_Availability_Groups],
  847. CASE WHEN @IsHadrEnabled = 1 THEN
  848. CASE @HadrManagerStatus WHEN 0 THEN '[Not started, pending communication]'
  849. WHEN 1 THEN '[Started and running]'
  850. WHEN 2 THEN '[Not started and failed]'
  851. END
  852. END AS [Status];
  853. IF @IsHadrEnabled = 1
  854. BEGIN
  855. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster)
  856. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster' AS [Information], cluster_name, quorum_type_desc, quorum_state_desc
  857. FROM sys.dm_hadr_cluster;
  858. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster_members)
  859. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster_Members' AS [Information], member_name, member_type_desc, member_state_desc, number_of_quorum_votes
  860. FROM sys.dm_hadr_cluster_members;
  861. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster_networks)
  862. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster_Networks' AS [Information], member_name, network_subnet_ip, network_subnet_ipv4_mask, is_public, is_ipv4
  863. FROM sys.dm_hadr_cluster_networks;
  864. END;
  865. IF @ptochecks = 1 AND @IsHadrEnabled = 1
  866. BEGIN
  867. -- Note: If low_water_mark_for_ghosts number is not increasing over time, it implies that ghost cleanup might not happen.
  868. SELECT 'Information' AS [Category], 'AlwaysOn_Replicas' AS [Information], database_id, group_id, replica_id, group_database_id, is_local, synchronization_state_desc,
  869. is_commit_participant, synchronization_health_desc, database_state_desc, is_suspended, suspend_reason_desc, last_sent_time, last_received_time, last_hardened_time,
  870. last_redone_time, log_send_queue_size, log_send_rate, redo_queue_size, redo_rate, filestream_send_rate, last_commit_time, low_water_mark_for_ghosts
  871. FROM sys.dm_hadr_database_replica_states;
  872. SELECT 'Information' AS [Category], 'AlwaysOn_Replica_Cluster' AS [Information], replica_id, group_database_id, database_name, is_failover_ready, is_pending_secondary_suspend,
  873. is_database_joined, recovery_lsn, truncation_lsn
  874. FROM sys.dm_hadr_database_replica_cluster_states;
  875. END
  876. END;
  877. --------------------------------------------------------------------------------------------------------------------------------
  878. -- Linked servers info subsection
  879. --------------------------------------------------------------------------------------------------------------------------------
  880. RAISERROR (N'|-Starting Linked servers info', 10, 1) WITH NOWAIT
  881. 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
  882. BEGIN
  883. IF @sqlmajorver > 9
  884. BEGIN
  885. EXEC ('SELECT ''Information'' AS [Category], ''Linked_servers'' AS [Information], s.name, s.product,
  886. s.provider, s.data_source, s.location, s.provider_string, s.catalog, s.connect_timeout,
  887. s.query_timeout, s.is_linked, s.is_remote_login_enabled, s.is_rpc_out_enabled,
  888. s.is_data_access_enabled, s.is_collation_compatible, s.uses_remote_collation, s.collation_name,
  889. s.lazy_schema_validation, s.is_system, s.is_publisher, s.is_subscriber, s.is_distributor,
  890. s.is_nonsql_subscriber, s.is_remote_proc_transaction_promotion_enabled,
  891. s.modify_date, CASE WHEN l.local_principal_id = 0 THEN ''local or wildcard'' ELSE p.name END AS [local_principal],
  892. CASE WHEN l.uses_self_credential = 0 THEN ''use own credentials'' ELSE ''use supplied username and pwd'' END AS uses_self_credential,
  893. l.remote_name, l.modify_date AS [linked_login_modify_date]
  894. FROM sys.servers AS s (NOLOCK)
  895. INNER JOIN sys.linked_logins AS l (NOLOCK) ON s.server_id = l.server_id
  896. INNER JOIN sys.server_principals AS p (NOLOCK) ON p.principal_id = l.local_principal_id
  897. WHERE s.is_linked = 1')
  898. END
  899. ELSE
  900. BEGIN
  901. EXEC ('SELECT ''Information'' AS [Category], ''Linked_servers'' AS [Information], s.name, s.product,
  902. s.provider, s.data_source, s.location, s.provider_string, s.catalog, s.connect_timeout,
  903. s.query_timeout, s.is_linked, s.is_remote_login_enabled, s.is_rpc_out_enabled,
  904. s.is_data_access_enabled, s.is_collation_compatible, s.uses_remote_collation, s.collation_name,
  905. s.lazy_schema_validation, s.is_system, s.is_publisher, s.is_subscriber, s.is_distributor,
  906. s.is_nonsql_subscriber, s.modify_date, CASE WHEN l.local_principal_id = 0 THEN ''local or wildcard'' ELSE p.name END AS [local_principal],
  907. CASE WHEN l.uses_self_credential = 0 THEN ''use own credentials'' ELSE ''use supplied username and pwd'' END AS uses_self_credential,
  908. l.remote_name, l.modify_date AS [linked_login_modify_date]
  909. FROM sys.servers AS s (NOLOCK)
  910. INNER JOIN sys.linked_logins AS l (NOLOCK) ON s.server_id = l.server_id
  911. INNER JOIN sys.server_principals AS p (NOLOCK) ON p.principal_id = l.local_principal_id
  912. WHERE s.is_linked = 1')
  913. END
  914. END
  915. ELSE
  916. BEGIN
  917. SELECT 'Information' AS [Category], 'Linked_servers' AS [Information], '[None]' AS [Status]
  918. END;
  919. --------------------------------------------------------------------------------------------------------------------------------
  920. -- Instance info subsection
  921. --------------------------------------------------------------------------------------------------------------------------------
  922. RAISERROR (N'|-Starting Instance info', 10, 1) WITH NOWAIT
  923. DECLARE @port VARCHAR(5), @replication int, @RegKey NVARCHAR(255), @cpuaffin VARCHAR(255), @cpucount int, @numa int
  924. DECLARE @i int, @cpuaffin_fixed VARCHAR(300)
  925. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild < 2500)
  926. BEGIN
  927. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  928. BEGIN
  929. BEGIN TRY
  930. SELECT @RegKey = CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) IS NULL THEN N'Software\Microsoft\MSSQLServer\MSSQLServer\SuperSocketNetLib\Tcp'
  931. ELSE N'Software\Microsoft\Microsoft SQL Server\' + CAST(SERVERPROPERTY('InstanceName') AS NVARCHAR(128)) + N'\MSSQLServer\SuperSocketNetLib\Tcp' END
  932. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'TcpPort', @port OUTPUT, NO_OUTPUT
  933. END TRY
  934. BEGIN CATCH
  935. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  936. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  937. RAISERROR (@ErrorMessage, 16, 1);
  938. END CATCH
  939. END
  940. ELSE
  941. BEGIN
  942. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing TCP port check]', 16, 1, N'sysadmin')
  943. --RETURN
  944. END
  945. END
  946. ELSE
  947. BEGIN
  948. BEGIN TRY
  949. SET @sqlcmd = N'SELECT @portOUT = MAX(CONVERT(int,CONVERT(float,value_data))) FROM sys.dm_server_registry WHERE registry_key LIKE ''%MSSQLServer\SuperSocketNetLib\Tcp\%'' AND value_name LIKE N''%TcpPort%'' AND CONVERT(float,value_data) > 0;';
  950. SET @params = N'@portOUT int OUTPUT';
  951. EXECUTE sp_executesql @sqlcmd, @params, @portOUT = @port OUTPUT;
  952. IF @port IS NULL
  953. BEGIN
  954. SET @sqlcmd = N'SELECT @portOUT = CONVERT(int,CONVERT(float,value_data)) FROM sys.dm_server_registry WHERE registry_key LIKE ''%MSSQLServer\SuperSocketNetLib\Tcp\%'' AND value_name LIKE N''%TcpDynamicPort%'' AND CONVERT(float,value_data) > 0;';
  955. SET @params = N'@portOUT int OUTPUT';
  956. EXECUTE sp_executesql @sqlcmd, @params, @portOUT = @port OUTPUT;
  957. END
  958. END TRY
  959. BEGIN CATCH
  960. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  961. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  962. RAISERROR (@ErrorMessage, 16, 1);
  963. END CATCH
  964. END
  965. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 1)
  966. BEGIN
  967. BEGIN TRY
  968. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Replication', N'IsInstalled', @replication OUTPUT, NO_OUTPUT
  969. END TRY
  970. BEGIN CATCH
  971. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  972. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  973. RAISERROR (@ErrorMessage, 16, 1);
  974. END CATCH
  975. END
  976. ELSE
  977. BEGIN
  978. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing replication check]', 16, 1, N'sysadmin')
  979. --RETURN
  980. END
  981. SELECT @cpucount = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64
  982. SELECT @numa = COUNT(DISTINCT parent_node_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64;
  983. ;WITH bits AS
  984. (SELECT 7 AS N, 128 AS E UNION ALL SELECT 6, 64 UNION ALL
  985. SELECT 5, 32 UNION ALL SELECT 4, 16 UNION ALL SELECT 3, 8 UNION ALL
  986. SELECT 2, 4 UNION ALL SELECT 1, 2 UNION ALL SELECT 0, 1),
  987. bytes AS
  988. (SELECT 1 M UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
  989. SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL
  990. SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9)
  991. -- CPU Affinity is shown highest to lowest CPU ID
  992. SELECT @cpuaffin = CASE WHEN [value] = 0 THEN REPLICATE('1', @cpucount)
  993. ELSE RIGHT((SELECT ((CONVERT(tinyint, SUBSTRING(CONVERT(binary(9), [value]), M, 1)) & E) / E) AS [text()]
  994. FROM bits CROSS JOIN bytes
  995. ORDER BY M, N DESC
  996. FOR XML PATH('')), @cpucount) END
  997. FROM sys.configurations (NOLOCK)
  998. WHERE name = 'affinity mask';
  999. SET @cpuaffin_fixed = @cpuaffin
  1000. IF @numa > 1
  1001. BEGIN
  1002. -- format binary mask by node for better reading
  1003. SET @i = @cpucount/@numa + 1
  1004. WHILE @i <= @cpucount
  1005. BEGIN
  1006. SELECT @cpuaffin_fixed = STUFF(@cpuaffin_fixed, @i, 1, '_' + SUBSTRING(@cpuaffin, @i, 1))
  1007. SET @i = @i + @cpucount/@numa + 1
  1008. END
  1009. END
  1010. SELECT 'Information' AS [Category], 'Instance' AS [Information],
  1011. (CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) IS NULL THEN 'DEFAULT_INSTANCE'
  1012. ELSE CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) END) AS Instance_Name,
  1013. (CASE WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'CLUSTERED'
  1014. WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'NOT_CLUSTERED'
  1015. ELSE 'INVALID INPUT/ERROR' END) AS Failover_Clustered,
  1016. /*The version of SQL Server instance in the form: major.minor.build*/
  1017. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductVersion')) AS Product_Version,
  1018. /*Level of the version of SQL Server Instance*/
  1019. 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
  1020. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductBuildType'))
  1021. ELSE 'NA' END AS Product_Build_Type,
  1022. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductLevel')) AS Product_Level,
  1023. 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
  1024. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductUpdateLevel'))
  1025. ELSE 'NA' END AS Product_Update_Level,
  1026. 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
  1027. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductUpdateReference'))
  1028. ELSE 'NA' END AS Product_Update_Ref_KB,
  1029. CONVERT(VARCHAR(128), SERVERPROPERTY('Edition')) AS Edition,
  1030. CONVERT(VARCHAR(128), SERVERPROPERTY('MachineName')) AS Machine_Name,
  1031. RTRIM(@port) AS TCP_Port,
  1032. @@SERVICENAME AS Service_Name,
  1033. /*To identify which sqlservr.exe belongs to this instance*/
  1034. SERVERPROPERTY('ProcessID') AS Process_ID,
  1035. CONVERT(VARCHAR(128), SERVERPROPERTY('ServerName')) AS Server_Name,
  1036. @cpuaffin_fixed AS Affinity_Mask_Bitmask,
  1037. CONVERT(VARCHAR(128), SERVERPROPERTY('Collation')) AS [Server_Collation],
  1038. (CASE WHEN @replication = 1 THEN 'Installed'
  1039. WHEN @replication = 0 THEN 'Not_Installed'
  1040. ELSE 'INVALID INPUT/ERROR' END) AS Replication_Components_Installation,
  1041. (CASE WHEN SERVERPROPERTY('IsFullTextInstalled') = 1 THEN 'Installed'
  1042. WHEN SERVERPROPERTY('IsFulltextInstalled') = 0 THEN 'Not_Installed'
  1043. ELSE 'INVALID INPUT/ERROR' END) AS Full_Text_Installation,
  1044. (CASE WHEN SERVERPROPERTY('IsIntegratedSecurityOnly') = 1 THEN 'Integrated_Security'
  1045. WHEN SERVERPROPERTY('IsIntegratedSecurityOnly') = 0 THEN 'SQL_Server_Security'
  1046. ELSE 'INVALID INPUT/ERROR' END) AS [Security],
  1047. (CASE WHEN SERVERPROPERTY('IsSingleUser') = 1 THEN 'Single_User'
  1048. WHEN SERVERPROPERTY('IsSingleUser') = 0 THEN 'Multi_User'
  1049. ELSE 'INVALID INPUT/ERROR' END) AS [Single_User],
  1050. (CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('LicenseType')) = 'PER_SEAT' THEN 'Per_Seat_Mode'
  1051. WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('LicenseType')) = 'PER_PROCESSOR' THEN 'Per_Processor_Mode'
  1052. ELSE 'Disabled' END) AS License_Type, -- From SQL Server 2008R2 always returns DISABLED.
  1053. CONVERT(NVARCHAR(128), SERVERPROPERTY('BuildClrVersion')) AS CLR_Version,
  1054. CASE WHEN @sqlmajorver >= 10 THEN
  1055. CASE WHEN SERVERPROPERTY('FilestreamConfiguredLevel') = 0 THEN 'Disabled'
  1056. WHEN SERVERPROPERTY('FilestreamConfiguredLevel') = 1 THEN 'Enabled_for_TSQL'
  1057. ELSE 'Enabled for TSQL and Win32' END
  1058. ELSE 'Not compatible' END AS Filestream_Configured_Level,
  1059. CASE WHEN @sqlmajorver >= 10 THEN
  1060. CASE WHEN SERVERPROPERTY('FilestreamEffectiveLevel') = 0 THEN 'Disabled'
  1061. WHEN SERVERPROPERTY('FilestreamEffectiveLevel') = 1 THEN 'Enabled_for_TSQL'
  1062. ELSE 'Enabled for TSQL and Win32' END
  1063. ELSE 'Not compatible' END AS Filestream_Effective_Level,
  1064. CASE WHEN @sqlmajorver >= 10 THEN
  1065. SERVERPROPERTY('FilestreamShareName')
  1066. ELSE 'Not compatible' END AS Filestream_Share_Name,
  1067. CASE WHEN @sqlmajorver >= 12 THEN
  1068. SERVERPROPERTY('IsXTPSupported')
  1069. ELSE 'Not compatible' END AS XTP_Compatible,
  1070. CASE WHEN @sqlmajorver >= 13 THEN
  1071. SERVERPROPERTY('IsPolybaseInstalled')
  1072. ELSE 'Not compatible' END AS Polybase_Installed,
  1073. CASE WHEN @sqlmajorver >= 13 THEN
  1074. SERVERPROPERTY('IsAdvancedAnalyticsInstalled')
  1075. ELSE 'Not compatible' END AS R_Services_Installed;
  1076. --------------------------------------------------------------------------------------------------------------------------------
  1077. -- Buffer Pool Extension info subsection
  1078. --------------------------------------------------------------------------------------------------------------------------------
  1079. RAISERROR (N'|-Starting Buffer Pool Extension info', 10, 1) WITH NOWAIT
  1080. IF @sqlmajorver > 11
  1081. BEGIN
  1082. SELECT 'Information' AS [Category], 'BP_Extension' AS [Information],
  1083. CASE WHEN state = 0 THEN 'BP_Extension_Disabled'
  1084. WHEN state = 1 THEN 'BP_Extension_is_Disabling'
  1085. WHEN state = 3 THEN 'BP_Extension_is_Enabling'
  1086. WHEN state = 5 THEN 'BP_Extension_Enabled'
  1087. END AS state,
  1088. [path], current_size_in_kb
  1089. FROM sys.dm_os_buffer_pool_extension_configuration
  1090. END
  1091. ELSE
  1092. BEGIN
  1093. SELECT 'Information' AS [Category], 'BP_Extension' AS [Information], '[NA]' AS state
  1094. END;
  1095. --------------------------------------------------------------------------------------------------------------------------------
  1096. -- Resource Governor info subsection
  1097. --------------------------------------------------------------------------------------------------------------------------------
  1098. RAISERROR (N'|-Starting Resource Governor info', 10, 1) WITH NOWAIT
  1099. IF @sqlmajorver > 9
  1100. BEGIN
  1101. 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
  1102. FROM sys.dm_resource_governor_configuration
  1103. 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,
  1104. 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,
  1105. 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 + '
  1106. 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
  1107. EXECUTE sp_executesql @sqlcmd
  1108. 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,
  1109. 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,
  1110. total_lock_wait_time_ms, total_query_optimization_count, total_suboptimal_plan_generation_count, total_reduced_memgrant_count, max_request_grant_memory_kb,
  1111. active_parallel_thread_count, importance, request_max_memory_grant_percent, request_max_cpu_time_sec, request_memory_grant_timeout_sec,
  1112. group_max_requests, max_dop' + CASE WHEN @sqlmajorver > 10 THEN ', effective_max_dop' ELSE '' END + '
  1113. FROM sys.dm_resource_governor_workload_groups'
  1114. EXECUTE sp_executesql @sqlcmd
  1115. END;
  1116. --------------------------------------------------------------------------------------------------------------------------------
  1117. -- Logon triggers subsection
  1118. --------------------------------------------------------------------------------------------------------------------------------
  1119. RAISERROR (N'|-Starting Logon triggers', 10, 1) WITH NOWAIT
  1120. IF (SELECT COUNT([name]) FROM sys.server_triggers WHERE is_disabled = 0 AND is_ms_shipped = 0) > 0
  1121. BEGIN
  1122. SELECT 'Information' AS [Category], 'Logon_Triggers' AS [Information], name AS [Trigger_Name], type_desc AS [Trigger_Type],create_date, modify_date
  1123. FROM sys.server_triggers WHERE is_disabled = 0 AND is_ms_shipped = 0
  1124. ORDER BY name;
  1125. END
  1126. ELSE
  1127. BEGIN
  1128. SELECT 'Information' AS [Category], 'Logon_Triggers' AS [Information], '[NA]' AS [Comment]
  1129. END;
  1130. --------------------------------------------------------------------------------------------------------------------------------
  1131. -- Database Information subsection
  1132. --------------------------------------------------------------------------------------------------------------------------------
  1133. RAISERROR (N'|-Starting Database Information', 10, 1) WITH NOWAIT
  1134. RAISERROR (N' |-Building DB list', 10, 1) WITH NOWAIT
  1135. DECLARE @curdbname VARCHAR(1000), @curdbid int, @currole tinyint, @cursecondary_role_allow_connections tinyint, @state tinyint
  1136. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  1137. DROP TABLE #tmpdbs0;
  1138. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  1139. 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);
  1140. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  1141. DROP TABLE #tmpdbfiledetail;
  1142. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  1143. 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)
  1144. IF @sqlmajorver < 11
  1145. BEGIN
  1146. INSERT INTO #tmpdbs0 ([dbid], [dbname], [compatibility_level], is_read_only, [state], is_distributor, [role], [secondary_role_allow_connections], [isdone])
  1147. SELECT database_id, name, [compatibility_level], is_read_only, [state], is_distributor, 1, 1, 0 FROM master.sys.databases (NOLOCK)
  1148. END;
  1149. IF @sqlmajorver > 10
  1150. BEGIN
  1151. 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])
  1152. 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
  1153. FROM master.sys.databases sd (NOLOCK)
  1154. LEFT JOIN sys.dm_hadr_database_replica_states d ON sd.database_id = d.database_id
  1155. LEFT JOIN sys.availability_replicas ar ON d.group_id = ar.group_id AND d.replica_id = ar.replica_id
  1156. LEFT JOIN sys.dm_hadr_availability_replica_states ars ON d.group_id = ars.group_id AND d.replica_id = ars.replica_id
  1157. LEFT JOIN sys.dm_hadr_database_replica_cluster_states rcs ON rcs.database_name = sd.name AND rcs.replica_id = ar.replica_id
  1158. 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;
  1159. END;
  1160. /* Validate if database scope is set */
  1161. IF @dbScope IS NOT NULL AND ISNUMERIC(@dbScope) <> 1 AND @dbScope NOT LIKE '%,%'
  1162. BEGIN
  1163. 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;
  1164. RETURN
  1165. END;
  1166. RAISERROR (N' |-Applying specific database scope list, if any', 10, 1) WITH NOWAIT
  1167. IF @dbScope IS NOT NULL
  1168. BEGIN
  1169. SELECT @sqlcmd = 'DELETE FROM #tmpdbs0 WHERE [dbid] > 4 AND [dbid] NOT IN (' + REPLACE(@dbScope,' ','') + ')'
  1170. EXEC sp_executesql @sqlcmd;
  1171. END;
  1172. IF @sqlmajorver < 11
  1173. BEGIN
  1174. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1175. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1176. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1177. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1178. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1179. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1180. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
  1181. db.is_auto_update_stats_async_on, db.is_parameterization_forced,
  1182. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1183. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on, ''NA'' AS [is_indirect_checkpoint_on],
  1184. db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1185. FROM master.sys.databases AS db (NOLOCK)
  1186. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1187. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1188. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1189. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1190. 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 + '
  1191. ORDER BY [Database_Name]
  1192. OPTION (RECOMPILE)'
  1193. END
  1194. ELSE IF @sqlmajorver = 11
  1195. BEGIN
  1196. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1197. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1198. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1199. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1200. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1201. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1202. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
  1203. db.is_auto_update_stats_async_on, db.is_parameterization_forced,
  1204. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1205. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1206. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1207. db.target_recovery_time_in_seconds,
  1208. db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1209. FROM master.sys.databases AS db (NOLOCK)
  1210. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1211. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1212. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1213. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1214. 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 + '
  1215. ORDER BY [Database_Name]
  1216. OPTION (RECOMPILE)'
  1217. END
  1218. ELSE IF @sqlmajorver = 12
  1219. BEGIN
  1220. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1221. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1222. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1223. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1224. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1225. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1226. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_create_stats_incremental_on,
  1227. db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.delayed_durability_desc AS [delayed_durability_status],
  1228. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1229. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1230. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1231. db.target_recovery_time_in_seconds, db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1232. FROM master.sys.databases AS db (NOLOCK)
  1233. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1234. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1235. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1236. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1237. 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 + '
  1238. ORDER BY [Database_Name]
  1239. OPTION (RECOMPILE)'
  1240. END
  1241. ELSE IF @sqlmajorver >= 13
  1242. BEGIN
  1243. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1244. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1245. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1246. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1247. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1248. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1249. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_create_stats_incremental_on,
  1250. db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.delayed_durability_desc AS [delayed_durability_status],
  1251. db.is_query_store_on, db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1252. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1253. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1254. db.target_recovery_time_in_seconds, db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced,
  1255. db.is_memory_optimized_elevate_to_snapshot_on, db.is_remote_data_archive_enabled, db.is_mixed_page_allocation_on
  1256. FROM master.sys.databases AS db (NOLOCK)
  1257. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1258. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1259. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1260. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1261. 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 + '
  1262. ORDER BY [Database_Name]
  1263. OPTION (RECOMPILE)'
  1264. END
  1265. EXECUTE sp_executesql @sqlcmd;
  1266. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1267. BEGIN
  1268. SELECT TOP 1 @curdbname = [dbname], @curdbid = [dbid], @currole = [role], @state = [state], @cursecondary_role_allow_connections = secondary_role_allow_connections FROM #tmpdbs0 WHERE isdone = 0
  1269. IF (@currole = 2 AND @cursecondary_role_allow_connections = 0) OR @state <> 0
  1270. BEGIN
  1271. 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
  1272. FROM sys.master_files (NOLOCK) WHERE [database_id] = ' + CONVERT(VARCHAR(10), @curdbid)
  1273. END
  1274. ELSE
  1275. BEGIN
  1276. SET @sqlcmd = 'USE ' + QUOTENAME(@curdbname) + ';
  1277. 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
  1278. FROM sys.database_files (NOLOCK)'
  1279. END
  1280. BEGIN TRY
  1281. INSERT INTO #tmpdbfiledetail
  1282. EXECUTE sp_executesql @sqlcmd
  1283. END TRY
  1284. BEGIN CATCH
  1285. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1286. SELECT @ErrorMessage = 'Database Information subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1287. RAISERROR (@ErrorMessage, 16, 1);
  1288. END CATCH
  1289. UPDATE #tmpdbs0
  1290. SET isdone = 1
  1291. WHERE [dbid] = @curdbid
  1292. END;
  1293. 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,
  1294. 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,
  1295. 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,
  1296. is_media_read_only, is_read_only, is_sparse, is_name_reserved
  1297. FROM #tmpdbfiledetail
  1298. ORDER BY database_id, [file_id];
  1299. IF @sqlmajorver >= 12
  1300. BEGIN
  1301. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1302. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  1303. DROP TABLE #tblInMemDBs;
  1304. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  1305. CREATE TABLE #tblInMemDBs ([DBName] sysname, [Has_MemoryOptimizedObjects] bit, [MemoryAllocated_MemoryOptimizedObjects_KB] DECIMAL(18,2), [MemoryUsed_MemoryOptimizedObjects_KB] DECIMAL(18,2));
  1306. UPDATE #tmpdbs0
  1307. SET isdone = 0;
  1308. UPDATE #tmpdbs0
  1309. SET isdone = 1
  1310. WHERE [state] <> 0 OR [dbid] < 5;
  1311. UPDATE #tmpdbs0
  1312. SET isdone = 1
  1313. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1314. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1315. BEGIN
  1316. RAISERROR (N' |-Starting Storage analysis for In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  1317. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1318. BEGIN
  1319. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1320. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1321. SELECT ''' + @dbname + ''' AS [DBName], ISNULL((SELECT 1 FROM sys.filegroups FG WHERE FG.[type] = ''FX''), 0) AS [Has_MemoryOptimizedObjects],
  1322. 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],
  1323. 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];'
  1324. BEGIN TRY
  1325. INSERT INTO #tblInMemDBs
  1326. EXECUTE sp_executesql @sqlcmd
  1327. END TRY
  1328. BEGIN CATCH
  1329. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1330. SELECT @ErrorMessage = 'Storage analysis for In-Memory OLTP Engine subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1331. RAISERROR (@ErrorMessage, 16, 1);
  1332. END CATCH
  1333. UPDATE #tmpdbs0
  1334. SET isdone = 1
  1335. WHERE [dbid] = @dbid
  1336. END
  1337. END;
  1338. IF (SELECT COUNT([DBName]) FROM #tblInMemDBs WHERE [Has_MemoryOptimizedObjects] = 1) > 0
  1339. BEGIN
  1340. SELECT 'Information' AS [Category], 'InMem_Database_Storage' AS [Information], DBName AS [Database_Name],
  1341. [MemoryAllocated_MemoryOptimizedObjects_KB], [MemoryUsed_MemoryOptimizedObjects_KB]
  1342. FROM #tblInMemDBs WHERE Has_MemoryOptimizedObjects = 1
  1343. ORDER BY DBName;
  1344. END
  1345. ELSE
  1346. BEGIN
  1347. SELECT 'Information' AS [Category], 'InMem_Database_Storage' AS [Information], '[NA]' AS [Comment]
  1348. END
  1349. END;
  1350. -- http://support.microsoft.com/kb/2857849
  1351. IF @sqlmajorver > 10 AND @IsHadrEnabled = 1
  1352. BEGIN
  1353. SELECT 'Information' AS [Category], 'AlwaysOn_AG_Databases' AS [Information], dc.database_name AS [Database_Name],
  1354. d.synchronization_health_desc, d.synchronization_state_desc, d.database_state_desc
  1355. FROM sys.dm_hadr_database_replica_states d
  1356. INNER JOIN sys.availability_databases_cluster dc ON d.group_database_id=dc.group_database_id
  1357. WHERE d.is_local=1
  1358. END;
  1359. --------------------------------------------------------------------------------------------------------------------------------
  1360. -- Database file autogrows last 72h subsection
  1361. --------------------------------------------------------------------------------------------------------------------------------
  1362. RAISERROR (N' |-Starting database file autogrows last 72h', 10, 1) WITH NOWAIT
  1363. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE is_default = 1)
  1364. BEGIN
  1365. DECLARE @tracefilename VARCHAR(500)
  1366. SELECT @tracefilename = LEFT([path],LEN([path]) - PATINDEX('%\%', REVERSE([path]))) + '\log.trc' FROM sys.traces WHERE is_default = 1;
  1367. WITH AutoGrow_CTE (databaseid, [filename], Growth, Duration, StartTime, EndTime)
  1368. AS
  1369. (
  1370. SELECT databaseid, [filename], SUM(IntegerData*8) AS Growth, Duration, StartTime, EndTime--, CASE WHEN EventClass =
  1371. FROM ::fn_trace_gettable(@tracefilename, default)
  1372. WHERE EventClass >= 92 AND EventClass <= 95 AND DATEDIFF(hh,StartTime,GETDATE()) < 72 -- Last 24h
  1373. GROUP BY databaseid, [filename], IntegerData, Duration, StartTime, EndTime
  1374. )
  1375. SELECT 'Information' AS [Category], 'Recorded_Autogrows_Lst72H' AS [Information], DB_NAME(database_id) AS Database_Name,
  1376. mf.name AS logical_file_name, mf.size*8 / 1024 AS size_MB, mf.type_desc,
  1377. ag.Growth AS [growth_KB], CASE WHEN is_percent_growth = 1 THEN 'Pct' ELSE 'MB' END AS growth_type,
  1378. Duration/1000 AS Growth_Duration_ms, ag.StartTime, ag.EndTime
  1379. FROM sys.master_files mf
  1380. LEFT OUTER JOIN AutoGrow_CTE ag ON mf.database_id=ag.databaseid AND mf.name=ag.[filename]
  1381. WHERE ag.Growth > 0 --Only where growth occurred
  1382. GROUP BY database_id, mf.name, mf.size, ag.Growth, ag.Duration, ag.StartTime, ag.EndTime, is_percent_growth, mf.growth, mf.type_desc
  1383. ORDER BY Database_Name, logical_file_name, ag.StartTime;
  1384. END
  1385. ELSE
  1386. BEGIN
  1387. SELECT 'Information' AS [Category], 'Recorded_Autogrows_Lst72H' AS [Information], '[WARNING: Could not gather information on autogrow times]' AS [Comment]
  1388. END;
  1389. --------------------------------------------------------------------------------------------------------------------------------
  1390. -- Database triggers subsection
  1391. --------------------------------------------------------------------------------------------------------------------------------
  1392. IF @ptochecks = 1
  1393. BEGIN
  1394. RAISERROR (N' |-Starting database triggers', 10, 1) WITH NOWAIT
  1395. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1396. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  1397. DROP TABLE #tblTriggers;
  1398. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  1399. 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);
  1400. UPDATE #tmpdbs0
  1401. SET isdone = 0;
  1402. UPDATE #tmpdbs0
  1403. SET isdone = 1
  1404. WHERE [state] <> 0 OR [dbid] < 5;
  1405. UPDATE #tmpdbs0
  1406. SET isdone = 1
  1407. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1408. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1409. BEGIN
  1410. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1411. BEGIN
  1412. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1413. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1414. 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
  1415. FROM sys.triggers AS st
  1416. INNER JOIN sys.tables stb ON st.parent_id = stb.[object_id]
  1417. INNER JOIN sys.schemas ss ON stb.[schema_id] = ss.[schema_id]
  1418. WHERE st.is_ms_shipped = 0
  1419. ORDER BY stb.name, st.name;'
  1420. BEGIN TRY
  1421. INSERT INTO #tblTriggers
  1422. EXECUTE sp_executesql @sqlcmd
  1423. END TRY
  1424. BEGIN CATCH
  1425. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1426. SELECT @ErrorMessage = 'Database triggers subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1427. RAISERROR (@ErrorMessage, 16, 1);
  1428. END CATCH
  1429. UPDATE #tmpdbs0
  1430. SET isdone = 1
  1431. WHERE [dbid] = @dbid
  1432. END
  1433. END;
  1434. IF (SELECT COUNT([triggerName]) FROM #tblTriggers) > 0
  1435. BEGIN
  1436. SELECT 'Information' AS [Category], 'Database_Triggers' AS [Information], DBName AS [Database_Name],
  1437. triggerName AS [Trigger_Name], schemaName AS [Schema_Name], tableName AS [Table_Name],
  1438. type_desc AS [Trigger_Type], parent_class_desc AS [Trigger_Parent],
  1439. CASE is_instead_of_trigger WHEN 1 THEN 'INSTEAD_OF' ELSE 'AFTER' END AS [Trigger_Behavior],
  1440. create_date, modify_date,
  1441. CASE WHEN is_disabled = 1 THEN 'YES' ELSE 'NO' END AS [is_disabled],
  1442. CASE WHEN is_not_for_replication = 1 THEN 'YES' ELSE 'NO' END AS [is_not_for_replication]
  1443. FROM #tblTriggers
  1444. ORDER BY DBName, tableName, triggerName;
  1445. END
  1446. ELSE
  1447. BEGIN
  1448. SELECT 'Information' AS [Category], 'Database_Triggers' AS [Information], '[NA]' AS [Comment]
  1449. END
  1450. END;
  1451. --------------------------------------------------------------------------------------------------------------------------------
  1452. -- Enterprise features usage subsection
  1453. --------------------------------------------------------------------------------------------------------------------------------
  1454. IF @sqlmajorver > 9
  1455. BEGIN
  1456. RAISERROR (N'|-Starting Enterprise features usage', 10, 1) WITH NOWAIT
  1457. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1458. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  1459. DROP TABLE #tblPerSku;
  1460. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  1461. CREATE TABLE #tblPerSku ([DBName] sysname NULL, [Feature_Name] VARCHAR(100));
  1462. UPDATE #tmpdbs0
  1463. SET isdone = 0;
  1464. UPDATE #tmpdbs0
  1465. SET isdone = 1
  1466. WHERE [state] <> 0 OR [dbid] < 5;
  1467. UPDATE #tmpdbs0
  1468. SET isdone = 1
  1469. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1470. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1471. BEGIN
  1472. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1473. BEGIN
  1474. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1475. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1476. SELECT ''' + @dbname + ''' AS [DBName], feature_name FROM sys.dm_db_persisted_sku_features (NOLOCK);'
  1477. BEGIN TRY
  1478. INSERT INTO #tblPerSku
  1479. EXECUTE sp_executesql @sqlcmd
  1480. END TRY
  1481. BEGIN CATCH
  1482. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1483. SELECT @ErrorMessage = 'Enterprise features usage subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1484. RAISERROR (@ErrorMessage, 16, 1);
  1485. END CATCH
  1486. UPDATE #tmpdbs0
  1487. SET isdone = 1
  1488. WHERE [dbid] = @dbid
  1489. END
  1490. END;
  1491. IF @sqlmajorver > 10 AND ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13) AND @IsHadrEnabled = 1
  1492. BEGIN
  1493. INSERT INTO #tblPerSku
  1494. SELECT NULL, 'Always_On' AS feature_name
  1495. END;
  1496. 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
  1497. BEGIN
  1498. INSERT INTO #tblPerSku
  1499. 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
  1500. END;
  1501. IF (@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13
  1502. BEGIN
  1503. DELETE FROM #tblPerSku
  1504. WHERE feature_name IN ('ColumnStoreIndex','InMemoryOLTP')
  1505. END;
  1506. IF (SELECT COUNT([Feature_Name]) FROM #tblPerSku) > 0
  1507. BEGIN
  1508. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Check], '[INFORMATION: Some databases are using Enterprise only features]' AS [Comment]
  1509. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Information], DBName AS [Database_Name], [Feature_Name]
  1510. FROM #tblPerSku
  1511. ORDER BY 2, 3
  1512. END
  1513. ELSE
  1514. BEGIN
  1515. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Check], '[NA]' AS [Comment]
  1516. END
  1517. END;
  1518. --------------------------------------------------------------------------------------------------------------------------------
  1519. -- Backups since last Full Information subsection
  1520. --------------------------------------------------------------------------------------------------------------------------------
  1521. RAISERROR (N'|-Starting Backups', 10, 1) WITH NOWAIT
  1522. IF @sqlmajorver > 10
  1523. BEGIN
  1524. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Backups_since_last_Full'' AS [Information],
  1525. [database_name] AS [Database_Name], CASE WHEN type = ''D'' THEN ''Database''
  1526. WHEN type = ''I'' THEN ''Diff_Database''
  1527. WHEN type = ''L'' THEN ''Log''
  1528. WHEN type = ''F'' THEN ''File''
  1529. WHEN type = ''G'' THEN ''Diff_file''
  1530. WHEN type = ''P'' THEN ''Partial''
  1531. WHEN type = ''Q'' THEN ''Diff_partial''
  1532. ELSE NULL END AS [bck_type],
  1533. [backup_start_date], [backup_finish_date],
  1534. CONVERT(decimal(20,2),backup_size/1024.00/1024.00) AS [backup_size_MB],
  1535. CONVERT(decimal(20,2),compressed_backup_size/1024.00/1024.00) AS [compressed_backup_size_MB],
  1536. [recovery_model], [user_name],
  1537. database_backup_lsn AS [full_base_lsn], [differential_base_lsn], [expiration_date],
  1538. [is_password_protected], [has_backup_checksums], [is_readonly], is_copy_only, [has_incomplete_metadata] AS [Tail_log]
  1539. FROM msdb.dbo.backupset bck1 (NOLOCK)
  1540. WHERE is_copy_only = 0 -- No COPY_ONLY backups
  1541. 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)
  1542. ORDER BY database_name, backup_start_date DESC'
  1543. END
  1544. ELSE
  1545. BEGIN
  1546. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Backups_since_last_Full'' AS [Information],
  1547. [database_name] AS [Database_Name], CASE WHEN type = ''D'' THEN ''Database''
  1548. WHEN type = ''I'' THEN ''Diff_Database''
  1549. WHEN type = ''L'' THEN ''Log''
  1550. WHEN type = ''F'' THEN ''File''
  1551. WHEN type = ''G'' THEN ''Diff_file''
  1552. WHEN type = ''P'' THEN ''Partial''
  1553. WHEN type = ''Q'' THEN ''Diff_partial''
  1554. ELSE NULL END AS [bck_type],
  1555. [backup_start_date], [backup_finish_date],
  1556. CONVERT(decimal(20,2),backup_size/1024.00/1024.00) AS [backup_size_MB],
  1557. ''[NA]'' AS [compressed_backup_size_MB],
  1558. [recovery_model], [user_name],
  1559. database_backup_lsn AS [full_base_lsn], [differential_base_lsn], [expiration_date],
  1560. [is_password_protected], [has_backup_checksums], [is_readonly], is_copy_only, [has_incomplete_metadata] AS [Tail_log]
  1561. FROM msdb.dbo.backupset bck1 (NOLOCK)
  1562. WHERE is_copy_only = 0 -- No COPY_ONLY backups
  1563. 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)
  1564. ORDER BY database_name, backup_start_date DESC'
  1565. END;
  1566. EXECUTE sp_executesql @sqlcmd;
  1567. --------------------------------------------------------------------------------------------------------------------------------
  1568. -- System Configuration subsection
  1569. --------------------------------------------------------------------------------------------------------------------------------
  1570. RAISERROR (N'|-Starting System Configuration', 10, 1) WITH NOWAIT
  1571. SELECT 'Information' AS [Category], 'All_System_Configurations' AS [Information],
  1572. name AS [Name],
  1573. configuration_id AS [Number],
  1574. minimum AS [Minimum],
  1575. maximum AS [Maximum],
  1576. is_dynamic AS [Dynamic],
  1577. is_advanced AS [Advanced],
  1578. value AS [ConfigValue],
  1579. value_in_use AS [RunValue],
  1580. description AS [Description]
  1581. FROM sys.configurations (NOLOCK)
  1582. ORDER BY name OPTION (RECOMPILE);
  1583. --------------------------------------------------------------------------------------------------------------------------------
  1584. -- Pre-checks section
  1585. --------------------------------------------------------------------------------------------------------------------------------
  1586. RAISERROR (N'Starting Pre-Checks - Building DB list excluding MS shipped', 10, 1) WITH NOWAIT
  1587. DECLARE @MSdb int
  1588. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  1589. DROP TABLE #tmpdbs1;
  1590. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  1591. CREATE TABLE #tmpdbs1 (id int IDENTITY(1,1), [dbid] int, [dbname] VARCHAR(1000), [role] tinyint, [secondary_role_allow_connections] tinyint, isdone bit)
  1592. RAISERROR (N'|-Excluding MS shipped by standard names and databases belonging to non-readable AG secondary replicas (if available)', 10, 1) WITH NOWAIT
  1593. -- Ignore MS shipped databases and databases belonging to non-readable AG secondary replicas
  1594. INSERT INTO #tmpdbs1 ([dbid], [dbname], [role], [secondary_role_allow_connections], [isdone])
  1595. SELECT [dbid], [dbname], [role], [secondary_role_allow_connections], 0
  1596. FROM #tmpdbs0 (NOLOCK)
  1597. WHERE is_read_only = 0 AND [state] = 0 AND [dbid] > 4 AND is_distributor = 0
  1598. AND [role] <> 2 AND (secondary_role_allow_connections <> 0 OR secondary_role_allow_connections IS NULL)
  1599. AND lower([dbname]) NOT IN ('virtualmanagerdb', --Virtual Machine Manager
  1600. 'scspfdb', --Service Provider Foundation
  1601. 'semanticsdb', --Semantic Search
  1602. 'servicemanager','service manager','dwstagingandconfig','dwrepository','dwdatamart','dwasdatabase','omdwdatamart','cmdwdatamart', --SCSM
  1603. 'ssodb','bamanalysis','bamarchive','bamalertsapplication','bamalertsnsmain','bamprimaryimport','bamstarschema','biztalkmgmtdb','biztalkmsgboxdb','biztalkdtadb','biztalkruleenginedb','bamprimaryimport','biztalkedidb','biztalkhwsdb','tpm','biztalkanalysisdb','bamprimaryimportsuccessfully', --BizTalk
  1604. 'aspstate','aspnet', --ASP.NET
  1605. 'mscrm_config', --Dynamics CRM
  1606. 'cpsdyn','lcslog','lcscdr','lis','lyss','mgc','qoemetrics','rgsconfig','rgsdyn','rtc','rtcab','rtcab1','rtcdyn','rtcshared','rtcxds','xds', --Lync
  1607. 'activitylog','branchdb','clienttracelog','eventlog','listingssettings','servicegroupdb','tservercontroller','vodbackend', --MediaRoom
  1608. 'operationsmanager','operationsmanagerdw','operationsmanagerac', --SCOM
  1609. 'orchestrator', --Orchestrator
  1610. 'sso','wss_search','wss_search_config','sharedservices_db','sharedservices_search_db','wss_content','profiledb', 'social db','sync db', --Sharepoint
  1611. 'susdb', --WSUS
  1612. 'projectserver_archive','projectserver_draft','projectserver_published','projectserver_reporting', --Project Server
  1613. 'reportserver','reportservertempdb','rsdb','rstempdb', --SSRS
  1614. 'fastsearchadmindatabase', --Fast Search
  1615. 'ppsmonitoring','ppsplanningservice','ppsplanningsystem', --PerformancePoint Services
  1616. 'dynamics', --Dynamics GP
  1617. 'microsoftdynamicsax','microsoftdynamicsaxbaseline', --Dynamics AX
  1618. 'fimservice','fimsynchronizationservice', --Forefront Identity Manager
  1619. 'sbgatewaydatabase','sbmanagementdb', --Service Bus
  1620. 'wfinstancemanagementdb','wfmanagementdb','wfresourcemanagementdb' --Workflow Manager
  1621. )
  1622. AND [dbname] NOT LIKE 'repANDtingservice[_]%' --SSRS
  1623. AND [dbname] NOT LIKE 'tfs[_]%' --TFS
  1624. AND [dbname] NOT LIKE 'defaultpowerpivotserviceapplicationdb%' --PowerPivot
  1625. AND [dbname] NOT LIKE 'perfANDmancepoint service[_]%' --PerfANDmancePoint Services
  1626. AND [dbname] NOT LIKE '%database nav%' --Dynamics NAV
  1627. AND [dbname] NOT LIKE '%[_]mscrm' --Dynamics CRM
  1628. AND [dbname] NOT LIKE 'dpmdb[_]%' --DPM
  1629. AND [dbname] NOT LIKE 'sbmessagecontainer%' --Service Bus
  1630. AND [dbname] NOT LIKE 'sma%' --SCSMA
  1631. AND [dbname] NOT LIKE 'releasemanagement%' --TFS Release Management
  1632. AND [dbname] NOT LIKE 'projectwebapp%' --Project Server
  1633. AND [dbname] NOT LIKE 'sms[_]%' AND [dbname] NOT LIKE 'cm[_]%' --SCCM
  1634. AND [dbname] NOT LIKE 'fepdw%' AND [dbname] NOT LIKE 'FEPDB[_]%' --Forefront Endpoint Protection
  1635. --Sharepoint
  1636. AND [dbname] NOT LIKE 'sharepoint[_]admincontent%' AND [dbname] NOT LIKE 'sharepoint[_]config%' AND [dbname] NOT LIKE 'wss[_]content%' AND [dbname] NOT LIKE 'wss[_]search%'
  1637. 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%'
  1638. AND [dbname] NOT LIKE 'sharedservicescontent%' AND [dbname] NOT LIKE 'application[_]registry[_]service[_]db%' AND [dbname] NOT LIKE 'search[_]service[_]application[_]propertystANDedb[_]%'
  1639. AND [dbname] NOT LIKE 'subscriptionsettings[_]%' AND [dbname] NOT LIKE 'webanalyticsserviceapplication[_]stagingdb[_]%' AND [dbname] NOT LIKE 'webanalyticsserviceapplication[_]repANDtingdb[_]%'
  1640. AND [dbname] NOT LIKE 'bdc[_]service[_]db[_]%' AND [dbname] NOT LIKE 'managed metadata service[_]%' AND [dbname] NOT LIKE 'perfANDmancepoint service application[_]%'
  1641. 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%'
  1642. 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[_]%'
  1643. AND [dbname] NOT LIKE 'wANDdautomationservices[_]%' AND [dbname] NOT LIKE 'wss[_]logging%' AND [dbname] NOT LIKE 'wss[_]usageapplication%' AND [dbname] NOT LIKE 'appmng[_]service[_]db%'
  1644. AND [dbname] NOT LIKE 'search[_]service[_]application[_]analyticsrepANDtingstANDedb[_]%' AND [dbname] NOT LIKE 'search[_]service[_]application[_]linksstANDedb[_]%' AND [dbname] NOT LIKE 'sharepoint[_]logging[_]%'
  1645. 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%'
  1646. IF EXISTS (SELECT name FROM msdb.sys.objects (NOLOCK) WHERE name='MSdistributiondbs' AND is_ms_shipped = 1)
  1647. BEGIN
  1648. DELETE FROM #tmpdbs1 WHERE [dbid] IN (SELECT DB_ID(name) FROM msdb.dbo.MSdistributiondbs)
  1649. END;
  1650. RAISERROR (N'|-Excluding MS shipped by notable object names', 10, 1) WITH NOWAIT
  1651. -- Removing other noticeable MS shipped DBs
  1652. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  1653. BEGIN
  1654. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  1655. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1656. 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)
  1657. OR (OBJECT_ID(''dbo.Versions'',''U'') IS NOT NULL
  1658. 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)
  1659. 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)
  1660. 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)
  1661. 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)
  1662. 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)
  1663. 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)
  1664. 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)
  1665. 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)
  1666. 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)
  1667. 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)
  1668. 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)
  1669. 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)
  1670. )
  1671. 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)
  1672. 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)
  1673. 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)
  1674. 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)
  1675. -- End Sharepoint
  1676. 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)
  1677. 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)
  1678. -- End ASP.NET
  1679. 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)
  1680. -- End PowerPivot
  1681. 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)
  1682. -- End Orchestrator
  1683. 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)
  1684. -- End VMM
  1685. 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)
  1686. -- End Service Provider Foundation
  1687. 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)
  1688. 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))
  1689. -- End BizTalk
  1690. 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)
  1691. -- End Dynamics AX
  1692. OR (OBJECT_ID(''dbo.Notification'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SystemUserRoles'',''U'') IS NOT NULL
  1693. AND (OBJECT_ID(''dbo.p_GetCrmUserId'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.p_GetPrivilegesInRole'',''P'') IS NOT NULL)
  1694. OR (OBJECT_ID(''dbo.p_AccountOVRollup'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.p_GetDbSize'',''P'') IS NOT NULL))
  1695. -- End Dynamics CRM
  1696. 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'')))
  1697. -- End Dynamics NAV
  1698. 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)
  1699. -- End Dynamics GP
  1700. 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)
  1701. -- End SCCM
  1702. 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)
  1703. -- End Forefront Endpoint Protection
  1704. 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)
  1705. -- End Fast Search
  1706. OR (OBJECT_ID(''fim.Objects'',''U'') IS NOT NULL AND SCHEMA_ID(''debug'') IS NOT NULL)
  1707. 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)
  1708. -- End Forefront Identity Manager
  1709. 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)
  1710. 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)
  1711. -- End PerformancePoint Services
  1712. 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))
  1713. -- End Project Server
  1714. OR (OBJECT_ID(''apm.MESSAGES'',''U'') IS NOT NULL AND SCHEMA_ID(''CS'') IS NOT NULL OR SCHEMA_ID(''CM'') IS NOT NULL)
  1715. 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)
  1716. 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)
  1717. 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)
  1718. -- End SCOM
  1719. OR (OBJECT_ID(''dbo.version'',''U'') IS NOT NULL AND EXISTS(SELECT 1 FROM sys.internal_tables (NOLOCK) WHERE name LIKE ''language[_]model[_]%''))
  1720. -- End Semantic Search
  1721. 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)
  1722. -- End WSUS
  1723. 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)
  1724. -- End DPM
  1725. OR ((OBJECT_ID(''dbo.DomainTable'',''U'') IS NOT NULL AND OBJECT_ID(''etl.Source'',''U'') IS NOT NULL)
  1726. 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)
  1727. 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))
  1728. -- End SCSM
  1729. 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)
  1730. -- End SSRS
  1731. OR (OBJECT_ID(''dbo.prc_ChangeHostId'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.prc_EnablePrefixCompression'',''P'') IS NOT NULL
  1732. 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)
  1733. 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))
  1734. 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)
  1735. -- End TFS
  1736. 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)
  1737. -- End TFS Release Management
  1738. 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)
  1739. 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)
  1740. 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)
  1741. -- End Service Bus
  1742. 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)
  1743. 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)
  1744. 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)
  1745. -- End Workflow Manager
  1746. 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)
  1747. -- End SCSMA
  1748. BEGIN
  1749. SELECT @MSdbOUT = ' + CONVERT(VARCHAR(10), @dbid) + '
  1750. END'
  1751. SET @params = N'@MSdbOUT int OUTPUT';
  1752. EXECUTE sp_executesql @sqlcmd, @params, @MSdbOUT=@MSdb OUTPUT
  1753. IF @MSdb = @dbid
  1754. BEGIN
  1755. DELETE FROM #tmpdbs1
  1756. WHERE [dbid] = @dbid;
  1757. END
  1758. ELSE
  1759. BEGIN
  1760. UPDATE #tmpdbs1
  1761. SET isdone = 1
  1762. WHERE [dbid] = @dbid
  1763. END
  1764. END;
  1765. UPDATE #tmpdbs1
  1766. SET isdone = 0;
  1767. RAISERROR (N'|-Applying 2nd layer of specific database scope, if any', 10, 1) WITH NOWAIT
  1768. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  1769. DROP TABLE #tmpdbs_userchoice;
  1770. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  1771. CREATE TABLE #tmpdbs_userchoice ([dbid] int PRIMARY KEY, [dbname] VARCHAR(1000))
  1772. IF @dbScope IS NOT NULL
  1773. BEGIN
  1774. SELECT @sqlcmd = 'SELECT [dbid], [dbname]
  1775. FROM #tmpdbs0 (NOLOCK)
  1776. WHERE is_read_only = 0 AND [state] = 0 AND [dbid] > 4 AND is_distributor = 0
  1777. AND [role] <> 2 AND (secondary_role_allow_connections <> 0 OR secondary_role_allow_connections IS NULL)
  1778. AND [dbid] IN (' + REPLACE(@dbScope,' ','') + ')'
  1779. INSERT INTO #tmpdbs_userchoice ([dbid], [dbname])
  1780. EXEC sp_executesql @sqlcmd;
  1781. SELECT @sqlcmd = 'DELETE FROM #tmpdbs1 WHERE [dbid] NOT IN (' + REPLACE(@dbScope,' ','') + ')'
  1782. EXEC sp_executesql @sqlcmd;
  1783. END;
  1784. --------------------------------------------------------------------------------------------------------------------------------
  1785. -- Checks section
  1786. --------------------------------------------------------------------------------------------------------------------------------
  1787. RAISERROR (N'Starting Checks section', 10, 1) WITH NOWAIT
  1788. RAISERROR (N'|-Starting Processor Checks', 10, 1) WITH NOWAIT
  1789. --------------------------------------------------------------------------------------------------------------------------------
  1790. -- Number of available Processors for this instance vs. MaxDOP setting subsection
  1791. --------------------------------------------------------------------------------------------------------------------------------
  1792. RAISERROR (N' |-Starting Number of available Processors for this instance vs. MaxDOP setting', 10, 1) WITH NOWAIT
  1793. DECLARE /*@cpucount int, @numa int, */@affined_cpus int
  1794. /*
  1795. DECLARE @i int, @cpuaffin_fixed VARCHAR(300)
  1796. SET @cpuaffin_fixed = @cpuaffin
  1797. SET @i = @cpucount/@numa + 1
  1798. WHILE @i <= @cpucount
  1799. BEGIN
  1800. SELECT @cpuaffin_fixed = STUFF(@cpuaffin_fixed, @i, 1, '_' + SUBSTRING(@cpuaffin, @i, 1))
  1801. SET @i = @i + @cpucount/@numa + 1
  1802. END
  1803. */
  1804. SELECT @affined_cpus = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE is_online = 1 AND scheduler_id < 255 AND parent_node_id < 64;
  1805. --SELECT @cpucount = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64
  1806. SELECT 'Processor_checks' AS [Category], 'Parallelism_MaxDOP' AS [Check],
  1807. CASE WHEN [value] > @affined_cpus THEN '[WARNING: MaxDOP setting exceeds available processor count (affinity)]'
  1808. 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)]'
  1809. 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]'
  1810. 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]'
  1811. ELSE '[OK]'
  1812. END AS [Deviation]
  1813. FROM sys.configurations (NOLOCK) WHERE name = 'max degree of parallelism';
  1814. SELECT 'Processor_checks' AS [Category], 'Parallelism_MaxDOP' AS [Information],
  1815. CASE WHEN [value] > @affined_cpus THEN @affined_cpus
  1816. WHEN @numa = 1 AND @affined_cpus > 8 AND ([value] = 0 OR [value] > 8) THEN 8
  1817. WHEN @numa > 1 AND (@cpucount/@numa) < 8 AND ([value] = 0 OR [value] > (@cpucount/@numa)) THEN @cpucount/@numa
  1818. WHEN @numa > 1 AND (@cpucount/@numa) >= 8 AND ([value] = 0 OR [value] > 8 OR [value] > (@cpucount/@numa)) THEN 8
  1819. ELSE 0
  1820. END AS [Recommended_MaxDOP],
  1821. [value] AS [Current_MaxDOP], @cpucount AS [Available_Processors], @affined_cpus AS [Affined_Processors],
  1822. -- Processor Affinity is shown highest to lowest CPU ID
  1823. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1824. FROM sys.configurations (NOLOCK) WHERE name = 'max degree of parallelism';
  1825. --------------------------------------------------------------------------------------------------------------------------------
  1826. -- Processor Affinity in NUMA architecture subsection
  1827. --------------------------------------------------------------------------------------------------------------------------------
  1828. RAISERROR (N' |-Starting Processor Affinity in NUMA architecture', 10, 1) WITH NOWAIT
  1829. IF @numa > 1
  1830. BEGIN
  1831. 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),
  1832. 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)
  1833. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Check],
  1834. CASE WHEN (SELECT COUNT(*) FROM ncpuCTE) > 0 THEN '[WARNING: Current NUMA configuration is not recommended. At least one node has a single assigned CPU]'
  1835. 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]'
  1836. ELSE '[OK]' END AS [Deviation]
  1837. FROM sys.dm_os_sys_info (NOLOCK)
  1838. OPTION (RECOMPILE);
  1839. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Information], cpu_count AS [Logical_CPU_Count],
  1840. (SELECT COUNT(DISTINCT parent_node_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64) AS [NUMA_Nodes],
  1841. -- Processor Affinity is shown highest to lowest CPU ID
  1842. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1843. FROM sys.dm_os_sys_info (NOLOCK)
  1844. OPTION (RECOMPILE);
  1845. END
  1846. ELSE
  1847. BEGIN
  1848. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Check], '[Not_NUMA]' AS [Deviation]
  1849. FROM sys.dm_os_sys_info (NOLOCK)
  1850. OPTION (RECOMPILE);
  1851. END;
  1852. --------------------------------------------------------------------------------------------------------------------------------
  1853. -- Additional Processor information subsection
  1854. --------------------------------------------------------------------------------------------------------------------------------
  1855. RAISERROR (N' |-Starting Additional Processor information', 10, 1) WITH NOWAIT
  1856. -- Processor Info
  1857. SELECT 'Processor_checks' AS [Category], 'Processor_Summary' AS [Information], cpu_count AS [Logical_CPU_Count], hyperthread_ratio AS [Cores2Socket_Ratio],
  1858. cpu_count/hyperthread_ratio AS [CPU_Sockets],
  1859. 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],
  1860. @affined_cpus AS [Affined_Processors],
  1861. -- Processor Affinity is shown highest to lowest Processor ID
  1862. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1863. FROM sys.dm_os_sys_info (NOLOCK)
  1864. OPTION (RECOMPILE);
  1865. IF @ptochecks = 1
  1866. BEGIN
  1867. RAISERROR (N' |-Starting Processor utilization rate in the last 2 hours', 10, 1) WITH NOWAIT
  1868. -- Processor utilization rate in the last 2 hours
  1869. DECLARE @ts_now bigint
  1870. DECLARE @tblAggCPU TABLE (SQLProc tinyint, SysIdle tinyint, OtherProc tinyint, Minutes tinyint)
  1871. SELECT @ts_now = ms_ticks FROM sys.dm_os_sys_info (NOLOCK);
  1872. WITH cteCPU (record_id, SystemIdle, SQLProcessUtilization, [timestamp]) AS (SELECT
  1873. record.value('(./Record/@id)[1]', 'int') AS record_id,
  1874. record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS SystemIdle,
  1875. record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS SQLProcessUtilization,
  1876. [TIMESTAMP] FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  1877. FROM sys.dm_os_ring_buffers (NOLOCK)
  1878. WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
  1879. AND record LIKE '%<SystemHealth>%') AS x
  1880. )
  1881. INSERT INTO @tblAggCPU
  1882. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 10
  1883. FROM cteCPU
  1884. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -10, GETDATE())
  1885. UNION ALL
  1886. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 20
  1887. FROM cteCPU
  1888. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -10, GETDATE()) AND
  1889. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -20, GETDATE())
  1890. UNION ALL
  1891. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 30
  1892. FROM cteCPU
  1893. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -20, GETDATE()) AND
  1894. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -30, GETDATE())
  1895. UNION ALL
  1896. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 40
  1897. FROM cteCPU
  1898. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -30, GETDATE()) AND
  1899. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -40, GETDATE())
  1900. UNION ALL
  1901. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 50
  1902. FROM cteCPU
  1903. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -40, GETDATE()) AND
  1904. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -50, GETDATE())
  1905. UNION ALL
  1906. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 60
  1907. FROM cteCPU
  1908. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -50, GETDATE()) AND
  1909. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -60, GETDATE())
  1910. UNION ALL
  1911. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 70
  1912. FROM cteCPU
  1913. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -60, GETDATE()) AND
  1914. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -70, GETDATE())
  1915. UNION ALL
  1916. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 80
  1917. FROM cteCPU
  1918. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -70, GETDATE()) AND
  1919. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -80, GETDATE())
  1920. UNION ALL
  1921. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 90
  1922. FROM cteCPU
  1923. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -80, GETDATE()) AND
  1924. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -90, GETDATE())
  1925. UNION ALL
  1926. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 100
  1927. FROM cteCPU
  1928. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -90, GETDATE()) AND
  1929. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -100, GETDATE())
  1930. UNION ALL
  1931. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 110
  1932. FROM cteCPU
  1933. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -100, GETDATE()) AND
  1934. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -110, GETDATE())
  1935. UNION ALL
  1936. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 120
  1937. FROM cteCPU
  1938. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -110, GETDATE()) AND
  1939. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -120, GETDATE())
  1940. IF (SELECT COUNT(SysIdle) FROM @tblAggCPU WHERE SysIdle < 30) > 0
  1941. BEGIN
  1942. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[WARNING: Detected CPU usage over 70 pct]' AS [Deviation];
  1943. END
  1944. ELSE IF (SELECT COUNT(SysIdle) FROM @tblAggCPU WHERE SysIdle < 10) > 0
  1945. BEGIN
  1946. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[WARNING: Detected CPU usage over 90 pct]' AS [Deviation];
  1947. END
  1948. ELSE
  1949. BEGIN
  1950. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[OK]' AS [Deviation];
  1951. END;
  1952. 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]
  1953. FROM @tblAggCPU;
  1954. END;
  1955. RAISERROR (N'|-Starting Memory Checks', 10, 1) WITH NOWAIT
  1956. --------------------------------------------------------------------------------------------------------------------------------
  1957. -- Server Memory subsection
  1958. --------------------------------------------------------------------------------------------------------------------------------
  1959. RAISERROR (N' |-Starting Server Memory', 10, 1) WITH NOWAIT
  1960. DECLARE @maxservermem bigint, @minservermem bigint, @systemmem bigint, @systemfreemem bigint, @numa_nodes_afinned tinyint, @LowMemoryThreshold int
  1961. DECLARE @commit_target bigint -- Includes stolen and reserved memory in the memory manager
  1962. DECLARE @committed bigint -- Does not include reserved memory in the memory manager
  1963. DECLARE @mwthreads_count int, @xtp int
  1964. IF @sqlmajorver = 9
  1965. BEGIN
  1966. SET @sqlcmd = N'SELECT @systemmemOUT = t1.record.value(''(./Record/MemoryRecord/TotalPhysicalMemory)[1]'', ''bigint'')/1024,
  1967. @systemfreememOUT = t1.record.value(''(./Record/MemoryRecord/AvailablePhysicalMemory)[1]'', ''bigint'')/1024
  1968. FROM (SELECT MAX([TIMESTAMP]) AS [TIMESTAMP], CONVERT(xml, record) AS record
  1969. FROM sys.dm_os_ring_buffers (NOLOCK)
  1970. WHERE ring_buffer_type = N''RING_BUFFER_RESOURCE_MONITOR''
  1971. AND record LIKE ''%RESOURCE_MEMPHYSICAL%''
  1972. GROUP BY record) AS t1';
  1973. END
  1974. ELSE
  1975. BEGIN
  1976. SET @sqlcmd = N'SELECT @systemmemOUT = total_physical_memory_kb/1024, @systemfreememOUT = available_physical_memory_kb/1024 FROM sys.dm_os_sys_memory';
  1977. END
  1978. SET @params = N'@systemmemOUT bigint OUTPUT, @systemfreememOUT bigint OUTPUT';
  1979. EXECUTE sp_executesql @sqlcmd, @params, @systemmemOUT=@systemmem OUTPUT, @systemfreememOUT=@systemfreemem OUTPUT;
  1980. IF @sqlmajorver >= 9 AND @sqlmajorver < 11
  1981. BEGIN
  1982. SET @sqlcmd = N'SELECT @commit_targetOUT=bpool_commit_target*8, @committedOUT=bpool_committed*8 FROM sys.dm_os_sys_info (NOLOCK)'
  1983. END
  1984. ELSE IF @sqlmajorver >= 11
  1985. BEGIN
  1986. SET @sqlcmd = N'SELECT @commit_targetOUT=committed_target_kb, @committedOUT=committed_kb FROM sys.dm_os_sys_info (NOLOCK)'
  1987. END
  1988. SET @params = N'@commit_targetOUT bigint OUTPUT, @committedOUT bigint OUTPUT';
  1989. EXECUTE sp_executesql @sqlcmd, @params, @commit_targetOUT=@commit_target OUTPUT, @committedOUT=@committed OUTPUT;
  1990. SELECT @minservermem = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE [Name] = 'min server memory (MB)';
  1991. SELECT @maxservermem = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE [Name] = 'max server memory (MB)';
  1992. SELECT @mwthreads_count = max_workers_count FROM sys.dm_os_sys_info;
  1993. 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
  1994. /*
  1995. From Windows Internals book by David Solomon and Mark Russinovich:
  1996. "The default level of available memory that signals a low-memory-resource notification event is approximately 32 MB per 4 GB,
  1997. 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."
  1998. */
  1999. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  2000. BEGIN
  2001. BEGIN TRY
  2002. SELECT @RegKey = N'System\CurrentControlSet\Control\SessionManager\MemoryManagement'
  2003. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'LowMemoryThreshold', @LowMemoryThreshold OUTPUT, NO_OUTPUT
  2004. IF @LowMemoryThreshold IS NULL
  2005. SELECT @LowMemoryThreshold = CASE WHEN @systemmem <= 4096 THEN 32 ELSE 64 END
  2006. END TRY
  2007. BEGIN CATCH
  2008. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2009. SELECT @ErrorMessage = 'Server Memory subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  2010. RAISERROR (@ErrorMessage, 16, 1);
  2011. END CATCH
  2012. END
  2013. ELSE
  2014. BEGIN
  2015. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing LowMemoryThreshold check]', 16, 1, N'sysadmin')
  2016. --RETURN
  2017. END;
  2018. SELECT 'Memory_checks' AS [Category], 'Memory_issues_MaxServerMem' AS [Check],
  2019. CASE WHEN @maxservermem = 2147483647 THEN '[WARNING: MaxMem setting is default. Please revise memory settings]'
  2020. WHEN @maxservermem > @systemmem THEN '[WARNING: MaxMem setting exceeds available system memory]'
  2021. WHEN @numa > 1 AND (@maxservermem/@numa) * @numa_nodes_afinned > (@systemmem/@numa) * @numa_nodes_afinned THEN '[WARNING: Current MaxMem setting will leverage node foreign memory.
  2022. Maximum value for MaxMem setting on this configuration is ' + CONVERT(NVARCHAR,(@systemmem/@numa) * @numa_nodes_afinned) + ' for a single instance]'
  2023. ELSE '[OK]'
  2024. END AS [Deviation], @maxservermem AS [sql_max_mem_MB];
  2025. SELECT 'Memory_checks' AS [Category], 'Memory_issues_MinServerMem' AS [Check],
  2026. 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]'
  2027. 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]'
  2028. 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]'
  2029. WHEN @numa > 1 AND (@minservermem/@numa) * @numa_nodes_afinned > (@systemmem/@numa) * @numa_nodes_afinned THEN '[WARNING: Current MinMem setting will leverage node foreign memory]'
  2030. ELSE '[OK]'
  2031. END AS [Deviation], @minservermem AS [sql_min_mem_MB];
  2032. SELECT 'Memory_checks' AS [Category], 'Memory_issues_FreeMem' AS [Check],
  2033. CASE WHEN (@systemfreemem*100)/@systemmem <= 5 THEN '[WARNING: Less than 5 percent of Free Memory available. Please revise memory settings]'
  2034. /* 64 is the default LowMemThreshold for windows on a system with 8GB of mem or more*/
  2035. WHEN @systemfreemem <= 64*3 THEN '[WARNING: System Free Memory is dangerously low. Please revise memory settings]'
  2036. ELSE '[OK]'
  2037. END AS [Deviation], @systemmem AS system_total_physical_memory_MB, @systemfreemem AS system_available_physical_memory_MB;
  2038. SELECT 'Memory_checks' AS [Category], 'Memory_issues_CommitedMem' AS [Check],
  2039. CASE WHEN @commit_target > @committed AND @sqlmajorver >= 11 THEN '[INFORMATION: Memory manager will try to obtain additional memory]'
  2040. WHEN @commit_target < @committed AND @sqlmajorver >= 11 THEN '[INFORMATION: Memory manager will try to shrink the amount of memory committed]'
  2041. WHEN @commit_target > @committed AND @sqlmajorver < 11 THEN '[INFORMATION: Buffer Pool will try to obtain additional memory]'
  2042. WHEN @commit_target < @committed AND @sqlmajorver < 11 THEN '[INFORMATION: Buffer Pool will try to shrink]'
  2043. ELSE '[OK]'
  2044. END AS [Deviation], @commit_target/1024 AS sql_commit_target_MB, @committed/1024 AS sql_commited_MB;
  2045. SELECT 'Memory_checks' AS [Category], 'Memory_reference' AS [Check],
  2046. CASE WHEN @arch IS NULL THEN '[WARNING: Could not determine architecture needed for check]'
  2047. 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
  2048. (@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
  2049. (@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
  2050. (@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
  2051. (@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
  2052. (@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
  2053. (@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]'
  2054. ELSE '[OK]'
  2055. END AS [Deviation],
  2056. 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))
  2057. 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))
  2058. 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))
  2059. 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))
  2060. 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))
  2061. 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))
  2062. 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))
  2063. END AS [Recommended_MaxMem_MB_SingleInstance],
  2064. CASE WHEN @systemmem <= 2048 THEN 512
  2065. WHEN @systemmem BETWEEN 2049 AND 4096 THEN 819
  2066. WHEN @systemmem BETWEEN 4097 AND 8192 THEN 1228
  2067. WHEN @systemmem BETWEEN 8193 AND 12288 THEN 2048
  2068. WHEN @systemmem BETWEEN 12289 AND 24576 THEN 2560
  2069. WHEN @systemmem BETWEEN 24577 AND 32768 THEN 3072
  2070. WHEN @systemmem > 32768 THEN 4096
  2071. END AS [Mem_MB_for_OS],
  2072. 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)
  2073. 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)
  2074. 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)
  2075. 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)
  2076. 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)
  2077. 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)
  2078. WHEN @systemmem > 32768 THEN @mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END)
  2079. END AS [Potential_threads_mem_MB],
  2080. @mwthreads_count AS [Configured_workers];
  2081. IF @sqlmajorver = 9
  2082. BEGIN
  2083. SELECT 'Memory_checks' AS [Category], 'Memory_Summary' AS [Information],
  2084. @maxservermem AS sql_max_mem_MB, @minservermem AS sql_min_mem_MB,
  2085. @commit_target/1024 AS sql_commit_target_MB, --BPool in SQL 2005 to 2008R2
  2086. @committed/1024 AS sql_commited_MB, --BPool in SQL 2005 to 2008R2
  2087. @systemmem AS system_total_physical_memory_MB,
  2088. @systemfreemem AS system_available_physical_memory_MB
  2089. END
  2090. ELSE
  2091. BEGIN
  2092. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Memory_Summary'' AS [Information],
  2093. @maxservermemIN AS sql_max_mem_MB, @minservermemIN AS sql_min_mem_MB,
  2094. @commit_targetIN/1024 AS sql_commit_target_MB, --BPool in SQL 2005 to 2008R2
  2095. @committedIN/1024 AS sql_commited_MB, --BPool in SQL 2005 to 2008R2
  2096. physical_memory_in_use_kb/1024 AS sql_physical_memory_in_use_MB,
  2097. large_page_allocations_kb/1024 AS sql_large_page_allocations_MB,
  2098. locked_page_allocations_kb/1024 AS sql_locked_page_allocations_MB,
  2099. @systemmemIN AS system_total_physical_memory_MB,
  2100. @systemfreememIN AS system_available_physical_memory_MB,
  2101. total_virtual_address_space_kb/1024 AS sql_total_VAS_MB,
  2102. virtual_address_space_reserved_kb/1024 AS sql_VAS_reserved_MB,
  2103. virtual_address_space_committed_kb/1024 AS sql_VAS_committed_MB,
  2104. virtual_address_space_available_kb/1024 AS sql_VAS_available_MB,
  2105. page_fault_count AS sql_page_fault_count,
  2106. memory_utilization_percentage AS sql_memory_utilization_percentage,
  2107. process_physical_memory_low AS sql_process_physical_memory_low,
  2108. process_virtual_memory_low AS sql_process_virtual_memory_low
  2109. FROM sys.dm_os_process_memory (NOLOCK)'
  2110. SET @params = N'@maxservermemIN bigint, @minservermemIN bigint, @systemmemIN bigint, @systemfreememIN bigint, @commit_targetIN bigint, @committedIN bigint';
  2111. EXECUTE sp_executesql @sqlcmd, @params, @maxservermemIN=@maxservermem, @minservermemIN=@minservermem,@systemmemIN=@systemmem, @systemfreememIN=@systemfreemem, @commit_targetIN=@commit_target, @committedIN=@committed
  2112. END;
  2113. IF @numa > 1 AND @sqlmajorver > 10
  2114. BEGIN
  2115. 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;')
  2116. END
  2117. ELSE IF @numa > 1 AND @sqlmajorver = 10
  2118. BEGIN
  2119. 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;')
  2120. END;
  2121. IF @ptochecks = 1
  2122. BEGIN
  2123. RAISERROR (N' |-Starting RM Task', 10, 1) WITH NOWAIT
  2124. IF @LowMemoryThreshold IS NOT NULL
  2125. SELECT 'Memory_checks' AS [Category], 'Memory_RM_Tresholds' AS [Information], @LowMemoryThreshold AS [MEMPHYSICAL_LOW_Threshold], @LowMemoryThreshold * 3 AS [MEMPHYSICAL_HIGH_Threshold]
  2126. SELECT 'Memory_checks' AS [Category], 'Memory_RM_Notifications' AS [Information],
  2127. 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())
  2128. ELSE DATEADD(s, ([TIMESTAMP]/1000) - (si.ms_ticks/1000), GETDATE()) END AS Event_Time,
  2129. record.value('(./Record/ResourceMonitor/Notification)[1]', 'VARCHAR(max)') AS [Notification],
  2130. record.value('(./Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint')/1024 AS [Total_Physical_Mem_MB],
  2131. record.value('(./Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint')/1024 AS [Avail_Physical_Mem_MB],
  2132. record.value('(./Record/MemoryRecord/AvailableVirtualAddressSpace)[1]', 'bigint')/1024 AS [Avail_VAS_MB],
  2133. record.value('(./Record/MemoryRecord/TotalPageFile)[1]', 'bigint')/1024 AS [Total_Pagefile_MB],
  2134. record.value('(./Record/MemoryRecord/AvailablePageFile)[1]', 'bigint')/1024 AS [Avail_Pagefile_MB]
  2135. FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  2136. FROM sys.dm_os_ring_buffers (NOLOCK)
  2137. WHERE ring_buffer_type = N'RING_BUFFER_RESOURCE_MONITOR') AS x
  2138. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2139. --WHERE CASE WHEN x.[timestamp] BETWEEN -2147483648 AND 2147483648 THEN DATEADD(ms, x.[timestamp] - si.ms_ticks, GETDATE())
  2140. -- ELSE DATEADD(s, (x.[timestamp]/1000) - (si.ms_ticks/1000), GETDATE()) END >= DATEADD(hh, -12, GETDATE())
  2141. ORDER BY 2 DESC;
  2142. RAISERROR (N' |-Starting Hand Movements from Cache Clock Hands', 10, 1) WITH NOWAIT
  2143. IF (SELECT COUNT(rounds_count) FROM sys.dm_os_memory_cache_clock_hands (NOLOCK) WHERE rounds_count > 0) > 0
  2144. BEGIN
  2145. IF @sqlmajorver >= 11
  2146. BEGIN
  2147. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Clock_Hand_Notifications'' AS [Information], mcch.name, mcch.[type],
  2148. mcch.clock_hand, mcch.clock_status, SUM(mcch.rounds_count) AS rounds_count,
  2149. SUM(mcch.removed_all_rounds_count) AS cache_entries_removed_all_rounds,
  2150. SUM(mcch.removed_last_round_count) AS cache_entries_removed_last_round,
  2151. SUM(mcch.updated_last_round_count) AS cache_entries_updated_last_round,
  2152. SUM(mcc.pages_kb) AS cache_pages_kb,
  2153. SUM(mcc.pages_in_use_kb) AS cache_pages_in_use_kb,
  2154. SUM(mcc.entries_count) AS cache_entries_count,
  2155. SUM(mcc.entries_in_use_count) AS cache_entries_in_use_count,
  2156. 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())
  2157. 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())
  2158. ELSE NULL END AS last_clock_hand_move
  2159. FROM sys.dm_os_memory_cache_counters mcc (NOLOCK)
  2160. INNER JOIN sys.dm_os_memory_cache_clock_hands mcch (NOLOCK) ON mcc.cache_address = mcch.cache_address
  2161. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2162. WHERE mcch.rounds_count > 0
  2163. 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
  2164. ORDER BY SUM(mcch.removed_all_rounds_count) DESC, mcch.[type];'
  2165. END
  2166. ELSE
  2167. BEGIN
  2168. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Clock_Hand_Notifications'' AS [Information], mcch.name, mcch.[type],
  2169. mcch.clock_hand, mcch.clock_status, SUM(mcch.rounds_count) AS rounds_count,
  2170. SUM(mcch.removed_all_rounds_count) AS cache_entries_removed_all_rounds,
  2171. SUM(mcch.removed_last_round_count) AS cache_entries_removed_last_round,
  2172. SUM(mcch.updated_last_round_count) AS cache_entries_updated_last_round,
  2173. SUM(mcc.single_pages_kb) AS cache_single_pages_kb,
  2174. SUM(mcc.multi_pages_kb) AS cache_multi_pages_kb,
  2175. SUM(mcc.single_pages_in_use_kb) AS cache_single_pages_in_use_kb,
  2176. SUM(mcc.multi_pages_in_use_kb) AS cache_multi_pages_in_use_kb,
  2177. SUM(mcc.entries_count) AS cache_entries_count,
  2178. SUM(mcc.entries_in_use_count) AS cache_entries_in_use_count,
  2179. 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())
  2180. 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())
  2181. ELSE NULL END AS last_clock_hand_move
  2182. FROM sys.dm_os_memory_cache_counters mcc (NOLOCK)
  2183. INNER JOIN sys.dm_os_memory_cache_clock_hands mcch (NOLOCK) ON mcc.cache_address = mcch.cache_address
  2184. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2185. WHERE mcch.rounds_count > 0
  2186. 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
  2187. ORDER BY SUM(mcch.removed_all_rounds_count) DESC, mcch.[type];'
  2188. END
  2189. EXECUTE sp_executesql @sqlcmd;
  2190. END
  2191. ELSE
  2192. BEGIN
  2193. SELECT 'Memory_checks' AS [Category], 'Clock_Hand_Notifications' AS [Information], '[OK]' AS Comment
  2194. END;
  2195. IF @bpool_consumer = 1
  2196. BEGIN
  2197. RAISERROR (N' |-Starting Buffer Pool Consumers from Buffer Descriptors', 10, 1) WITH NOWAIT
  2198. -- Note: in case of NUMA architecture, more than one entry per database is expected
  2199. SET @sqlcmd = 'SELECT ''Memory_checks'' AS [Category], ''Buffer_Pool_Consumers'' AS [Information],
  2200. COUNT_BIG(DISTINCT page_id)*8/1024 AS total_pages_MB,
  2201. CASE database_id WHEN 32767 THEN ''ResourceDB'' ELSE DB_NAME(database_id) END AS database_name,
  2202. SUM(row_count)/COUNT_BIG(DISTINCT page_id) AS avg_row_count_per_page,
  2203. SUM(CONVERT(BIGINT, free_space_in_bytes))/COUNT_BIG(DISTINCT page_id) AS avg_free_space_bytes_per_page
  2204. ' + CASE WHEN @sqlmajorver >= 12 THEN ',is_in_bpool_extension' ELSE '' END + '
  2205. ' + CASE WHEN @sqlmajorver = 10 THEN ',numa_node' ELSE '' END + '
  2206. ' + CASE WHEN @sqlmajorver >= 11 THEN ',AVG(read_microsec) AS avg_read_microsec' ELSE '' END + '
  2207. FROM sys.dm_os_buffer_descriptors
  2208. --WHERE bd.page_type IN (''DATA_PAGE'', ''INDEX_PAGE'')
  2209. GROUP BY database_id' + CASE WHEN @sqlmajorver >= 10 THEN ', numa_node' ELSE '' END + CASE WHEN @sqlmajorver >= 12 THEN ', is_in_bpool_extension' ELSE '' END + '
  2210. ORDER BY total_pages_MB DESC;'
  2211. EXECUTE sp_executesql @sqlcmd;
  2212. END
  2213. RAISERROR (N' |-Starting Memory Allocations from Memory Clerks', 10, 1) WITH NOWAIT
  2214. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], [type] AS Alloc_Type,
  2215. ' + 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'
  2216. ELSE 'SUM(pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb + awe_allocated_kb) AS Alloc_Mem_KB' END + '
  2217. FROM sys.dm_os_memory_clerks
  2218. WHERE type IN (''CACHESTORE_COLUMNSTOREOBJECTPOOL'',''CACHESTORE_CLRPROC'',''CACHESTORE_OBJCP'',''CACHESTORE_PHDR'',''CACHESTORE_SQLCP'',''CACHESTORE_TEMPTABLES'',
  2219. ''MEMORYCLERK_SQLBUFFERPOOL'',''MEMORYCLERK_SQLCLR'',''MEMORYCLERK_SQLGENERAL'',''MEMORYCLERK_SQLLOGPOOL'',''MEMORYCLERK_SQLOPTIMIZER'',
  2220. ''MEMORYCLERK_SQLQUERYCOMPILE'',''MEMORYCLERK_SQLQUERYEXEC'',''MEMORYCLERK_SQLQUERYPLAN'',''MEMORYCLERK_SQLSTORENG'',''MEMORYCLERK_XTP'',
  2221. ''OBJECTSTORE_LOCK_MANAGER'',''OBJECTSTORE_SNI_PACKET'',''USERSTORE_DBMETADATA'',''USERSTORE_OBJPERM'')
  2222. GROUP BY [type]
  2223. UNION ALL
  2224. SELECT ''Memory_checks'' AS [Category], ''Others'' AS Alloc_Type,
  2225. ' + CASE WHEN @sqlmajorver < 11 THEN 'SUM(single_pages_kb + multi_pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb) AS Alloc_Mem_KB'
  2226. ELSE 'SUM(pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb) AS Alloc_Mem_KB' END + '
  2227. FROM sys.dm_os_memory_clerks
  2228. WHERE type NOT IN (''CACHESTORE_COLUMNSTOREOBJECTPOOL'',''CACHESTORE_CLRPROC'',''CACHESTORE_OBJCP'',''CACHESTORE_PHDR'',''CACHESTORE_SQLCP'',''CACHESTORE_TEMPTABLES'',
  2229. ''MEMORYCLERK_SQLBUFFERPOOL'',''MEMORYCLERK_SQLCLR'',''MEMORYCLERK_SQLGENERAL'',''MEMORYCLERK_SQLLOGPOOL'',''MEMORYCLERK_SQLOPTIMIZER'',
  2230. ''MEMORYCLERK_SQLQUERYCOMPILE'',''MEMORYCLERK_SQLQUERYEXEC'',''MEMORYCLERK_SQLQUERYPLAN'',''MEMORYCLERK_SQLSTORENG'',''MEMORYCLERK_XTP'',
  2231. ''OBJECTSTORE_LOCK_MANAGER'',''OBJECTSTORE_SNI_PACKET'',''USERSTORE_DBMETADATA'',''USERSTORE_OBJPERM'')
  2232. ORDER BY Alloc_Mem_KB'
  2233. EXECUTE sp_executesql @sqlcmd;
  2234. IF @sqlmajorver >= 12
  2235. BEGIN
  2236. SET @sqlcmd = N'SELECT @xtpOUT = COUNT(*) FROM sys.dm_db_xtp_memory_consumers';
  2237. SET @params = N'@xtpOUT int OUTPUT';
  2238. EXECUTE sp_executesql @sqlcmd, @params, @xtpOUT = @xtp OUTPUT;
  2239. IF @xtp > 0
  2240. BEGIN
  2241. RAISERROR (N' |-Starting Memory Consumers from In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  2242. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''InMemory_Consumers'' AS Alloc_Type,
  2243. OBJECT_NAME([object_id]) AS [Object_Name], memory_consumer_type_desc, [object_id], index_id,
  2244. allocated_bytes/(1024*1024) AS Allocated_MB, used_bytes/(1024*1024) AS Used_MB,
  2245. CASE WHEN used_bytes IS NULL THEN ''used_bytes_is_varheap_only'' ELSE '''' END AS [Comment]
  2246. FROM sys.dm_db_xtp_memory_consumers
  2247. WHERE [object_id] > 0
  2248. ORDER BY Allocated_MB DESC' -- Only user objects; system objects are negative numbers
  2249. EXECUTE sp_executesql @sqlcmd;
  2250. RAISERROR (N' |-Starting Memory Allocations from In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  2251. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''InMemory_Alloc'' AS Alloc_Type,
  2252. SUM(allocated_bytes)/(1024*1024) AS total_allocated_MB, SUM(used_bytes)/(1024*1024) AS total_used_MB
  2253. FROM sys.dm_db_xtp_memory_consumers
  2254. ORDER BY total_allocated_MB DESC'
  2255. EXECUTE sp_executesql @sqlcmd;
  2256. END;
  2257. END;
  2258. END;
  2259. RAISERROR (N' |-Starting OOM', 10, 1) WITH NOWAIT
  2260. IF (SELECT COUNT([TIMESTAMP]) FROM sys.dm_os_ring_buffers (NOLOCK) WHERE ring_buffer_type = N'RING_BUFFER_OOM') > 0
  2261. BEGIN
  2262. SELECT 'Memory_checks' AS [Category], 'OOM_Notifications' AS [Information],
  2263. 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())
  2264. ELSE DATEADD(s, ([TIMESTAMP]/1000) - (si.ms_ticks/1000), GETDATE()) END AS Event_Time,
  2265. record.value('(./Record/OOM/Action)[1]', 'varchar(50)') AS [Action],
  2266. record.value('(./Record/OOM/Resources)[1]', 'int') AS [Resources],
  2267. record.value('(./Record/OOM/Task)[1]', 'varchar(20)') AS [Task],
  2268. record.value('(./Record/OOM/Pool)[1]', 'int') AS [PoolID],
  2269. rgrp.name AS [PoolName],
  2270. record.value('(./Record/MemoryRecord/MemoryUtilization)[1]', 'bigint') AS [MemoryUtilPct],
  2271. record.value('(./Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint')/1024 AS [Total_Physical_Mem_MB],
  2272. record.value('(./Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint')/1024 AS [Avail_Physical_Mem_MB],
  2273. record.value('(./Record/MemoryRecord/AvailableVirtualAddressSpace)[1]', 'bigint')/1024 AS [Avail_VAS_MB],
  2274. record.value('(./Record/MemoryRecord/TotalPageFile)[1]', 'bigint')/1024 AS [Total_Pagefile_MB],
  2275. record.value('(./Record/MemoryRecord/AvailablePageFile)[1]', 'bigint')/1024 AS [Avail_Pagefile_MB]
  2276. FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  2277. FROM sys.dm_os_ring_buffers (NOLOCK)
  2278. WHERE ring_buffer_type = N'RING_BUFFER_OOM') AS x
  2279. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2280. LEFT JOIN sys.resource_governor_resource_pools rgrp (NOLOCK) ON rgrp.pool_id = record.value('(./Record/OOM/Pool)[1]', 'int')
  2281. --WHERE CASE WHEN x.[timestamp] BETWEEN -2147483648 AND 2147483648 THEN DATEADD(ms, x.[timestamp] - si.ms_ticks, GETDATE())
  2282. -- ELSE DATEADD(s, (x.[timestamp]/1000) - (si.ms_ticks/1000), GETDATE()) END >= DATEADD(hh, -12, GETDATE())
  2283. ORDER BY 2 DESC;
  2284. END
  2285. ELSE
  2286. BEGIN
  2287. SELECT 'Memory_checks' AS [Category], 'OOM_Notifications' AS [Information], '[OK]' AS Comment
  2288. END;
  2289. --------------------------------------------------------------------------------------------------------------------------------
  2290. -- LPIM subsection
  2291. --------------------------------------------------------------------------------------------------------------------------------
  2292. RAISERROR (N' |-Starting LPIM', 10, 1) WITH NOWAIT
  2293. DECLARE @lpim bit, @lognumber int, @logcount int
  2294. IF ((@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13)
  2295. BEGIN
  2296. SET @sqlcmd = N'SELECT @lpimOUT = CASE WHEN sql_memory_model = 2 THEN 1 ELSE 0 END FROM sys.dm_os_sys_info';
  2297. SET @params = N'@lpimOUT bit OUTPUT';
  2298. EXECUTE sp_executesql @sqlcmd, @params, @lpimOUT=@lpim OUTPUT;
  2299. END
  2300. ELSE IF ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13)
  2301. BEGIN
  2302. SET @sqlcmd = N'SELECT @lpimOUT = CASE WHEN locked_page_allocations_kb > 0 THEN 1 ELSE 0 END FROM sys.dm_os_process_memory (NOLOCK)'
  2303. SET @params = N'@lpimOUT bit OUTPUT';
  2304. EXECUTE sp_executesql @sqlcmd, @params, @lpimOUT=@lpim OUTPUT
  2305. END
  2306. ELSE IF @sqlmajorver = 9
  2307. BEGIN
  2308. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2309. OR ISNULL(IS_SRVROLEMEMBER(N'securityadmin'), 0) = 1 -- Is securityadmin
  2310. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_readerrorlog') > 0
  2311. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_readerrorlog') > 0
  2312. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_enumerrorlogs') > 0)
  2313. BEGIN
  2314. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimdbcc'))
  2315. DROP TABLE #lpimdbcc;
  2316. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimdbcc'))
  2317. CREATE TABLE #lpimdbcc (logdate DATETIME, spid VARCHAR(50), logmsg VARCHAR(4000))
  2318. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimavail_logs'))
  2319. DROP TABLE #lpimavail_logs;
  2320. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimavail_logs'))
  2321. CREATE TABLE #lpimavail_logs (lognum int, logdate DATETIME, logsize int)
  2322. -- Get the number of available logs
  2323. INSERT INTO #lpimavail_logs
  2324. EXEC xp_enumerrorlogs
  2325. SELECT @lognumber = MIN(lognum) FROM #lpimavail_logs WHERE DATEADD(dd, DATEDIFF(dd, 0, logdate), 0) >= DATEADD(dd, DATEDIFF(dd, 0, @StartDate), 0)
  2326. SELECT @logcount = ISNULL(MAX(lognum),@lognumber) FROM #lpimavail_logs WHERE DATEADD(dd, DATEDIFF(dd, 0, logdate), 0) >= DATEADD(dd, DATEDIFF(dd, 0, @StartDate), 0)
  2327. IF @lognumber IS NULL
  2328. BEGIN
  2329. SELECT @ErrorMessage = '[WARNING: Could not retrieve information about Locked pages usage in SQL Server 2005]'
  2330. RAISERROR (@ErrorMessage, 16, 1);
  2331. END
  2332. ELSE
  2333. WHILE @lognumber < @logcount
  2334. BEGIN
  2335. -- Cycle through sql error logs (Cannot use Large Page Extensions: lock memory privilege was not granted)
  2336. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''Using locked pages for buffer pool'''
  2337. BEGIN TRY
  2338. INSERT INTO #lpimdbcc (logdate, spid, logmsg)
  2339. EXECUTE (@sqlcmd);
  2340. END TRY
  2341. BEGIN CATCH
  2342. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2343. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  2344. RAISERROR (@ErrorMessage, 16, 1);
  2345. END CATCH
  2346. -- Next log
  2347. --SET @lognumber = @lognumber + 1
  2348. SELECT @lognumber = MIN(lognum) FROM #lpimavail_logs WHERE lognum > @lognumber
  2349. END
  2350. IF (SELECT COUNT(*) FROM #lpimdbcc) > 0
  2351. BEGIN
  2352. SET @lpim = 1
  2353. END
  2354. ELSE IF (SELECT COUNT(*) FROM #lpimdbcc) = 0 AND @lognumber IS NOT NULL
  2355. BEGIN
  2356. SET @lpim = 0
  2357. END;
  2358. DROP TABLE #lpimavail_logs;
  2359. DROP TABLE #lpimdbcc;
  2360. END
  2361. ELSE
  2362. BEGIN
  2363. RAISERROR('[WARNING: Only a sysadmin or securityadmin can run the "Locked_pages" check. Bypassing check]', 16, 1, N'permissions')
  2364. 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')
  2365. --RETURN
  2366. END;
  2367. END
  2368. IF @lpim = 0 AND CONVERT(DECIMAL(3,1), @winver) < 6.0 AND @arch = 64
  2369. BEGIN
  2370. 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]
  2371. END
  2372. ELSE IF @lpim = 1 AND CONVERT(DECIMAL(3,1), @winver) < 6.0 AND @arch = 64
  2373. BEGIN
  2374. 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]
  2375. END
  2376. ELSE IF @lpim = 1 AND CONVERT(DECIMAL(3,1), @winver) >= 6.0 AND @arch = 64
  2377. BEGIN
  2378. 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]
  2379. END
  2380. ELSE IF @lpim IS NULL
  2381. BEGIN
  2382. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[Could_not_retrieve_information]' AS [Deviation]
  2383. END
  2384. ELSE
  2385. BEGIN
  2386. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[Not_used]' AS [Deviation]
  2387. END;
  2388. --------------------------------------------------------------------------------------------------------------------------------
  2389. -- Pagefile subsection
  2390. --------------------------------------------------------------------------------------------------------------------------------
  2391. RAISERROR (N'|-Starting Pagefile Checks', 10, 1) WITH NOWAIT
  2392. DECLARE @pf_value tinyint--, @RegKey NVARCHAR(255)
  2393. DECLARE @pagefile bigint, @freepagefile bigint, @paged bigint
  2394. DECLARE @tbl_pf_value TABLE (Value VARCHAR(25), Data VARCHAR(50))
  2395. IF @sqlmajorver = 9
  2396. BEGIN
  2397. SET @sqlcmd = N'SELECT @pagefileOUT = (t1.record.value(''(./Record/MemoryRecord/TotalPageFile)[1]'', ''bigint'')-t1.record.value(''(./Record/MemoryRecord/TotalPhysicalMemory)[1]'', ''bigint''))/1024,
  2398. @freepagefileOUT = (t1.record.value(''(./Record/MemoryRecord/AvailablePageFile)[1]'', ''bigint'')-t1.record.value(''(./Record/MemoryRecord/AvailablePhysicalMemory)[1]'', ''bigint''))/1024,
  2399. @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
  2400. FROM (SELECT MAX([TIMESTAMP]) AS [TIMESTAMP], CONVERT(xml, record) AS record
  2401. FROM sys.dm_os_ring_buffers (NOLOCK)
  2402. WHERE ring_buffer_type = N''RING_BUFFER_RESOURCE_MONITOR''
  2403. AND record LIKE ''%RESOURCE_MEMPHYSICAL%''
  2404. GROUP BY record) AS t1';
  2405. END
  2406. ELSE
  2407. BEGIN
  2408. SET @sqlcmd = N'SELECT @pagefileOUT = (total_page_file_kb-total_physical_memory_kb)/1024,
  2409. @freepagefileOUT = (available_page_file_kb-available_physical_memory_kb)/1024,
  2410. @pagedOUT = ((total_page_file_kb-available_page_file_kb)/total_page_file_kb)
  2411. FROM sys.dm_os_sys_memory (NOLOCK)';
  2412. END
  2413. SET @params = N'@pagefileOUT bigint OUTPUT, @freepagefileOUT bigint OUTPUT, @pagedOUT bigint OUTPUT';
  2414. EXECUTE sp_executesql @sqlcmd, @params, @pagefileOUT=@pagefile OUTPUT, @freepagefileOUT=@freepagefile OUTPUT, @pagedOUT=@paged OUTPUT;
  2415. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  2416. BEGIN
  2417. BEGIN TRY
  2418. SELECT @RegKey = N'System\CurrentControlSet\Control\Session Manager\Memory Management'
  2419. INSERT INTO @tbl_pf_value
  2420. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'PagingFiles', NO_OUTPUT
  2421. END TRY
  2422. BEGIN CATCH
  2423. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2424. SELECT @ErrorMessage = 'Pagefile subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  2425. RAISERROR (@ErrorMessage, 16, 1);
  2426. END CATCH
  2427. END
  2428. ELSE
  2429. BEGIN
  2430. RAISERROR('[WARNING: Missing permissions for full "Pagefile" checks. Bypassing System managed pagefile check]', 16, 1, N'sysadmin')
  2431. --RETURN
  2432. END;
  2433. IF (SELECT COUNT(*) FROM @tbl_pf_value) > 0
  2434. BEGIN
  2435. SELECT @pf_value = CASE WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data = '') > 0 THEN 1
  2436. WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data = '?:\pagefile.sys') > 0 THEN 2
  2437. WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data LIKE '%:\pagefile.sys 0 0%') > 0 THEN 3
  2438. ELSE 0 END
  2439. FROM @tbl_pf_value
  2440. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_management' AS [Check],
  2441. CASE WHEN @pf_value = 1 THEN '[WARNING: No pagefile is configured]'
  2442. WHEN @pf_value = 2 THEN '[WARNING: Pagefile is managed automatically on ALL drives]'
  2443. WHEN @pf_value = 3 THEN '[WARNING: Pagefile is managed automatically]'
  2444. ELSE '[OK]' END AS [Deviation]
  2445. END
  2446. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_free_space' AS [Check],
  2447. CASE WHEN @freepagefile <= 150 THEN '[WARNING: Pagefile free space is dangerously low. Please revise Pagefile settings]'
  2448. WHEN (@freepagefile*100)/@pagefile <= 10 THEN '[WARNING: Less than 10 percent of Pagefile is available. Please revise Pagefile settings]'
  2449. WHEN (@freepagefile*100)/@pagefile <= 30 THEN '[INFORMATION: Less than 30 percent of Pagefile is available]'
  2450. ELSE '[OK]' END AS [Deviation],
  2451. @pagefile AS total_pagefile_MB, @freepagefile AS available_pagefile_MB;
  2452. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_minimum_size' AS [Check],
  2453. 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]'
  2454. 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]'
  2455. WHEN @winver <> '5.2' THEN '[NA]'
  2456. ELSE '[OK]' END AS [Deviation],
  2457. @pagefile AS total_pagefile_MB;
  2458. SELECT 'Pagefile_checks' AS [Category], 'Process_paged_out' AS [Check],
  2459. CASE WHEN @paged > 0 THEN '[WARNING: Part of SQL Server process memory has been paged out. Please revise LPIM settings]'
  2460. ELSE '[OK]' END AS [Deviation],
  2461. @paged AS paged_out_MB;
  2462. IF @ptochecks = 1
  2463. RAISERROR (N'|-Starting I/O Checks', 10, 1) WITH NOWAIT
  2464. --------------------------------------------------------------------------------------------------------------------------------
  2465. -- I/O stall in database files over 50% of cumulative sampled time or I/O latencies over 20ms in the last 5s subsection
  2466. -- io_stall refers to user processes waited for I/O. This number can be much greater than the sample_ms.
  2467. -- Might indicate that your I/O has insufficient service capabilities (HBA queue depths, reduced throughput, etc).
  2468. --------------------------------------------------------------------------------------------------------------------------------
  2469. IF @ptochecks = 1
  2470. BEGIN
  2471. RAISERROR (N' |-Starting I/O Stall subsection (wait for 5s)', 10, 1) WITH NOWAIT
  2472. DECLARE @mincol DATETIME, @maxcol DATETIME
  2473. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  2474. DROP TABLE #tmp_dm_io_virtual_file_stats;
  2475. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  2476. 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),
  2477. [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,
  2478. [num_of_bytes_written] bigint,[io_stall_write_ms] bigint,[io_stall] bigint,[size_on_disk_bytes] bigint,
  2479. CONSTRAINT PK_dm_io_virtual_file_stats PRIMARY KEY CLUSTERED(database_id, [file_id], [retrieval_time]));
  2480. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  2481. DROP TABLE #tblIOStall;
  2482. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  2483. CREATE TABLE #tblIOStall (database_id int, [file_id] int, [DBName] sysname, [logical_file_name] NVARCHAR(255), [type_desc] NVARCHAR(60),
  2484. [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,
  2485. 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,
  2486. avg_io_stall_write_pct int, cumulative_io_stall_write_pct int, cumulative_sample_HH int, io_stall_pct_of_cumulative_sample int,
  2487. CONSTRAINT PK_IOStall PRIMARY KEY CLUSTERED(database_id, [file_id]));
  2488. SELECT @mincol = GETDATE()
  2489. INSERT INTO #tmp_dm_io_virtual_file_stats
  2490. SELECT @mincol, f.database_id, f.[file_id], DB_NAME(f.database_id), f.name AS logical_file_name, f.type_desc,
  2491. CAST (CASE
  2492. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2493. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2494. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2495. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2496. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2497. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2498. ELSE f.physical_name
  2499. END AS NVARCHAR(255)) AS physical_location,
  2500. fs.[sample_ms],fs.[num_of_reads],fs.[num_of_bytes_read],fs.[io_stall_read_ms],fs.[num_of_writes],
  2501. fs.[num_of_bytes_written],fs.[io_stall_write_ms],fs.[io_stall],fs.[size_on_disk_bytes]
  2502. FROM sys.dm_io_virtual_file_stats (default, default) AS fs
  2503. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id]
  2504. WAITFOR DELAY '00:00:05' -- wait 5s between pooling
  2505. SELECT @maxcol = GETDATE()
  2506. INSERT INTO #tmp_dm_io_virtual_file_stats
  2507. SELECT @maxcol, f.database_id, f.[file_id], DB_NAME(f.database_id), f.name AS logical_file_name, f.type_desc,
  2508. CAST (CASE
  2509. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2510. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2511. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2512. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2513. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2514. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2515. ELSE f.physical_name
  2516. END AS NVARCHAR(255)) AS physical_location,
  2517. fs.[sample_ms],fs.[num_of_reads],fs.[num_of_bytes_read],fs.[io_stall_read_ms],fs.[num_of_writes],
  2518. fs.[num_of_bytes_written],fs.[io_stall_write_ms],fs.[io_stall],fs.[size_on_disk_bytes]
  2519. FROM sys.dm_io_virtual_file_stats (default, default) AS fs
  2520. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id]
  2521. ;WITH cteFileStats1 AS (SELECT database_id,[file_id],[DBName],[logical_file_name],[type_desc],
  2522. [physical_location],[sample_ms],[num_of_reads],[num_of_bytes_read],[io_stall_read_ms],[num_of_writes],
  2523. [num_of_bytes_written],[io_stall_write_ms],[io_stall],[size_on_disk_bytes]
  2524. FROM #tmp_dm_io_virtual_file_stats WHERE [retrieval_time] = @mincol),
  2525. cteFileStats2 AS (SELECT database_id,[file_id],[DBName],[logical_file_name],[type_desc],
  2526. [physical_location],[sample_ms],[num_of_reads],[num_of_bytes_read],[io_stall_read_ms],[num_of_writes],
  2527. [num_of_bytes_written],[io_stall_write_ms],[io_stall],[size_on_disk_bytes]
  2528. FROM #tmp_dm_io_virtual_file_stats WHERE [retrieval_time] = @maxcol)
  2529. INSERT INTO #tblIOStall
  2530. SELECT t1.database_id, t1.[file_id], t1.[DBName], t1.logical_file_name, t1.type_desc, t1.physical_location,
  2531. t1.size_on_disk_bytes/1024/1024 AS size_on_disk_Mbytes,
  2532. (t2.num_of_reads-t1.num_of_reads) AS num_of_reads,
  2533. (t2.num_of_writes-t1.num_of_writes) AS num_of_writes,
  2534. (t2.num_of_bytes_read-t1.num_of_bytes_read)/1024 AS num_of_KBytes_read,
  2535. (t2.num_of_bytes_written-t1.num_of_bytes_written)/1024 AS num_of_KBytes_written,
  2536. (t2.io_stall-t1.io_stall) AS io_stall_ms,
  2537. (t2.io_stall_read_ms-t1.io_stall_read_ms) AS io_stall_read_ms,
  2538. (t2.io_stall_write_ms-t1.io_stall_write_ms) AS io_stall_write_ms,
  2539. ((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,
  2540. ((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,
  2541. ((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,
  2542. ((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,
  2543. ((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,
  2544. ((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,
  2545. ABS((t2.sample_ms/1000)/60/60) AS cumulative_sample_HH,
  2546. ((t2.io_stall/1000/60)*100)/(ABS((t2.sample_ms/1000)/60)) AS io_stall_pct_of_cumulative_sample
  2547. FROM cteFileStats1 t1 INNER JOIN cteFileStats2 t2 ON t1.database_id = t2.database_id AND t1.[file_id] = t2.[file_id]
  2548. IF (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE avg_read_latency_ms >= 20) > 0
  2549. OR (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE avg_write_latency_ms >= 20) > 0
  2550. BEGIN
  2551. 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]
  2552. 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,
  2553. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2554. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2555. 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
  2556. FROM #tblIOStall
  2557. WHERE avg_read_latency_ms >= 20 OR avg_write_latency_ms >= 20
  2558. ORDER BY avg_read_latency_ms DESC, avg_write_latency_ms DESC, [DBName], [type_desc], [logical_file_name]
  2559. END
  2560. ELSE IF (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE io_stall_pct_of_cumulative_sample > 50) > 0
  2561. BEGIN
  2562. 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]
  2563. 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,
  2564. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2565. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2566. 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
  2567. FROM #tblIOStall
  2568. WHERE io_stall_pct_of_cumulative_sample > 50
  2569. ORDER BY io_stall_pct_of_cumulative_sample DESC, [DBName], [type_desc], [logical_file_name]
  2570. END
  2571. ELSE
  2572. BEGIN
  2573. SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Check], '[OK]' AS [Deviation]
  2574. /*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,
  2575. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2576. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2577. 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
  2578. FROM #tblIOStall
  2579. ORDER BY [DBName], [type_desc], [logical_file_name]*/
  2580. END;
  2581. END;
  2582. --------------------------------------------------------------------------------------------------------------------------------
  2583. -- Pending disk I/O Requests subsection
  2584. -- Indicate that your I/O has insufficient service capabilities (HBA queue depths, reduced throughput, etc).
  2585. --------------------------------------------------------------------------------------------------------------------------------
  2586. IF @ptochecks = 1
  2587. BEGIN
  2588. RAISERROR (N' |-Starting Pending disk I/O Requests subsection (wait for a max of 5s)', 10, 1) WITH NOWAIT
  2589. DECLARE @IOCnt tinyint
  2590. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  2591. DROP TABLE #tblPendingIOReq;
  2592. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  2593. 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));
  2594. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  2595. DROP TABLE #tblPendingIO;
  2596. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  2597. CREATE TABLE #tblPendingIO (database_id int, [file_id] int, [DBName] sysname, [logical_file_name] NVARCHAR(255), [type_desc] NVARCHAR(60),
  2598. [physical_location] NVARCHAR(260), io_stall_min int, io_stall_read_min int, io_stall_write_min int, avg_read_latency_ms int,
  2599. avg_write_latency_ms int, io_stall_read_pct int, io_stall_write_pct int, sampled_HH int,
  2600. 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),
  2601. scheduler_id int, pending_disk_io_count int, work_queue_count bigint);
  2602. SET @IOCnt = 1
  2603. WHILE @IOCnt < 5
  2604. BEGIN
  2605. INSERT INTO #tblPendingIOReq
  2606. SELECT io_completion_request_address, io_handle, io_type, io_pending, io_pending_ms_ticks, scheduler_address
  2607. FROM sys.dm_io_pending_io_requests;
  2608. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 1
  2609. BREAK
  2610. WAITFOR DELAY '00:00:01' -- wait 1s between pooling
  2611. SET @IOCnt = @IOCnt + 1
  2612. END;
  2613. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 0
  2614. BEGIN
  2615. INSERT INTO #tblPendingIO
  2616. 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,
  2617. CAST (CASE
  2618. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2619. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2620. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2621. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2622. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2623. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2624. ELSE f.physical_name
  2625. END AS NVARCHAR(255)) AS physical_location,
  2626. fs.io_stall/1000/60 AS io_stall_min,
  2627. fs.io_stall_read_ms/1000/60 AS io_stall_read_min,
  2628. fs.io_stall_write_ms/1000/60 AS io_stall_write_min,
  2629. (fs.io_stall_read_ms / (1.0 + fs.num_of_reads)) AS avg_read_latency_ms,
  2630. (fs.io_stall_write_ms / (1.0 + fs.num_of_writes)) AS avg_write_latency_ms,
  2631. ((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,
  2632. ((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,
  2633. ABS((fs.sample_ms/1000)/60/60) AS 'sample_HH',
  2634. ((fs.io_stall/1000/60)*100)/(ABS((fs.sample_ms/1000)/60))AS 'io_stall_pct_of_overall_sample',
  2635. pio.io_completion_request_address, pio.io_handle, pio.io_type, pio.io_pending,
  2636. pio.io_pending_ms_ticks, pio.scheduler_address, os.scheduler_id, os.pending_disk_io_count, os.work_queue_count
  2637. FROM #tblPendingIOReq AS pio
  2638. INNER JOIN sys.dm_io_virtual_file_stats (NULL,NULL) AS fs ON fs.file_handle = pio.io_handle
  2639. INNER JOIN sys.dm_os_schedulers AS os ON pio.scheduler_address = os.scheduler_address
  2640. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id];
  2641. END;
  2642. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 0
  2643. BEGIN
  2644. 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]
  2645. 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,
  2646. 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,
  2647. io_completion_request_address, io_type, CASE WHEN io_pending = 1 THEN 'Pending_Context_Switching' ELSE 'Pending_WindowsOS' END AS io_pending_type,
  2648. io_pending_ms_ticks, scheduler_address, scheduler_id, pending_disk_io_count, work_queue_count
  2649. FROM #tblPendingIO
  2650. ORDER BY scheduler_address, [DBName], [type_desc], [logical_file_name]
  2651. END
  2652. ELSE
  2653. BEGIN
  2654. SELECT 'IO_checks' AS [Category], 'Pending_IO' AS [Check], '[OK]' AS [Deviation]
  2655. END;
  2656. END;
  2657. RAISERROR (N'|-Starting Server Checks', 10, 1) WITH NOWAIT
  2658. --------------------------------------------------------------------------------------------------------------------------------
  2659. -- Power plan subsection
  2660. --------------------------------------------------------------------------------------------------------------------------------
  2661. RAISERROR (N' |-Starting Power plan', 10, 1) WITH NOWAIT
  2662. DECLARE @planguid NVARCHAR(64), @powerkey NVARCHAR(255)
  2663. --SELECT @powerkey = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel\NameSpace\{025A5937-A6BE-4686-A844-36FE4BEC8B6D}'
  2664. --SELECT @powerkey = 'SYSTEM\CurrentControlSet\Control\Power\User\Default\PowerSchemes'
  2665. SELECT @powerkey = 'SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes'
  2666. IF CONVERT(DECIMAL(3,1), @winver) >= 6.0
  2667. BEGIN
  2668. BEGIN TRY
  2669. --EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @powerkey, 'PreferredPlan', @planguid OUTPUT, NO_OUTPUT
  2670. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @powerkey, 'ActivePowerScheme', @planguid OUTPUT, NO_OUTPUT
  2671. END TRY
  2672. BEGIN CATCH
  2673. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2674. SELECT @ErrorMessage = 'Power plan subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  2675. RAISERROR (@ErrorMessage, 16, 1);
  2676. END CATCH
  2677. END
  2678. -- http://support.microsoft.com/kb/935799/en-us
  2679. IF @winver IS NULL
  2680. BEGIN
  2681. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Check], '[WARNING: Could not determine Windows version for check]' AS [Deviation]
  2682. END
  2683. ELSE IF @planguid IS NOT NULL AND @planguid <> '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
  2684. BEGIN
  2685. 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]
  2686. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Information], CASE WHEN @planguid = '381b4222-f694-41f0-9685-ff5bb260df2e' THEN 'Balanced'
  2687. WHEN @planguid = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c' THEN 'High Performance'
  2688. WHEN @planguid = 'a1841308-3541-4fab-bc81-f71556f20b4a' THEN 'Power Saver'
  2689. ELSE 'Other' END AS [Power_Plan]
  2690. END
  2691. ELSE IF @planguid IS NOT NULL AND @planguid = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
  2692. BEGIN
  2693. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Check], '[OK]' AS [Deviation]
  2694. END;
  2695. --------------------------------------------------------------------------------------------------------------------------------
  2696. -- Disk Partition alignment offset < 64KB subsection
  2697. --------------------------------------------------------------------------------------------------------------------------------
  2698. RAISERROR (N' |-Starting Disk Partition alignment offset < 64KB', 10, 1) WITH NOWAIT
  2699. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  2700. BEGIN
  2701. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2702. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2703. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  2704. AND (SELECT COUNT(l.name)
  2705. FROM sys.server_permissions p JOIN sys.server_principals l
  2706. ON p.grantee_principal_id = l.principal_id
  2707. AND p.class = 100 -- Server
  2708. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  2709. AND l.is_disabled = 0
  2710. AND p.permission_name = 'ALTER SETTINGS'
  2711. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  2712. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2713. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  2714. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  2715. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  2716. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  2717. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  2718. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  2719. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  2720. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  2721. BEGIN
  2722. DECLARE @diskpart int
  2723. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  2724. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  2725. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  2726. RAISERROR (' |-Configuration options set for Disk partition alignment offset check', 10, 1) WITH NOWAIT
  2727. IF @sao = 0
  2728. BEGIN
  2729. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  2730. END
  2731. IF @xcmd = 0
  2732. BEGIN
  2733. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  2734. END
  2735. IF @ole = 0
  2736. BEGIN
  2737. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  2738. END
  2739. DECLARE @output_hw_tot_diskpart TABLE ([PS_OUTPUT] VARCHAR(2048));
  2740. DECLARE @output_hw_format_diskpart TABLE ([volid] smallint IDENTITY(1,1), [HD_Partition] VARCHAR(50) NULL, StartingOffset bigint NULL)
  2741. IF @custompath IS NULL
  2742. BEGIN
  2743. IF @sqlmajorver < 11
  2744. BEGIN
  2745. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  2746. SET @path = @path + '\LOG'
  2747. END
  2748. ELSE
  2749. BEGIN
  2750. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  2751. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  2752. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  2753. END
  2754. -- Create COM object with FSO
  2755. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  2756. IF @OLEResult <> 0
  2757. BEGIN
  2758. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2759. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2760. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2761. END
  2762. ELSE
  2763. BEGIN
  2764. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  2765. IF @OLEResult <> 0
  2766. BEGIN
  2767. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2768. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  2769. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2770. END
  2771. ELSE
  2772. BEGIN
  2773. IF @existout <> 1
  2774. BEGIN
  2775. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  2776. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  2777. END
  2778. END
  2779. EXEC @OLEResult = sp_OADestroy @FSO
  2780. END
  2781. END
  2782. ELSE
  2783. BEGIN
  2784. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  2785. END
  2786. SET @FileName = @path + '\checkbp_diskpart_' + RTRIM(@server) + '.ps1'
  2787. EXEC master.dbo.xp_fileexist @FileName, @existout out
  2788. IF @existout = 0
  2789. BEGIN -- Scan for local disks
  2790. SET @Text1 = '[string] $serverName = ''localhost''
  2791. $partitions = Get-WmiObject -computername $serverName -query "SELECT * FROM Win32_DiskPartition"
  2792. foreach ($partition in $partitions)
  2793. {
  2794. [string] $diskpart = "{0}_{1};{2}" -f $partition.DiskIndex,$partition.Index,$partition.StartingOffset
  2795. Write-Output $diskpart
  2796. }
  2797. '
  2798. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  2799. IF @OLEResult <> 0
  2800. BEGIN
  2801. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2802. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2803. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2804. END
  2805. --Open file
  2806. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  2807. IF @OLEResult <> 0
  2808. BEGIN
  2809. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2810. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  2811. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2812. END
  2813. ELSE
  2814. BEGIN
  2815. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  2816. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  2817. END
  2818. --Write Text1
  2819. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  2820. IF @OLEResult <> 0
  2821. BEGIN
  2822. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2823. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  2824. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2825. END
  2826. EXEC @OLEResult = sp_OADestroy @FileID
  2827. EXEC @OLEResult = sp_OADestroy @FS
  2828. END
  2829. ELSE
  2830. BEGIN
  2831. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  2832. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  2833. END
  2834. IF @psver = 1
  2835. BEGIN
  2836. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  2837. END
  2838. ELSE
  2839. BEGIN
  2840. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  2841. END;
  2842. INSERT INTO @output_hw_tot_diskpart
  2843. EXEC master.dbo.xp_cmdshell @CMD
  2844. SET @CMD = 'del /Q "' + @FileName + '"'
  2845. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  2846. INSERT INTO @output_hw_format_diskpart ([HD_Partition],StartingOffset)
  2847. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  2848. 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)
  2849. FROM @output_hw_tot_diskpart
  2850. WHERE [PS_OUTPUT] IS NOT NULL;
  2851. SET @CMD2 = 'del ' + @FileName
  2852. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  2853. IF @xcmd = 0
  2854. BEGIN
  2855. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  2856. END
  2857. IF @ole = 0
  2858. BEGIN
  2859. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  2860. END
  2861. IF @sao = 0
  2862. BEGIN
  2863. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  2864. END;
  2865. ;WITH diskpartcte (StartingOffset) AS (
  2866. SELECT StartingOffset
  2867. FROM @output_hw_format_diskpart
  2868. WHERE StartingOffset IS NOT NULL OR LEN(StartingOffset) > 0)
  2869. SELECT @diskpart = CASE WHEN (SELECT COUNT(*) FROM diskpartcte) = 0 THEN NULL ELSE COUNT(cte1.[StartingOffset]) END
  2870. FROM diskpartcte cte1
  2871. WHERE cte1.[StartingOffset] < 65536;
  2872. IF @diskpart > 0 AND @diskpart IS NOT NULL
  2873. BEGIN
  2874. 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]
  2875. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Information], LEFT(t1.[HD_Partition],LEN(t1.[HD_Partition])-CHARINDEX('_',t1.[HD_Partition])) AS HD_Volume,
  2876. RIGHT(t1.[HD_Partition],LEN(t1.[HD_Partition])-CHARINDEX('_',t1.[HD_Partition])) AS [HD_Partition],
  2877. (t1.StartingOffset/1024) AS [StartingOffset_KB]
  2878. FROM @output_hw_format_diskpart t1
  2879. WHERE t1.StartingOffset IS NOT NULL OR LEN(t1.StartingOffset) > 0
  2880. ORDER BY t1.[HD_Partition]
  2881. OPTION (RECOMPILE);
  2882. END
  2883. ELSE IF @diskpart IS NULL
  2884. BEGIN
  2885. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Check], '[WARNING: Could not gather information on disk partition offset size]' AS [Deviation]
  2886. END
  2887. ELSE
  2888. BEGIN
  2889. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Check], '[OK]' AS [Deviation]
  2890. END;
  2891. END
  2892. ELSE
  2893. BEGIN
  2894. 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')
  2895. 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')
  2896. --RETURN
  2897. END
  2898. END
  2899. ELSE
  2900. BEGIN
  2901. 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')
  2902. --RETURN
  2903. END;
  2904. --------------------------------------------------------------------------------------------------------------------------------
  2905. -- NTFS block size in volumes that hold database files <> 64KB subsection
  2906. --------------------------------------------------------------------------------------------------------------------------------
  2907. RAISERROR (N' |-Starting NTFS block size in volumes that hold database files <> 64KB', 10, 1) WITH NOWAIT
  2908. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  2909. BEGIN
  2910. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2911. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2912. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  2913. AND (SELECT COUNT(l.name)
  2914. FROM sys.server_permissions p JOIN sys.server_principals l
  2915. ON p.grantee_principal_id = l.principal_id
  2916. AND p.class = 100 -- Server
  2917. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  2918. AND l.is_disabled = 0
  2919. AND p.permission_name = 'ALTER SETTINGS'
  2920. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  2921. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2922. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  2923. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  2924. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  2925. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  2926. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  2927. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  2928. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  2929. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  2930. BEGIN
  2931. DECLARE @ntfs int
  2932. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  2933. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  2934. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  2935. RAISERROR (' |-Configuration options set for NTFS Block size check', 10, 1) WITH NOWAIT
  2936. IF @sao = 0
  2937. BEGIN
  2938. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  2939. END
  2940. IF @xcmd = 0
  2941. BEGIN
  2942. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  2943. END
  2944. IF @ole = 0
  2945. BEGIN
  2946. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  2947. END
  2948. DECLARE @output_hw_tot_ntfs TABLE ([PS_OUTPUT] VARCHAR(2048));
  2949. DECLARE @output_hw_format_ntfs TABLE ([volid] smallint IDENTITY(1,1), [HD_Volume] NVARCHAR(2048) NULL, [NTFS_Block] NVARCHAR(8) NULL)
  2950. IF @custompath IS NULL
  2951. BEGIN
  2952. IF @sqlmajorver < 11
  2953. BEGIN
  2954. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  2955. SET @path = @path + '\LOG'
  2956. END
  2957. ELSE
  2958. BEGIN
  2959. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  2960. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  2961. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  2962. END
  2963. -- Create COM object with FSO
  2964. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  2965. IF @OLEResult <> 0
  2966. BEGIN
  2967. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2968. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2969. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2970. END
  2971. ELSE
  2972. BEGIN
  2973. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  2974. IF @OLEResult <> 0
  2975. BEGIN
  2976. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2977. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  2978. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2979. END
  2980. ELSE
  2981. BEGIN
  2982. IF @existout <> 1
  2983. BEGIN
  2984. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  2985. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  2986. END
  2987. END
  2988. EXEC @OLEResult = sp_OADestroy @FSO
  2989. END
  2990. END
  2991. ELSE
  2992. BEGIN
  2993. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  2994. END
  2995. SET @FileName = @path + '\checkbp_ntfs_' + RTRIM(@server) + '.ps1'
  2996. EXEC master.dbo.xp_fileexist @FileName, @existout out
  2997. IF @existout = 0
  2998. BEGIN -- Scan for local disks
  2999. SET @Text1 = '[string] $serverName = ''localhost''
  3000. $vols = Get-WmiObject -computername $serverName -query "select name, blocksize from Win32_Volume where Capacity <> NULL and DriveType = 3"
  3001. foreach($vol in $vols)
  3002. {
  3003. [string] $drive = "{0};{1}" -f $vol.name,$vol.blocksize
  3004. Write-Output $drive
  3005. } '
  3006. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3007. IF @OLEResult <> 0
  3008. BEGIN
  3009. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3010. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3011. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3012. END
  3013. --Open file
  3014. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3015. IF @OLEResult <> 0
  3016. BEGIN
  3017. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3018. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3019. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3020. END
  3021. ELSE
  3022. BEGIN
  3023. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3024. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3025. END
  3026. --Write Text1
  3027. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3028. IF @OLEResult <> 0
  3029. BEGIN
  3030. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3031. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3032. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3033. END
  3034. EXEC @OLEResult = sp_OADestroy @FileID
  3035. EXEC @OLEResult = sp_OADestroy @FS
  3036. END
  3037. ELSE
  3038. BEGIN
  3039. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3040. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3041. END
  3042. IF @psver = 1
  3043. BEGIN
  3044. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3045. END
  3046. ELSE
  3047. BEGIN
  3048. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3049. END;
  3050. INSERT INTO @output_hw_tot_ntfs
  3051. EXEC master.dbo.xp_cmdshell @CMD
  3052. SET @CMD = 'del /Q "' + @FileName + '"'
  3053. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3054. INSERT INTO @output_hw_format_ntfs ([HD_Volume],[NTFS_Block])
  3055. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3056. 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)
  3057. FROM @output_hw_tot_ntfs
  3058. WHERE [PS_OUTPUT] IS NOT NULL;
  3059. SET @CMD2 = 'del ' + @FileName
  3060. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3061. IF @xcmd = 0
  3062. BEGIN
  3063. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3064. END
  3065. IF @ole = 0
  3066. BEGIN
  3067. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3068. END
  3069. IF @sao = 0
  3070. BEGIN
  3071. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3072. END;
  3073. WITH ntfscte (physical_name, ntfsblock) AS (
  3074. SELECT DISTINCT(LEFT(physical_name, LEN(t2.HD_Volume))), [NTFS_Block]
  3075. FROM sys.master_files t1 INNER JOIN @output_hw_format_ntfs t2
  3076. ON LEFT(physical_name, LEN(t2.HD_Volume)) = t2.HD_Volume
  3077. WHERE [database_id] <> 32767 AND (t2.[NTFS_Block] IS NOT NULL OR LEN(t2.[NTFS_Block]) > 0)
  3078. )
  3079. SELECT @ntfs = CASE WHEN (SELECT COUNT(*) FROM ntfscte) = 0 THEN NULL ELSE COUNT(cte1.[ntfsblock]) END
  3080. FROM ntfscte cte1
  3081. WHERE cte1.[ntfsblock] <> 65536;
  3082. IF @ntfs > 0 AND @ntfs IS NOT NULL
  3083. BEGIN
  3084. 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]
  3085. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Information], t1.HD_Volume, (t1.[NTFS_Block]/1024) AS [NTFS_Block_Size_KB]
  3086. FROM (SELECT DISTINCT(LEFT(physical_name, LEN(t2.HD_Volume))) AS [HD_Volume], [NTFS_Block]
  3087. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format_ntfs t2
  3088. ON LEFT(physical_name, LEN(t2.HD_Volume)) = t2.HD_Volume
  3089. WHERE [database_id] <> 32767 AND (t2.[NTFS_Block] IS NOT NULL OR LEN(t2.[NTFS_Block]) > 0)) t1
  3090. ORDER BY t1.HD_Volume OPTION (RECOMPILE);
  3091. END
  3092. ELSE IF @ntfs IS NULL
  3093. BEGIN
  3094. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Check], '[WARNING: Could not gather information on NTFS block size]' AS [Deviation]
  3095. END
  3096. ELSE
  3097. BEGIN
  3098. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Check], '[OK]' AS [Deviation]
  3099. END;
  3100. END
  3101. ELSE
  3102. BEGIN
  3103. 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')
  3104. 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')
  3105. --RETURN
  3106. END
  3107. END
  3108. ELSE
  3109. BEGIN
  3110. 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')
  3111. --RETURN
  3112. END;
  3113. --------------------------------------------------------------------------------------------------------------------------------
  3114. -- Disk Fragmentation Analysis subsection
  3115. --------------------------------------------------------------------------------------------------------------------------------
  3116. IF @diskfrag = 1
  3117. BEGIN
  3118. RAISERROR (N' |-Starting Disk Fragmentation Analysis', 10, 1) WITH NOWAIT
  3119. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  3120. BEGIN
  3121. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3122. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3123. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  3124. AND (SELECT COUNT(l.name)
  3125. FROM sys.server_permissions p JOIN sys.server_principals l
  3126. ON p.grantee_principal_id = l.principal_id
  3127. AND p.class = 100 -- Server
  3128. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  3129. AND l.is_disabled = 0
  3130. AND p.permission_name = 'ALTER SETTINGS'
  3131. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  3132. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3133. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  3134. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  3135. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  3136. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  3137. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  3138. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  3139. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  3140. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  3141. BEGIN
  3142. DECLARE @frag int
  3143. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3144. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3145. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  3146. RAISERROR (' |-Configuration options set for Disk Fragmentation Analysis', 10, 1) WITH NOWAIT
  3147. IF @sao = 0
  3148. BEGIN
  3149. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3150. END
  3151. IF @xcmd = 0
  3152. BEGIN
  3153. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3154. END
  3155. IF @ole = 0
  3156. BEGIN
  3157. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  3158. END
  3159. DECLARE @output_hw_frag TABLE ([PS_OUTPUT] VARCHAR(2048));
  3160. DECLARE @output_hw_format_frag TABLE ([volid] smallint IDENTITY(1,1), [volfrag] VARCHAR(255), [fragrec] VARCHAR(10) NULL)
  3161. IF @custompath IS NULL
  3162. BEGIN
  3163. IF @sqlmajorver < 11
  3164. BEGIN
  3165. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  3166. SET @path = @path + '\LOG'
  3167. END
  3168. ELSE
  3169. BEGIN
  3170. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  3171. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  3172. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  3173. END
  3174. -- Create COM object with FSO
  3175. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  3176. IF @OLEResult <> 0
  3177. BEGIN
  3178. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3179. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3180. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3181. END
  3182. ELSE
  3183. BEGIN
  3184. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  3185. IF @OLEResult <> 0
  3186. BEGIN
  3187. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3188. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  3189. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3190. END
  3191. ELSE
  3192. BEGIN
  3193. IF @existout <> 1
  3194. BEGIN
  3195. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  3196. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  3197. END
  3198. END
  3199. EXEC @OLEResult = sp_OADestroy @FSO
  3200. END
  3201. END
  3202. ELSE
  3203. BEGIN
  3204. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  3205. END
  3206. SET @FileName = @path + '\checkbp_frag_' + RTRIM(@server) + '.ps1'
  3207. EXEC master.dbo.xp_fileexist @FileName, @existout out
  3208. IF @existout = 0
  3209. BEGIN -- Scan for frag
  3210. SET @Text1 = '$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
  3211. $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
  3212. $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
  3213. if ($myWindowsPrincipal.IsInRole($adminRole))
  3214. {
  3215. [string] $serverName = ''localhost''
  3216. $DiskResults = @()
  3217. $objDisks = Get-WmiObject -Computername $serverName -Class Win32_Volume | Where-Object { $_.DriveType -eq 3 -and $_.Name -like "*:\"}
  3218. ForEach( $disk in $objDisks)
  3219. {
  3220. $objDefrag = $disk.DefragAnalysis()
  3221. $rec = $objDefrag.DefragRecommended
  3222. $objDefragDetail = $objDefrag.DefragAnalysis
  3223. $diskFragmentation = $objDefragDetail.TotalPercentFragmentation
  3224. $FreeFragmentation = $objDefragDetail.FreeSpacePercentFragmentation
  3225. $FileFragmentation = $objDefragDetail.FilePercentFragmentation
  3226. [string] $ThisVolume = "{0}TotalFragPct {1} :: FreeSpaceFragPct {2} :: FileFragPct {3};{4}" -f $($disk.Name),$diskFragmentation,$FreeFragmentation,$FileFragmentation,$rec
  3227. $DiskResults += $ThisVolume
  3228. }
  3229. $DiskResults
  3230. }
  3231. else
  3232. {
  3233. Write-Host "NotAdmin"
  3234. }
  3235. '
  3236. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3237. IF @OLEResult <> 0
  3238. BEGIN
  3239. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3240. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3241. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3242. END
  3243. --Open file
  3244. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3245. IF @OLEResult <> 0
  3246. BEGIN
  3247. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3248. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3249. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3250. END
  3251. ELSE
  3252. BEGIN
  3253. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3254. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3255. END
  3256. --Write Text1
  3257. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3258. IF @OLEResult <> 0
  3259. BEGIN
  3260. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3261. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3262. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3263. END
  3264. EXEC @OLEResult = sp_OADestroy @FileID
  3265. EXEC @OLEResult = sp_OADestroy @FS
  3266. END
  3267. ELSE
  3268. BEGIN
  3269. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3270. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3271. END
  3272. RAISERROR (' |-Getting Disk(s) Fragmentation. This may take some time...', 10, 1) WITH NOWAIT
  3273. IF @psver = 1
  3274. BEGIN
  3275. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3276. END
  3277. ELSE
  3278. BEGIN
  3279. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3280. END;
  3281. INSERT INTO @output_hw_frag
  3282. EXEC master.dbo.xp_cmdshell @CMD
  3283. SET @CMD = 'del /Q "' + @FileName + '"'
  3284. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3285. IF (SELECT COUNT([PS_OUTPUT]) FROM @output_hw_frag WHERE [PS_OUTPUT] LIKE '%NotAdmin%') = 1
  3286. BEGIN
  3287. RAISERROR ('[WARNING: Powershell not running under Elevated Privileges. Bypassing Disk Fragmentation Analysis]',16,1);
  3288. END
  3289. ELSE
  3290. BEGIN
  3291. INSERT INTO @output_hw_format_frag ([volfrag],fragrec)
  3292. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3293. 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)
  3294. FROM @output_hw_frag
  3295. WHERE [PS_OUTPUT] IS NOT NULL
  3296. END
  3297. SET @CMD2 = 'del ' + @FileName
  3298. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3299. IF @xcmd = 0
  3300. BEGIN
  3301. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3302. END
  3303. IF @ole = 0
  3304. BEGIN
  3305. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3306. END
  3307. IF @sao = 0
  3308. BEGIN
  3309. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3310. END;
  3311. ;WITH fragcte (fragrec) AS (
  3312. SELECT fragrec
  3313. FROM @output_hw_format_frag
  3314. WHERE fragrec IS NOT NULL OR LEN(fragrec) > 0)
  3315. SELECT @frag = CASE WHEN (SELECT COUNT(*) FROM fragcte) = 0 THEN NULL ELSE COUNT(cte1.[fragrec]) END
  3316. FROM fragcte cte1
  3317. WHERE cte1.[fragrec] = 'True';
  3318. IF @frag > 0 AND @frag IS NOT NULL
  3319. BEGIN
  3320. 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]
  3321. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Information],
  3322. LEFT(t1.[volfrag],1) AS HD_Volume,
  3323. RIGHT(t1.[volfrag],(LEN(t1.[volfrag])-3)) AS [Fragmentation_Percent],
  3324. t1.fragrec AS [Defragmentation_Recommended]
  3325. FROM @output_hw_format_frag t1
  3326. WHERE t1.fragrec = 'True'
  3327. ORDER BY t1.[volfrag]
  3328. OPTION (RECOMPILE);
  3329. END
  3330. ELSE IF @frag IS NULL
  3331. BEGIN
  3332. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Check], '[WARNING: Could not gather information on Disk Fragmentation Analysis]' AS [Deviation]
  3333. END
  3334. ELSE
  3335. BEGIN
  3336. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Check], '[OK]' AS [Deviation]
  3337. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Information],
  3338. LEFT(t1.[volfrag],1) AS HD_Volume,
  3339. RIGHT(t1.[volfrag],(LEN(t1.[volfrag])-3)) AS [Fragmentation_Percent],
  3340. t1.fragrec AS [Defragmentation_Recommended]
  3341. FROM @output_hw_format_frag t1
  3342. ORDER BY t1.[volfrag]
  3343. OPTION (RECOMPILE);
  3344. END;
  3345. END
  3346. ELSE
  3347. BEGIN
  3348. 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')
  3349. 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')
  3350. --RETURN
  3351. END
  3352. END
  3353. ELSE
  3354. BEGIN
  3355. 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')
  3356. --RETURN
  3357. END
  3358. END
  3359. ELSE
  3360. BEGIN
  3361. RAISERROR(' |- [INFORMATION: "Disk Fragmentation Analysis" check is disabled]', 10, 1, N'disallow_diskfrag')
  3362. --RETURN
  3363. END;
  3364. --------------------------------------------------------------------------------------------------------------------------------
  3365. -- Cluster Quorum Model subsection
  3366. --------------------------------------------------------------------------------------------------------------------------------
  3367. IF @clustered = 1 AND @winver <> '5.2'
  3368. BEGIN
  3369. RAISERROR (N' |-Starting Cluster Quorum Model', 10, 1) WITH NOWAIT
  3370. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted')) AND @psver > 1
  3371. BEGIN
  3372. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3373. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3374. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  3375. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3376. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  3377. BEGIN
  3378. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3379. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3380. RAISERROR (' |-Configuration options set for Cluster Quorum Model check', 10, 1) WITH NOWAIT
  3381. IF @sao = 0
  3382. BEGIN
  3383. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3384. END
  3385. IF @xcmd = 0
  3386. BEGIN
  3387. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3388. END
  3389. DECLARE /*@CMD NVARCHAR(4000), @line int, @linemax int, */ @CntNodes tinyint, @CntVotes tinyint
  3390. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  3391. DROP TABLE #xp_cmdshell_CluNodesOutput;
  3392. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  3393. CREATE TABLE #xp_cmdshell_CluNodesOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(50));
  3394. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  3395. DROP TABLE #xp_cmdshell_CluOutput;
  3396. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  3397. CREATE TABLE #xp_cmdshell_CluOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(50));
  3398. IF @winver <> '5.2'
  3399. BEGIN
  3400. SELECT @CMD = N'powershell -NoLogo -NoProfile "Import-Module FailoverClusters"; "Get-ClusterNode | Format-Table -Autosize -HideTableHeaders NodeWeight"'
  3401. INSERT INTO #xp_cmdshell_CluNodesOutput ([Output])
  3402. EXEC master.dbo.xp_cmdshell @CMD;
  3403. END
  3404. SELECT @CMD = N'powershell -NoLogo -NoProfile "Import-Module FailoverClusters"; "Get-ClusterQuorum | Format-Table -Autosize -HideTableHeaders QuorumType"'
  3405. INSERT INTO #xp_cmdshell_CluOutput ([Output])
  3406. EXEC master.dbo.xp_cmdshell @CMD;
  3407. IF (SELECT COUNT([Output]) FROM #xp_cmdshell_CluNodesOutput WHERE [Output] = '') > 0
  3408. BEGIN
  3409. SELECT @CntNodes = COUNT(NodeName) FROM sys.dm_os_cluster_nodes (NOLOCK)
  3410. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check],
  3411. CASE WHEN REPLACE([Output], CHAR(9), '') = 'DiskOnly' AND @winver <> '5.2' THEN '[WARNING: The current quorum model is not recommended since WS2003]'
  3412. 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]'
  3413. 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]'
  3414. WHEN REPLACE([Output], CHAR(9), '') = 'NodeAndFileShareMajority' THEN '[INFORMATION: The current quorum model is recommended for clusters with special configurations]'
  3415. ELSE '[OK]' END AS [Deviation],
  3416. QUOTENAME(REPLACE([Output], CHAR(9), '')) AS QuorumModel,
  3417. '[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
  3418. FROM #xp_cmdshell_CluOutput WHERE [Output] IS NOT NULL
  3419. END
  3420. ELSE
  3421. BEGIN
  3422. SELECT @CntVotes = SUM(CONVERT(int, [Output])) FROM #xp_cmdshell_CluNodesOutput WHERE [Output] IS NOT NULL
  3423. IF EXISTS (SELECT TOP 1 [Output] FROM #xp_cmdshell_CluOutput WHERE [Output] LIKE '%Majority%' OR [Output] LIKE '%Disk%')
  3424. BEGIN
  3425. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check],
  3426. CASE WHEN REPLACE([Output], CHAR(9), '') = 'DiskOnly' AND @winver <> '5.2' THEN '[WARNING: The current quorum model is not recommended since WS2003]'
  3427. 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]'
  3428. 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]'
  3429. WHEN REPLACE([Output], CHAR(9), '') = 'NodeAndFileShareMajority' THEN '[INFORMATION: The current quorum model is recommended for clusters with special configurations]'
  3430. ELSE '[OK]' END AS [Deviation],
  3431. QUOTENAME(REPLACE([Output], CHAR(9), '')) AS QuorumModel
  3432. FROM #xp_cmdshell_CluOutput WHERE [Output] IS NOT NULL
  3433. END
  3434. END
  3435. IF @xcmd = 0
  3436. BEGIN
  3437. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3438. END
  3439. IF @sao = 0
  3440. BEGIN
  3441. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3442. END
  3443. END
  3444. ELSE
  3445. BEGIN
  3446. 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')
  3447. 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')
  3448. --RETURN
  3449. END
  3450. END
  3451. ELSE IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted')) AND @psver = 1
  3452. BEGIN
  3453. RAISERROR(' |- [INFORMATION: "Cluster Quorum Model" check was skipped: cannot execute with PS v1]', 10, 1, N'disallow_ps')
  3454. --RETURN
  3455. END
  3456. ELSE
  3457. BEGIN
  3458. 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')
  3459. --RETURN
  3460. END
  3461. END
  3462. ELSE
  3463. BEGIN
  3464. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3465. END;
  3466. IF @IsHadrEnabled = 1
  3467. BEGIN
  3468. SET @sqlcmd = N'DECLARE @winver VARCHAR(5), @CntNodes tinyint
  3469. SELECT @winver = windows_release FROM sys.dm_os_windows_info (NOLOCK)
  3470. SELECT @CntNodes = SUM(number_of_quorum_votes) FROM sys.dm_hadr_cluster_members (NOLOCK)
  3471. SELECT ''Server_checks'' AS [Category], ''AlwaysOn_Cluster_Quorum'' AS [Check], cluster_name,
  3472. CASE WHEN quorum_type = 3 AND @winver <> ''5.2'' THEN ''[WARNING: The current quorum model is not recommended since WS2003]''
  3473. 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]''
  3474. 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]''
  3475. WHEN quorum_type = 2 THEN ''[INFORMATION: The current quorum model is recommended for clusters with special configurations]''
  3476. ELSE ''[OK]'' END AS [Deviation],
  3477. QUOTENAME(quorum_type_desc) AS QuorumModel
  3478. FROM sys.dm_hadr_cluster;'
  3479. EXECUTE sp_executesql @sqlcmd
  3480. END;
  3481. --------------------------------------------------------------------------------------------------------------------------------
  3482. -- Cluster NIC Binding order subsection
  3483. --------------------------------------------------------------------------------------------------------------------------------
  3484. IF @allow_xpcmdshell = 1 and @clustered = 1
  3485. BEGIN
  3486. RAISERROR (N' |-Starting Cluster NIC Binding order', 10, 1) WITH NOWAIT
  3487. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  3488. BEGIN
  3489. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3490. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3491. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  3492. AND (SELECT COUNT(l.name)
  3493. FROM sys.server_permissions p JOIN sys.server_principals l
  3494. ON p.grantee_principal_id = l.principal_id
  3495. AND p.class = 100 -- Server
  3496. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  3497. AND l.is_disabled = 0
  3498. AND p.permission_name = 'ALTER SETTINGS'
  3499. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  3500. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3501. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  3502. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  3503. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  3504. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  3505. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  3506. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  3507. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  3508. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  3509. BEGIN
  3510. DECLARE @clunic int, @maxnic int
  3511. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3512. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3513. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  3514. RAISERROR (' |-Configuration options set for Cluster NIC Binding Order check', 10, 1) WITH NOWAIT
  3515. IF @sao = 0
  3516. BEGIN
  3517. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3518. END
  3519. IF @xcmd = 0
  3520. BEGIN
  3521. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3522. END
  3523. IF @ole = 0
  3524. BEGIN
  3525. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  3526. END
  3527. DECLARE @output_hw_nics TABLE ([PS_OUTPUT] VARCHAR(2048));
  3528. DECLARE @output_hw_format_nics TABLE ([nicid] smallint, [nicname] VARCHAR(255) NULL)
  3529. IF @custompath IS NULL
  3530. BEGIN
  3531. IF @sqlmajorver < 11
  3532. BEGIN
  3533. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  3534. SET @path = @path + '\LOG'
  3535. END
  3536. ELSE
  3537. BEGIN
  3538. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  3539. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  3540. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  3541. END
  3542. -- Create COM object with FSO
  3543. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  3544. IF @OLEResult <> 0
  3545. BEGIN
  3546. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3547. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3548. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3549. END
  3550. ELSE
  3551. BEGIN
  3552. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  3553. IF @OLEResult <> 0
  3554. BEGIN
  3555. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3556. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  3557. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3558. END
  3559. ELSE
  3560. BEGIN
  3561. IF @existout <> 1
  3562. BEGIN
  3563. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  3564. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  3565. END
  3566. END
  3567. EXEC @OLEResult = sp_OADestroy @FSO
  3568. END
  3569. END
  3570. ELSE
  3571. BEGIN
  3572. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  3573. END
  3574. SET @FileName = @path + '\checkbp_nics_' + RTRIM(@server) + '.ps1'
  3575. EXEC master.dbo.xp_fileexist @FileName, @existout out
  3576. IF @existout = 0
  3577. BEGIN -- Scan for nics
  3578. SET @Text1 = '[string] $serverName = ''localhost''
  3579. $nics = Get-WmiObject -Computername $serverName -query "SELECT Description, Index FROM Win32_NetworkAdapterConfiguration"
  3580. foreach ($nic in $nics)
  3581. {
  3582. [string] $allnics = "{0};{1}" -f $nic.Index,$nic.Description
  3583. Write-Output $allnics
  3584. }
  3585. '
  3586. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3587. IF @OLEResult <> 0
  3588. BEGIN
  3589. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3590. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3591. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3592. END
  3593. --Open file
  3594. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3595. IF @OLEResult <> 0
  3596. BEGIN
  3597. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3598. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3599. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3600. END
  3601. ELSE
  3602. BEGIN
  3603. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3604. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3605. END
  3606. --Write Text1
  3607. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3608. IF @OLEResult <> 0
  3609. BEGIN
  3610. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3611. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3612. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3613. END
  3614. EXEC @OLEResult = sp_OADestroy @FileID
  3615. EXEC @OLEResult = sp_OADestroy @FS
  3616. END
  3617. ELSE
  3618. BEGIN
  3619. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3620. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3621. END
  3622. IF @psver = 1
  3623. BEGIN
  3624. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3625. END
  3626. ELSE
  3627. BEGIN
  3628. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3629. END;
  3630. INSERT INTO @output_hw_nics
  3631. EXEC master.dbo.xp_cmdshell @CMD
  3632. SET @CMD = 'del /Q "' + @FileName + '"'
  3633. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3634. INSERT INTO @output_hw_format_nics ([nicid],nicname)
  3635. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3636. 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)
  3637. FROM @output_hw_nics
  3638. WHERE [PS_OUTPUT] IS NOT NULL;
  3639. SET @CMD2 = 'del ' + @FileName
  3640. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3641. IF @xcmd = 0
  3642. BEGIN
  3643. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3644. END
  3645. IF @ole = 0
  3646. BEGIN
  3647. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3648. END
  3649. IF @sao = 0
  3650. BEGIN
  3651. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3652. END;
  3653. SELECT @maxnic = MAX(nicid) FROM @output_hw_format_nics;
  3654. SELECT TOP 1 @clunic = nicid FROM @output_hw_format_nics WHERE nicname LIKE '%Cluster Virtual Adapter%';
  3655. IF @clunic < @maxnic OR @clunic IS NULL --http://support2.microsoft.com/kb/955963
  3656. BEGIN
  3657. 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]
  3658. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Information], nicid AS NIC_ID, nicname AS NIC_Name
  3659. FROM @output_hw_format_nics t1
  3660. ORDER BY t1.[nicid]
  3661. OPTION (RECOMPILE);
  3662. END
  3663. ELSE IF @clunic = @maxnic
  3664. BEGIN
  3665. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], '[OK]' AS [Deviation]
  3666. END
  3667. ELSE
  3668. BEGIN
  3669. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], '[WARNING: Could not gather information on NIC binding order]' AS [Deviation]
  3670. END;
  3671. END
  3672. ELSE
  3673. BEGIN
  3674. 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')
  3675. 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')
  3676. --RETURN
  3677. END
  3678. END
  3679. ELSE
  3680. BEGIN
  3681. 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')
  3682. --RETURN
  3683. END
  3684. END
  3685. ELSE
  3686. BEGIN
  3687. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3688. END;
  3689. --------------------------------------------------------------------------------------------------------------------------------
  3690. -- Cluster QFE node equality subsection
  3691. --------------------------------------------------------------------------------------------------------------------------------
  3692. IF @clustered = 1
  3693. BEGIN
  3694. RAISERROR (N' |-Starting QFE node equality', 10, 1) WITH NOWAIT
  3695. IF @allow_xpcmdshell = 1
  3696. BEGIN
  3697. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3698. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3699. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  3700. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3701. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  3702. BEGIN
  3703. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3704. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3705. RAISERROR (' |-Configuration options set for QFE node equality check', 10, 1) WITH NOWAIT
  3706. IF @sao = 0
  3707. BEGIN
  3708. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3709. END
  3710. IF @xcmd = 0
  3711. BEGIN
  3712. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3713. END
  3714. DECLARE /* @CMD NVARCHAR(4000), @line int, @linemax int, */ @Node VARCHAR(50)
  3715. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  3716. DROP TABLE #xp_cmdshell_Nodes;
  3717. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  3718. CREATE TABLE #xp_cmdshell_Nodes (NodeName VARCHAR(50), isdone bit NOT NULL);
  3719. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  3720. DROP TABLE #xp_cmdshell_QFEOutput;
  3721. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  3722. CREATE TABLE #xp_cmdshell_QFEOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(150));
  3723. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  3724. DROP TABLE #xp_cmdshell_QFEFinal;
  3725. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  3726. CREATE TABLE #xp_cmdshell_QFEFinal (NodeName VARCHAR(50), [QFE] VARCHAR(150));
  3727. INSERT INTO #xp_cmdshell_Nodes
  3728. SELECT NodeName, 0 FROM sys.dm_os_cluster_nodes (NOLOCK);
  3729. WHILE (SELECT COUNT(NodeName) FROM #xp_cmdshell_Nodes WHERE isdone = 0) > 0
  3730. BEGIN
  3731. SELECT TOP 1 @Node = NodeName FROM #xp_cmdshell_Nodes WHERE isdone = 0;
  3732. SET @CMD = 'wmic /node:"' + @Node + '" qfe get hotfixid'
  3733. INSERT INTO #xp_cmdshell_QFEOutput ([Output])
  3734. EXEC master.dbo.xp_cmdshell @CMD;
  3735. IF (SELECT COUNT([Output]) FROM #xp_cmdshell_QFEOutput WHERE [Output] LIKE '%Access is denied%') = 0
  3736. BEGIN
  3737. INSERT INTO #xp_cmdshell_QFEFinal
  3738. SELECT @Node, RTRIM(REPLACE([Output],CHAR(13),'')) FROM #xp_cmdshell_QFEOutput WHERE RTRIM(REPLACE([Output],CHAR(13),'')) NOT IN ('','HotFixID');
  3739. END
  3740. ELSE
  3741. BEGIN
  3742. SET @ErrorMessage = '[WARNING: Access Denied error while trying to get updates from node ' + @Node + ']'
  3743. RAISERROR (@ErrorMessage,16,1);
  3744. END;
  3745. TRUNCATE TABLE #xp_cmdshell_QFEOutput;
  3746. UPDATE #xp_cmdshell_Nodes
  3747. SET isdone = 1
  3748. WHERE NodeName = @Node;
  3749. END;
  3750. IF (SELECT COUNT(DISTINCT NodeName) FROM #xp_cmdshell_QFEFinal) = (SELECT COUNT(DISTINCT NodeName) FROM #xp_cmdshell_Nodes)
  3751. BEGIN
  3752. 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
  3753. BEGIN
  3754. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], '[WARNING: Missing updates found in some of the nodes]' AS [Deviation]
  3755. SELECT t1.NodeName, t1.[QFE] AS MissingUpdates FROM #xp_cmdshell_QFEFinal t1
  3756. WHERE t1.[QFE] NOT IN (SELECT DISTINCT t2.[QFE] FROM #xp_cmdshell_QFEFinal t2 WHERE t2.NodeName <> t1.NodeName);
  3757. END
  3758. ELSE
  3759. BEGIN
  3760. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], '[OK]' AS [Deviation];
  3761. SELECT DISTINCT t1.[QFE] AS InstalledUpdates FROM #xp_cmdshell_QFEFinal t1;
  3762. END
  3763. END
  3764. ELSE
  3765. BEGIN
  3766. RAISERROR ('[WARNING: Could not collect data from all cluster nodes. Bypassing QFE node equality check]',16,1);
  3767. END
  3768. IF @xcmd = 0
  3769. BEGIN
  3770. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3771. END
  3772. IF @sao = 0
  3773. BEGIN
  3774. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3775. END
  3776. END
  3777. ELSE
  3778. BEGIN
  3779. 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')
  3780. 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')
  3781. --RETURN
  3782. END
  3783. END
  3784. ELSE
  3785. BEGIN
  3786. RAISERROR(' |- [INFORMATION: "QFE node equality" check was skipped because xp_cmdshell was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  3787. --RETURN
  3788. END
  3789. END
  3790. ELSE
  3791. BEGIN
  3792. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3793. END;
  3794. RAISERROR (N'|-Starting Service Accounts Checks', 10, 1) WITH NOWAIT
  3795. --------------------------------------------------------------------------------------------------------------------------------
  3796. -- Service Accounts Status subsection
  3797. --------------------------------------------------------------------------------------------------------------------------------
  3798. RAISERROR (N' |-Starting Service Accounts Status', 10, 1) WITH NOWAIT
  3799. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1)
  3800. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1 AND
  3801. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_servicecontrol') = 1)
  3802. BEGIN
  3803. DECLARE @rc int, @profile NVARCHAR(128)
  3804. DECLARE @sqlservice NVARCHAR(128), @sqlagentservice NVARCHAR(128), @dtsservice NVARCHAR(128), @ftservice NVARCHAR(128)
  3805. DECLARE @browservice NVARCHAR(128), @olapservice NVARCHAR(128), @rsservice NVARCHAR(128)
  3806. DECLARE @statussqlservice NVARCHAR(20), @statussqlagentservice NVARCHAR(20), @statusdtsservice NVARCHAR(20), @statusftservice NVARCHAR(20)
  3807. DECLARE @statusbrowservice NVARCHAR(20), @statusolapservice NVARCHAR(20), @statusrsservice NVARCHAR(20)
  3808. DECLARE @regkeysqlservice NVARCHAR(256), @regkeysqlagentservice NVARCHAR(256), @regkeydtsservice NVARCHAR(256), @regkeyftservice NVARCHAR(256)
  3809. DECLARE @regkeybrowservice NVARCHAR(256), @regkeyolapservice NVARCHAR(256), @regkeyrsservice NVARCHAR(256)
  3810. DECLARE @accntsqlservice NVARCHAR(128), @accntsqlagentservice NVARCHAR(128), @accntdtsservice NVARCHAR(128), @accntftservice NVARCHAR(128)
  3811. DECLARE @accntbrowservice NVARCHAR(128), @accntolapservice NVARCHAR(128), @accntrsservice NVARCHAR(128)
  3812. -- Get service names
  3813. IF (@instancename IS NULL)
  3814. BEGIN
  3815. IF @sqlmajorver < 11
  3816. BEGIN
  3817. SELECT @sqlservice = N'MSSQLServer'
  3818. SELECT @sqlagentservice = N'SQLServerAgent'
  3819. END
  3820. SELECT @olapservice = N'MSSQLServerOLAPService'
  3821. SELECT @rsservice = N'ReportServer'
  3822. END
  3823. ELSE
  3824. BEGIN
  3825. IF @sqlmajorver < 11
  3826. BEGIN
  3827. SELECT @sqlservice = N'MSSQL$' + @instancename
  3828. SELECT @sqlagentservice = N'SQLAgent$' + @instancename
  3829. END
  3830. SELECT @olapservice = N'MSOLAP$' + @instancename
  3831. SELECT @rsservice = N'ReportServer$' + @instancename
  3832. END
  3833. IF @sqlmajorver = 9
  3834. BEGIN
  3835. SELECT @dtsservice = N'MsDtsServer'
  3836. END
  3837. ELSE
  3838. BEGIN
  3839. SELECT @dtsservice = N'MsDtsServer' + CONVERT(VARCHAR, @sqlmajorver) + '0'
  3840. END
  3841. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3842. BEGIN
  3843. IF (@instancename IS NULL) AND @sqlmajorver = 10
  3844. BEGIN
  3845. SELECT @ftservice = N'MSSQLFDLauncher'
  3846. END
  3847. ELSE IF (@instancename IS NOT NULL) AND @sqlmajorver = 10
  3848. BEGIN
  3849. SELECT @ftservice = N'MSSQLFDLauncher$' + @instancename
  3850. END
  3851. ELSE IF (@instancename IS NULL) AND @sqlmajorver = 9
  3852. BEGIN
  3853. SELECT @ftservice = N'msftesql'
  3854. END
  3855. ELSE IF (@instancename IS NOT NULL) AND @sqlmajorver = 9
  3856. BEGIN
  3857. SELECT @ftservice = N'msftesql$' + @instancename
  3858. END
  3859. END
  3860. SELECT @browservice = N'SQLBrowser'
  3861. IF @sqlmajorver < 11
  3862. BEGIN
  3863. SELECT @regkeysqlservice = N'SYSTEM\CurrentControlSet\Services\' + @sqlservice
  3864. SELECT @regkeysqlagentservice = N'SYSTEM\CurrentControlSet\Services\' + @sqlagentservice
  3865. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3866. BEGIN
  3867. SELECT @regkeyftservice = N'SYSTEM\CurrentControlSet\Services\' + @ftservice
  3868. END
  3869. END
  3870. SELECT @regkeyolapservice = N'SYSTEM\CurrentControlSet\Services\' + @olapservice
  3871. SELECT @regkeyrsservice = N'SYSTEM\CurrentControlSet\Services\' + @rsservice
  3872. SELECT @regkeydtsservice = N'SYSTEM\CurrentControlSet\Services\' + @dtsservice
  3873. SELECT @regkeybrowservice = N'SYSTEM\CurrentControlSet\Services\' + @browservice
  3874. -- Service status
  3875. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#RegResult'))
  3876. CREATE TABLE #RegResult (ResultValue bit)
  3877. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ServiceStatus'))
  3878. CREATE TABLE #ServiceStatus (ServiceStatus VARCHAR(128))
  3879. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3880. BEGIN
  3881. BEGIN TRY
  3882. INSERT INTO #RegResult (ResultValue)
  3883. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlservice
  3884. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3885. BEGIN
  3886. INSERT INTO #ServiceStatus (ServiceStatus)
  3887. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @sqlservice
  3888. SELECT @statussqlservice = ServiceStatus FROM #ServiceStatus
  3889. TRUNCATE TABLE #ServiceStatus;
  3890. END
  3891. ELSE
  3892. BEGIN
  3893. SET @statussqlservice = 'Not Installed'
  3894. END
  3895. TRUNCATE TABLE #RegResult;
  3896. END TRY
  3897. BEGIN CATCH
  3898. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3899. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  3900. RAISERROR (@ErrorMessage, 16, 1);
  3901. END CATCH
  3902. END
  3903. ELSE
  3904. BEGIN
  3905. SET @sqlcmd = N'SELECT @statussqlserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server%'' AND servicename NOT LIKE ''SQL Server Agent%''';
  3906. SET @params = N'@statussqlserviceOUT NVARCHAR(20) OUTPUT';
  3907. EXECUTE sp_executesql @sqlcmd, @params, @statussqlserviceOUT=@statussqlservice OUTPUT;
  3908. IF @statussqlservice IS NULL
  3909. BEGIN
  3910. SET @statussqlservice = 'Not Installed'
  3911. END
  3912. END
  3913. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3914. BEGIN
  3915. BEGIN TRY
  3916. INSERT INTO #RegResult (ResultValue)
  3917. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlagentservice
  3918. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3919. BEGIN
  3920. INSERT INTO #ServiceStatus (ServiceStatus)
  3921. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @sqlagentservice
  3922. SELECT @statussqlagentservice = ServiceStatus FROM #ServiceStatus
  3923. TRUNCATE TABLE #ServiceStatus;
  3924. END
  3925. ELSE
  3926. BEGIN
  3927. SET @statussqlagentservice = 'Not Installed'
  3928. END
  3929. TRUNCATE TABLE #RegResult;
  3930. END TRY
  3931. BEGIN CATCH
  3932. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3933. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  3934. RAISERROR (@ErrorMessage, 16, 1);
  3935. END CATCH
  3936. END
  3937. ELSE
  3938. BEGIN
  3939. SET @sqlcmd = N'SELECT @statussqlagentserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server Agent%''';
  3940. SET @params = N'@statussqlagentserviceOUT NVARCHAR(20) OUTPUT';
  3941. EXECUTE sp_executesql @sqlcmd, @params, @statussqlagentserviceOUT=@statussqlagentservice OUTPUT;
  3942. IF @statussqlagentservice IS NULL
  3943. BEGIN
  3944. SET @statussqlagentservice = 'Not Installed'
  3945. END
  3946. END
  3947. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3948. BEGIN
  3949. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3950. BEGIN
  3951. BEGIN TRY
  3952. INSERT INTO #RegResult (ResultValue)
  3953. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyftservice
  3954. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3955. BEGIN
  3956. INSERT INTO #ServiceStatus (ServiceStatus)
  3957. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @ftservice
  3958. SELECT @statusftservice = ServiceStatus FROM #ServiceStatus
  3959. TRUNCATE TABLE #ServiceStatus;
  3960. END
  3961. ELSE
  3962. BEGIN
  3963. SET @statusftservice = '[INFORMATION: Service is not installed]'
  3964. END
  3965. TRUNCATE TABLE #RegResult;
  3966. END TRY
  3967. BEGIN CATCH
  3968. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3969. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  3970. RAISERROR (@ErrorMessage, 16, 1);
  3971. END CATCH
  3972. END
  3973. END
  3974. ELSE
  3975. BEGIN
  3976. SET @sqlcmd = N'SELECT @statusftserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Full-text Filter Daemon Launcher%''';
  3977. SET @params = N'@statusftserviceOUT NVARCHAR(20) OUTPUT';
  3978. EXECUTE sp_executesql @sqlcmd, @params, @statusftserviceOUT=@statusftservice OUTPUT;
  3979. IF @statusftservice IS NULL
  3980. BEGIN
  3981. SET @statusftservice = '[INFORMATION: Service is not installed]'
  3982. END
  3983. END
  3984. BEGIN TRY
  3985. INSERT INTO #RegResult (ResultValue)
  3986. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyolapservice
  3987. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3988. BEGIN
  3989. INSERT INTO #ServiceStatus (ServiceStatus)
  3990. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @olapservice
  3991. SELECT @statusolapservice = ServiceStatus FROM #ServiceStatus
  3992. TRUNCATE TABLE #ServiceStatus;
  3993. END
  3994. ELSE
  3995. BEGIN
  3996. SET @statusolapservice = 'Not Installed'
  3997. END
  3998. TRUNCATE TABLE #RegResult;
  3999. END TRY
  4000. BEGIN CATCH
  4001. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4002. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 4. ' + ERROR_MESSAGE()
  4003. RAISERROR (@ErrorMessage, 16, 1);
  4004. END CATCH
  4005. BEGIN TRY
  4006. INSERT INTO #RegResult (ResultValue)
  4007. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyrsservice
  4008. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4009. BEGIN
  4010. INSERT INTO #ServiceStatus (ServiceStatus)
  4011. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @rsservice
  4012. SELECT @statusrsservice = ServiceStatus FROM #ServiceStatus
  4013. TRUNCATE TABLE #ServiceStatus;
  4014. END
  4015. ELSE
  4016. BEGIN
  4017. SET @statusrsservice = 'Not Installed'
  4018. END
  4019. TRUNCATE TABLE #RegResult;
  4020. END TRY
  4021. BEGIN CATCH
  4022. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4023. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 5. ' + ERROR_MESSAGE()
  4024. RAISERROR (@ErrorMessage, 16, 1);
  4025. END CATCH
  4026. BEGIN TRY
  4027. INSERT INTO #RegResult (ResultValue)
  4028. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeydtsservice
  4029. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4030. BEGIN
  4031. INSERT INTO #ServiceStatus (ServiceStatus)
  4032. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @dtsservice
  4033. SELECT @statusdtsservice = ServiceStatus FROM #ServiceStatus
  4034. TRUNCATE TABLE #ServiceStatus;
  4035. END
  4036. ELSE
  4037. BEGIN
  4038. SET @statusdtsservice = 'Not Installed'
  4039. END
  4040. TRUNCATE TABLE #RegResult;
  4041. END TRY
  4042. BEGIN CATCH
  4043. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4044. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 6. ' + ERROR_MESSAGE()
  4045. RAISERROR (@ErrorMessage, 16, 1);
  4046. END CATCH
  4047. BEGIN TRY
  4048. INSERT INTO #RegResult (ResultValue)
  4049. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeybrowservice
  4050. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4051. BEGIN
  4052. INSERT INTO #ServiceStatus (ServiceStatus)
  4053. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @browservice
  4054. SELECT @statusbrowservice = ServiceStatus FROM #ServiceStatus
  4055. TRUNCATE TABLE #ServiceStatus;
  4056. END
  4057. ELSE
  4058. BEGIN
  4059. SET @statusbrowservice = 'Not Installed'
  4060. END
  4061. END TRY
  4062. BEGIN CATCH
  4063. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4064. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 7. ' + ERROR_MESSAGE()
  4065. RAISERROR (@ErrorMessage, 16, 1);
  4066. END CATCH
  4067. DROP TABLE #RegResult;
  4068. DROP TABLE #ServiceStatus;
  4069. -- Accounts
  4070. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  4071. BEGIN
  4072. BEGIN TRY
  4073. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlservice, N'ObjectName', @accntsqlservice OUTPUT, NO_OUTPUT
  4074. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlagentservice, N'ObjectName', @accntsqlagentservice OUTPUT, NO_OUTPUT
  4075. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyftservice, N'ObjectName', @accntftservice OUTPUT, NO_OUTPUT
  4076. END TRY
  4077. BEGIN CATCH
  4078. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4079. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 8. ' + ERROR_MESSAGE()
  4080. RAISERROR (@ErrorMessage, 16, 1);
  4081. END CATCH
  4082. END
  4083. ELSE
  4084. BEGIN
  4085. BEGIN TRY
  4086. SET @sqlcmd = N'SELECT @accntsqlserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server%'' AND servicename NOT LIKE ''SQL Server Agent%''';
  4087. SET @params = N'@accntsqlserviceOUT NVARCHAR(128) OUTPUT';
  4088. EXECUTE sp_executesql @sqlcmd, @params, @accntsqlserviceOUT=@accntsqlservice OUTPUT;
  4089. SET @sqlcmd = N'SELECT @accntsqlagentserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server Agent%''';
  4090. SET @params = N'@accntsqlagentserviceOUT NVARCHAR(128) OUTPUT';
  4091. EXECUTE sp_executesql @sqlcmd, @params, @accntsqlagentserviceOUT=@accntsqlagentservice OUTPUT;
  4092. SET @sqlcmd = N'SELECT @accntftserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Full-text Filter Daemon Launcher%''';
  4093. SET @params = N'@accntftserviceOUT NVARCHAR(128) OUTPUT';
  4094. EXECUTE sp_executesql @sqlcmd, @params, @accntftserviceOUT=@accntftservice OUTPUT;
  4095. END TRY
  4096. BEGIN CATCH
  4097. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4098. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 9. ' + ERROR_MESSAGE()
  4099. RAISERROR (@ErrorMessage, 16, 1);
  4100. END CATCH
  4101. END
  4102. BEGIN TRY
  4103. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyolapservice, N'ObjectName', @accntolapservice OUTPUT, NO_OUTPUT
  4104. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyrsservice, N'ObjectName', @accntrsservice OUTPUT, NO_OUTPUT
  4105. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeydtsservice, N'ObjectName', @accntdtsservice OUTPUT, NO_OUTPUT
  4106. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeybrowservice, N'ObjectName', @accntbrowservice OUTPUT, NO_OUTPUT
  4107. END TRY
  4108. BEGIN CATCH
  4109. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4110. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 10. ' + ERROR_MESSAGE()
  4111. RAISERROR (@ErrorMessage, 16, 1);
  4112. END CATCH
  4113. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server' AS [Service], @statussqlservice AS [Status], @accntsqlservice AS [Account],
  4114. CASE WHEN @statussqlservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4115. WHEN @statussqlservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4116. WHEN @accntsqlservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4117. WHEN @accntsqlservice = 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4118. WHEN @clustered = 1 AND @accntsqlservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4119. WHEN @clustered = 1 AND @accntsqlservice = 'LocalSystem' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4120. WHEN @clustered = 1 AND @accntsqlservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4121. WHEN @clustered = 0 AND @accntsqlservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4122. WHEN @clustered = 0 AND @accntsqlservice = 'LocalSystem' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4123. WHEN @clustered = 0 AND @accntsqlservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4124. -- 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)
  4125. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntsqlservice <> 'NT SERVICE\MSSQLSERVER' AND @accntsqlservice NOT LIKE 'NT SERVICE\MSSQL$%' THEN '[INFORMATION: SQL Server is not running with the default account]'
  4126. ELSE '[OK]'
  4127. END AS [Deviation]
  4128. UNION ALL
  4129. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Agent' AS [Service], @statussqlagentservice AS [Status], @accntsqlagentservice AS [Account],
  4130. CASE WHEN @statussqlagentservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4131. WHEN @statussqlagentservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4132. WHEN @accntsqlagentservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4133. WHEN @accntsqlagentservice = 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4134. WHEN @accntsqlagentservice = @accntsqlservice THEN '[WARNING: Running SQL Server Agent under the same account as SQL Server is not recommended]'
  4135. WHEN @clustered = 1 AND @accntsqlagentservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4136. WHEN @clustered = 1 AND @accntsqlagentservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4137. WHEN @clustered = 0 AND @accntsqlagentservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server Agent under this account is not recommended]'
  4138. WHEN @clustered = 0 AND @accntsqlagentservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not recommended]'
  4139. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4140. -- 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)
  4141. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntsqlagentservice <> 'NT SERVICE\SQLSERVERAGENT' AND @accntsqlagentservice NOT LIKE 'NT SERVICE\SQLAGENT$%' THEN '[INFORMATION: SQL Server Agent is not running with the default account]'
  4142. ELSE '[OK]'
  4143. END AS [Deviation]
  4144. UNION ALL
  4145. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Analysis_Services' AS [Service], @statusolapservice AS [Status], @accntolapservice AS [Account],
  4146. CASE WHEN @statusolapservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4147. WHEN @statusolapservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4148. WHEN @accntolapservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4149. WHEN @accntolapservice = @accntsqlservice THEN '[WARNING: Running SQL Server Analysis Services under the same account as SQL Server is not recommended]'
  4150. 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]'
  4151. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4152. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND @winver <= 6.0 AND @accntolapservice <> 'NT AUTHORITY\NETWORKSERVICE' THEN '[INFORMATION: SQL Server Analysis Services is not running with the default account]'
  4153. -- 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)
  4154. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntolapservice <> 'NT SERVICE\MSSQLServerOLAPService' AND @accntolapservice NOT LIKE 'NT SERVICE\MSOLAP$%' THEN '[INFORMATION: SQL Server Analysis Services is not running with the default account]'
  4155. ELSE '[OK]'
  4156. END AS [Deviation]
  4157. UNION ALL
  4158. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Integration_Services' AS [Service], @statusdtsservice AS [Status], @accntdtsservice AS [Account],
  4159. CASE WHEN @statusdtsservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4160. WHEN @statusdtsservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4161. WHEN @accntdtsservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4162. WHEN @accntdtsservice = @accntsqlservice THEN '[WARNING: Running SQL Server Integration Services under the same account as SQL Server is not recommended]'
  4163. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4164. WHEN @winver <= 6.0 AND @accntdtsservice <> 'NT AUTHORITY\NETWORKSERVICE' AND @accntdtsservice <> 'NT AUTHORITY\LOCALSYSTEM' THEN '[INFORMATION: SQL Server Integration Services is not running with the default account]'
  4165. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4166. WHEN @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntdtsservice NOT IN ('NT SERVICE\MSDTSSERVER100', 'NT SERVICE\MSDTSSERVER110') THEN '[INFORMATION: SQL Server Integration Services is not running with the default account]'
  4167. ELSE '[OK]'
  4168. END AS [Deviation]
  4169. UNION ALL
  4170. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Reporting_Services' AS [Service], @statusrsservice AS [Status], @accntrsservice AS [Account],
  4171. CASE WHEN @statusrsservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4172. WHEN @statusrsservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4173. WHEN @accntrsservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4174. WHEN @accntrsservice = @accntsqlservice THEN '[WARNING: Running SQL Server Reporting Services under the same account as SQL Server is not recommended]'
  4175. 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]'
  4176. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4177. WHEN @sqlmajorver >= 11 AND @winver <= 6.0 AND @accntrsservice <> 'NT AUTHORITY\NETWORKSERVICE' THEN '[INFORMATION: SQL Server Reporting Services is not running with the default account]'
  4178. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4179. WHEN @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntrsservice <> 'NT SERVICE\ReportServer' AND @accntrsservice NOT LIKE 'NT SERVICE\ReportServer$%' THEN '[INFORMATION: SQL Server Reporting Services is not running with the default account]'
  4180. ELSE '[OK]'
  4181. END AS [Deviation]
  4182. UNION ALL
  4183. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'Full-Text' AS [Service], ISNULL(@statusftservice, 'Not Installed') AS [Status], ISNULL(@accntftservice,'') AS [Account],
  4184. CASE WHEN (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1 THEN
  4185. CASE WHEN @statusftservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4186. WHEN @statusftservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4187. WHEN @accntftservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4188. WHEN @accntftservice = @accntsqlservice THEN '[WARNING: Running Full-Text Daemon under the same account as SQL Server is not recommended]'
  4189. WHEN @accntftservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running Full-Text Service under this account is not recommended]'
  4190. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4191. WHEN @sqlmajorver <= 10 AND @accntftservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running Full-Text Service under this account is not recommended]'
  4192. WHEN @sqlmajorver <= 10 AND @accntftservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4193. WHEN @sqlmajorver >= 11 AND @winver <= 6.0 AND @accntftservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4194. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4195. WHEN @sqlmajorver >= 11 AND CONVERT(float, @winver) >= 6.1 AND @accntftservice <> 'NT SERVICE\MSSQLFDLauncher' AND @accntftservice NOT LIKE 'NT SERVICE\MSSQLFDLauncher$%' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4196. ELSE '[OK]' END
  4197. ELSE '[INFORMATION: Service is not installed]'
  4198. END AS [Deviation]
  4199. UNION ALL
  4200. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Browser' AS [Service], @statusbrowservice AS [Status], @accntbrowservice AS [Account],
  4201. CASE WHEN @statusbrowservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4202. WHEN @statusbrowservice LIKE 'Stopped%' AND @instancename IS NOT NULL THEN '[WARNING: Service is stopped on a named instance]'
  4203. WHEN @statusbrowservice LIKE 'Stopped%' AND @instancename IS NULL THEN '[WARNING: Service is stopped]'
  4204. WHEN @accntbrowservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4205. WHEN @accntbrowservice = @accntsqlservice THEN '[WARNING: Running SQL Server Browser under the same account as SQL Server is not recommended]'
  4206. WHEN @accntbrowservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: SQL Server Browser is not running with the default account]'
  4207. ELSE '[OK]'
  4208. END AS [Deviation];
  4209. END
  4210. ELSE
  4211. BEGIN
  4212. 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')
  4213. --RETURN
  4214. END;
  4215. --------------------------------------------------------------------------------------------------------------------------------
  4216. -- Service Accounts and SPN registration subsection
  4217. --------------------------------------------------------------------------------------------------------------------------------
  4218. RAISERROR (N' |-Starting Service Accounts and SPN registration', 10, 1) WITH NOWAIT
  4219. 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
  4220. BEGIN
  4221. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  4222. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  4223. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  4224. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  4225. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  4226. BEGIN
  4227. RAISERROR (' |-Configuration options set for SPN check', 10, 1) WITH NOWAIT
  4228. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  4229. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  4230. IF @sao = 0
  4231. BEGIN
  4232. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  4233. END
  4234. IF @xcmd = 0
  4235. BEGIN
  4236. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  4237. END
  4238. BEGIN TRY
  4239. DECLARE /*@CMD NVARCHAR(4000),*/ @line int, @linemax int, @SPN VARCHAR(8000), @SPNMachine VARCHAR(8000)
  4240. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  4241. DROP TABLE #xp_cmdshell_AcctSPNoutput;
  4242. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  4243. CREATE TABLE #xp_cmdshell_AcctSPNoutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR (8000));
  4244. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  4245. DROP TABLE #xp_cmdshell_DupSPNoutput;
  4246. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  4247. CREATE TABLE #xp_cmdshell_DupSPNoutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR (8000));
  4248. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  4249. DROP TABLE #FinalDupSPN;
  4250. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  4251. CREATE TABLE #FinalDupSPN ([SPN] VARCHAR (8000), [Accounts] VARCHAR (8000));
  4252. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  4253. DROP TABLE #ScopedDupSPN;
  4254. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  4255. CREATE TABLE #ScopedDupSPN ([SPN] VARCHAR (8000), [Accounts] VARCHAR (8000));
  4256. SELECT @CMD = N'SETSPN -P -L ' + @accntsqlservice
  4257. INSERT INTO #xp_cmdshell_AcctSPNoutput ([Output])
  4258. EXEC master.dbo.xp_cmdshell @CMD;
  4259. SET @CMD = N'SETSPN -P -X'
  4260. INSERT INTO #xp_cmdshell_DupSPNoutput ([Output])
  4261. EXEC master.dbo.xp_cmdshell @CMD;
  4262. SELECT @SPNMachine = '%MSSQLSvc/' + CONVERT(NVARCHAR(100),SERVERPROPERTY('MachineName')) + '%';
  4263. 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]),' ', ''))))
  4264. BEGIN
  4265. 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%'
  4266. OPEN curSPN
  4267. FETCH NEXT FROM curSPN INTO @line, @SPN
  4268. WHILE @@FETCH_STATUS = 0
  4269. BEGIN
  4270. SELECT TOP 1 @linemax = line FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND [Output] IS NULL;
  4271. INSERT INTO #FinalDupSPN
  4272. SELECT QUOTENAME(@SPN), QUOTENAME(REPLACE([Output], CHAR(9), '')) FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND line < @linemax;
  4273. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_DupSPNoutput WHERE line = @line AND [Output] LIKE @SPNMachine)
  4274. BEGIN
  4275. INSERT INTO #ScopedDupSPN
  4276. SELECT QUOTENAME(@SPN), QUOTENAME(REPLACE([Output], CHAR(9), '')) FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND line < @linemax;
  4277. END
  4278. FETCH NEXT FROM curSPN INTO @line, @SPN
  4279. END
  4280. CLOSE curSPN
  4281. DEALLOCATE curSPN
  4282. END
  4283. IF EXISTS (SELECT TOP 1 [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%')
  4284. BEGIN
  4285. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%' AND [Output] LIKE @SPNMachine)
  4286. BEGIN
  4287. 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
  4288. END
  4289. ELSE
  4290. BEGIN
  4291. 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];
  4292. END
  4293. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%' AND [Output] NOT LIKE @SPNMachine)
  4294. BEGIN
  4295. 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
  4296. END
  4297. END
  4298. ELSE
  4299. BEGIN
  4300. 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];
  4301. END
  4302. IF (SELECT COUNT(*) FROM #ScopedDupSPN) > 0
  4303. BEGIN
  4304. 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
  4305. END
  4306. ELSE
  4307. BEGIN
  4308. SELECT 'Service_Account_checks' AS [Category], 'Dup_MSSQLSvc_SPNs_Acct_CurrServer' AS [Check], '[OK]' AS [Deviation];
  4309. END
  4310. IF (SELECT COUNT(*) FROM #FinalDupSPN) > 0
  4311. BEGIN
  4312. 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
  4313. END
  4314. ELSE
  4315. BEGIN
  4316. SELECT 'Service_Account_checks' AS [Category], 'Dup_MSSQLSvc_SPNs_Acct' AS [Check], '[OK]' AS [Deviation];
  4317. END
  4318. END TRY
  4319. BEGIN CATCH
  4320. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4321. SELECT @ErrorMessage = 'Service Accounts and SPN registration subsection - Error raised in TRY block 9. ' + ERROR_MESSAGE()
  4322. RAISERROR (@ErrorMessage, 16, 1);
  4323. END CATCH
  4324. IF @xcmd = 0
  4325. BEGIN
  4326. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  4327. END
  4328. IF @sao = 0
  4329. BEGIN
  4330. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  4331. END
  4332. END
  4333. ELSE
  4334. BEGIN
  4335. 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')
  4336. 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')
  4337. --RETURN
  4338. END
  4339. END
  4340. ELSE
  4341. BEGIN
  4342. 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')
  4343. --RETURN
  4344. END;
  4345. RAISERROR (N'|-Starting Instance Checks', 10, 1) WITH NOWAIT
  4346. --------------------------------------------------------------------------------------------------------------------------------
  4347. -- Recommended build check subsection
  4348. --------------------------------------------------------------------------------------------------------------------------------
  4349. RAISERROR (N' |-Starting Recommended build check', 10, 1) WITH NOWAIT
  4350. SELECT 'Instance_checks' AS [Category], 'Recommended_Build' AS [Check],
  4351. CASE WHEN (@sqlmajorver = 9 AND @sqlbuild < 5000)
  4352. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild < 6000)
  4353. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild < 6000)
  4354. OR (@sqlmajorver = 11 AND @sqlbuild < 6020)
  4355. OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  4356. OR (@sqlmajorver = 13 AND @sqlbuild < 4000)
  4357. THEN '[WARNING: current service pack has been superseded in the current SQL Server version. Install the latest service pack as soon as possible.]'
  4358. ELSE '[OK]'
  4359. END AS [Deviation],
  4360. CASE WHEN @sqlmajorver = 9 THEN '2005'
  4361. WHEN @sqlmajorver = 10 AND @sqlminorver = 0 THEN '2008'
  4362. WHEN @sqlmajorver = 10 AND @sqlminorver = 50 THEN '2008R2'
  4363. WHEN @sqlmajorver = 11 THEN '2012'
  4364. WHEN @sqlmajorver = 12 THEN '2014'
  4365. WHEN @sqlmajorver = 13 THEN '2016'
  4366. END AS [Product_Major_Version],
  4367. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductLevel')) AS Product_Level,
  4368. CASE WHEN @sqlmajorver >= 13 OR (@sqlmajorver = 12 AND @sqlbuild >= 2556 AND @sqlbuild < 4100) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427) THEN CONVERT(VARCHAR(128), SERVERPROPERTY('ProductBuildType')) ELSE 'NA' END AS Product_Build_Type,
  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('ProductUpdateLevel')) ELSE 'NA' END AS Product_Update_Level,
  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('ProductUpdateReference')) ELSE 'NA' END AS Product_Update_Ref_KB;
  4371. --------------------------------------------------------------------------------------------------------------------------------
  4372. -- Backup checks subsection
  4373. --------------------------------------------------------------------------------------------------------------------------------
  4374. RAISERROR (N' |-Starting Backup checks', 10, 1) WITH NOWAIT
  4375. DECLARE @nolog int, @nobck int, @nolog24h int, @neverlog int, @neverbck int
  4376. -- No Full backups
  4377. SELECT @neverbck = COUNT(DISTINCT d.name)
  4378. FROM master.sys.databases d (NOLOCK)
  4379. INNER JOIN #tmpdbs_userchoice tuc ON d.database_id = tuc.[dbid]
  4380. WHERE database_id NOT IN (2,3)
  4381. AND source_database_id IS NULL -- no snapshots
  4382. 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
  4383. -- No Full backups in last 7 days
  4384. ;WITH cteFullBcks (cnt) AS (SELECT DISTINCT database_name AS cnt
  4385. FROM msdb.dbo.backupset b (NOLOCK)
  4386. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4387. WHERE b.type = 'D' -- Full backup
  4388. AND b.is_copy_only = 0 -- No COPY_ONLY backups
  4389. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4390. WHERE database_id NOT IN (2,3)
  4391. AND source_database_id IS NULL) -- no snapshots
  4392. GROUP BY database_name
  4393. HAVING MAX(backup_finish_date) <= DATEADD(dd, -7, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) + 1, 0)))
  4394. SELECT @nobck = COUNT(cnt)
  4395. FROM cteFullBcks;
  4396. -- Last Log backup precedes last full or diff backup, and DB in Full or Bulk-logged RM
  4397. ;WITH cteLogBcks (cnt) AS (SELECT DISTINCT database_name
  4398. FROM msdb.dbo.backupset b (NOLOCK)
  4399. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4400. WHERE b.type = 'L' -- Log backup
  4401. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4402. WHERE database_id NOT IN (2,3)
  4403. AND source_database_id IS NULL -- no snapshots
  4404. AND recovery_model < 3) -- not SIMPLE recovery model
  4405. GROUP BY [database_name]
  4406. 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
  4407. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4408. AND c.database_name = b.database_name))
  4409. SELECT @nolog = COUNT(cnt)
  4410. FROM cteLogBcks;
  4411. -- No Log backup since last full or diff backup, and DB in Full or Bulk-logged RM
  4412. SELECT @neverlog = COUNT(DISTINCT database_name)
  4413. FROM msdb.dbo.backupset b (NOLOCK)
  4414. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4415. WHERE database_name IN (SELECT name
  4416. FROM master.sys.databases (NOLOCK)
  4417. WHERE database_id NOT IN (2,3)
  4418. AND source_database_id IS NULL -- no snapshots
  4419. AND recovery_model < 3) -- not SIMPLE recovery model
  4420. AND EXISTS (SELECT DISTINCT database_name
  4421. FROM msdb.dbo.backupset c (NOLOCK)
  4422. WHERE c.type IN ('D','I') -- Full or Differential backup
  4423. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4424. AND c.database_name = b.database_name) -- Log backup
  4425. AND NOT EXISTS (SELECT DISTINCT database_name
  4426. FROM msdb.dbo.backupset c (NOLOCK)
  4427. WHERE c.type = 'L' -- Log Backup
  4428. AND c.database_name = b.database_name);
  4429. -- Log backup since last full or diff backup is older than 24h, and DB in Full ar Bulk-logged RM
  4430. ;WITH cteLogBcks2 (cnt) AS (SELECT DISTINCT database_name
  4431. FROM msdb.dbo.backupset b (NOLOCK)
  4432. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4433. WHERE b.type = 'L' -- Log backup
  4434. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4435. WHERE database_id NOT IN (2,3)
  4436. AND source_database_id IS NULL -- no snapshots
  4437. AND recovery_model < 3) -- not SIMPLE recovery model
  4438. GROUP BY database_name
  4439. 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
  4440. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4441. AND c.database_name = b.database_name)
  4442. AND MAX(backup_finish_date) <= DATEADD(hh, -24, GETDATE()))
  4443. SELECT @nolog24h = COUNT(cnt)
  4444. FROM cteLogBcks2;
  4445. IF @nobck > 0 OR @neverbck > 0
  4446. BEGIN
  4447. 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]
  4448. -- No full backups in last 7 days
  4449. SELECT DISTINCT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Information], database_name AS [Database_Name], MAX(backup_finish_date) AS Lst_Full_Backup
  4450. FROM msdb.dbo.backupset b (NOLOCK)
  4451. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4452. WHERE b.type = 'D' -- Full backup
  4453. AND b.is_copy_only = 0 -- No COPY_ONLY backups
  4454. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4455. WHERE database_id NOT IN (2,3)
  4456. AND source_database_id IS NULL) -- no snapshots
  4457. GROUP BY database_name
  4458. HAVING MAX(backup_finish_date) <= DATEADD(dd, -7, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) + 1, 0))
  4459. UNION ALL
  4460. -- No full backups in history
  4461. SELECT DISTINCT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Information], d.name AS [Database_Name], NULL AS Lst_Full_Backup
  4462. FROM master.sys.databases d (NOLOCK)
  4463. INNER JOIN #tmpdbs_userchoice tuc ON d.database_id = tuc.[dbid]
  4464. WHERE database_id NOT IN (2,3)
  4465. AND source_database_id IS NULL -- no snapshots
  4466. AND recovery_model < 3 -- not SIMPLE recovery model
  4467. 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
  4468. AND d.name NOT IN (SELECT b.database_name FROM msdb.dbo.backupset b WHERE b.type = 'L') -- Log backup
  4469. ORDER BY [Database_Name]
  4470. END
  4471. ELSE
  4472. BEGIN
  4473. SELECT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Check], '[OK]' AS [Deviation]
  4474. END;
  4475. IF @nolog > 0 OR @neverlog > 0
  4476. BEGIN
  4477. 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]
  4478. ;WITH Bck AS (SELECT database_name, MAX(backup_finish_date) AS backup_finish_date
  4479. FROM msdb.dbo.backupset (NOLOCK) b
  4480. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4481. WHERE [type] IN ('D','I') -- Full or Differential backup
  4482. GROUP BY database_name)
  4483. -- Log backups since last full or diff is older than 24h
  4484. 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,
  4485. (SELECT backup_finish_date FROM Bck c WHERE c.database_name = b.database_name) AS Lst_FullDiff_Backup
  4486. FROM msdb.dbo.backupset b (NOLOCK)
  4487. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4488. WHERE b.type = 'L' -- Log backup
  4489. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4490. WHERE database_id NOT IN (2,3)
  4491. AND source_database_id IS NULL -- no snapshots
  4492. AND recovery_model < 3) -- not SIMPLE recovery model
  4493. GROUP BY [database_name]
  4494. HAVING MAX(backup_finish_date) < (SELECT backup_finish_date FROM Bck c WHERE c.database_name = b.database_name)
  4495. UNION ALL
  4496. -- No log backup in history but full backup exists
  4497. 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
  4498. FROM msdb.dbo.backupset b (NOLOCK)
  4499. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4500. WHERE database_name IN (SELECT name
  4501. FROM master.sys.databases (NOLOCK)
  4502. WHERE database_id NOT IN (2,3)
  4503. AND source_database_id IS NULL -- no snapshots
  4504. AND recovery_model < 3) -- not SIMPLE recovery model
  4505. AND EXISTS (SELECT DISTINCT database_name
  4506. FROM msdb.dbo.backupset c (NOLOCK)
  4507. WHERE c.type IN ('D','I') -- Full or Differential backup
  4508. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4509. AND c.database_name = b.database_name) -- Log backup
  4510. AND NOT EXISTS (SELECT DISTINCT database_name
  4511. FROM msdb.dbo.backupset c (NOLOCK)
  4512. WHERE c.type = 'L' -- Log Backup
  4513. AND c.database_name = b.database_name)
  4514. GROUP BY database_name
  4515. ORDER BY database_name;
  4516. END
  4517. ELSE
  4518. BEGIN
  4519. SELECT 'Instance_checks' AS [Category], 'No_Log_Bcks_since_LstFullorDiff' AS [Check], '[OK]' AS [Deviation]
  4520. END;
  4521. IF @nolog24h > 0
  4522. BEGIN
  4523. 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]
  4524. 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
  4525. FROM msdb.dbo.backupset b (NOLOCK)
  4526. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4527. WHERE b.type = 'L' -- Log backup
  4528. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4529. WHERE database_id NOT IN (2,3)
  4530. AND recovery_model < 3) -- not SIMPLE recovery model
  4531. GROUP BY database_name
  4532. 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
  4533. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4534. AND c.database_name = b.database_name)
  4535. AND MAX(backup_finish_date) <= DATEADD(hh, -24, GETDATE())
  4536. ORDER BY [database_name];
  4537. END
  4538. ELSE
  4539. BEGIN
  4540. SELECT 'Instance_checks' AS [Category], 'Log_Bcks_since_LstFullorDiff_are_older_than_24H' AS [Check], '[OK]' AS [Deviation]
  4541. END;
  4542. --------------------------------------------------------------------------------------------------------------------------------
  4543. -- Global trace flags subsection
  4544. --------------------------------------------------------------------------------------------------------------------------------
  4545. RAISERROR (N' |-Starting Global trace flags', 10, 1) WITH NOWAIT
  4546. DECLARE @tracestatus TABLE (TraceFlag NVARCHAR(40), [Status] tinyint, [Global] tinyint, [Session] tinyint);
  4547. INSERT INTO @tracestatus
  4548. EXEC ('DBCC TRACESTATUS WITH NO_INFOMSGS')
  4549. IF @sqlmajorver >= 11
  4550. BEGIN
  4551. DECLARE @dbname0 VARCHAR(1000), @dbid0 int, @sqlcmd0 NVARCHAR(4000), @has_colstrix int
  4552. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  4553. DROP TABLE #tblColStoreIXs;
  4554. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  4555. CREATE TABLE #tblColStoreIXs ([DBName] VARCHAR(1000), [Schema] VARCHAR(100), [Table] VARCHAR(255), [Object] VARCHAR(255));
  4556. UPDATE #tmpdbs0
  4557. SET isdone = 0;
  4558. UPDATE #tmpdbs0
  4559. SET isdone = 1
  4560. WHERE [state] <> 0 OR [dbid] < 5;
  4561. UPDATE #tmpdbs0
  4562. SET isdone = 1
  4563. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  4564. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  4565. BEGIN
  4566. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  4567. BEGIN
  4568. SELECT TOP 1 @dbname0 = [dbname], @dbid0 = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  4569. SET @sqlcmd0 = 'USE ' + QUOTENAME(@dbname0) + ';
  4570. SELECT ''' + @dbname0 + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), i.name
  4571. FROM sys.indexes AS i (NOLOCK)
  4572. INNER JOIN sys.objects AS o (NOLOCK) ON o.[object_id] = i.[object_id]
  4573. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = i.[object_id]
  4574. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  4575. WHERE i.[type] IN (5,6,7)' -- 5 = Clustered columnstore; 6 = Nonclustered columnstore; 7 = Nonclustered hash
  4576. BEGIN TRY
  4577. INSERT INTO #tblColStoreIXs
  4578. EXECUTE sp_executesql @sqlcmd0
  4579. END TRY
  4580. BEGIN CATCH
  4581. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4582. SELECT @ErrorMessage = 'Global trace flags subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  4583. RAISERROR (@ErrorMessage, 16, 1);
  4584. END CATCH
  4585. UPDATE #tmpdbs0
  4586. SET isdone = 1
  4587. WHERE [dbid] = @dbid0
  4588. END
  4589. END;
  4590. SELECT @has_colstrix = COUNT(*) FROM #tblColStoreIXs
  4591. END;
  4592. IF (SELECT COUNT(TraceFlag) FROM @tracestatus WHERE [Global]=1) = 0
  4593. BEGIN
  4594. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check], '[There are no Global Trace Flags active]' AS [Deviation]
  4595. END;
  4596. -- Plan affecting TFs: http://support.microsoft.com/kb/2801413 and https://support.microsoft.com/en-us/kb/2964518
  4597. -- All supported TFs: http://msdn.microsoft.com/library/ms188396.aspx
  4598. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1)
  4599. BEGIN
  4600. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 634)
  4601. BEGIN
  4602. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4603. '[INFORMATION: TF634 disables the background columnstore compression task]'
  4604. AS [Deviation], TraceFlag
  4605. FROM @tracestatus
  4606. WHERE [Global] = 1 AND TraceFlag = 634
  4607. END;
  4608. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 652)
  4609. BEGIN
  4610. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4611. '[INFORMATION: TF652 disables read-aheads during scans]' --http://support.microsoft.com/en-us/kb/920093
  4612. AS [Deviation], TraceFlag
  4613. FROM @tracestatus
  4614. WHERE [Global] = 1 AND TraceFlag = 634
  4615. END;
  4616. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 661)
  4617. BEGIN
  4618. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4619. '[INFORMATION: TF661 disables the ghost cleanup background task]'
  4620. AS [Deviation], TraceFlag
  4621. FROM @tracestatus
  4622. WHERE [Global] = 1 AND TraceFlag = 661
  4623. END;
  4624. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 834)
  4625. BEGIN
  4626. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4627. CASE WHEN @sqlmajorver >= 11
  4628. AND @has_colstrix > 0
  4629. THEN '[WARNING: TF834 (Large Page Support for BP) is discouraged when Columnstore Indexes are used]'
  4630. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4631. END AS [Deviation], TraceFlag
  4632. FROM @tracestatus
  4633. WHERE [Global] = 1 AND TraceFlag = 834
  4634. END;
  4635. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 845)
  4636. BEGIN
  4637. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4638. CASE WHEN SERVERPROPERTY('EngineEdition') = 2 --Standard SKU
  4639. AND ((@sqlmajorver = 10 AND ((@sqlminorver = 0 AND @sqlbuild >= 2714) OR @sqlminorver = 50))
  4640. OR (@sqlmajorver = 9 AND @sqlbuild >= 4226))
  4641. THEN '[INFORMATION: TF845 supports locking pages in memory in SQL Server Standard Editions]'
  4642. WHEN SERVERPROPERTY('EngineEdition') = 2 --Standard SKU
  4643. AND @sqlmajorver = 11
  4644. THEN '[WARNING: TF845 is not needed in SQL 2012 and above]'
  4645. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4646. END AS [Deviation], TraceFlag
  4647. FROM @tracestatus
  4648. WHERE [Global] = 1 AND TraceFlag = 845
  4649. END;
  4650. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 902)
  4651. BEGIN
  4652. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4653. '[WARNING: TF902 Bypasses execution of database upgrade script when installing a Cumulative Update or Service Pack]'
  4654. AS [Deviation], TraceFlag
  4655. FROM @tracestatus
  4656. WHERE [Global] = 1 AND TraceFlag = 902
  4657. END;
  4658. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1117)
  4659. BEGIN
  4660. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4661. '[INFORMATION: TF1117 autogrows all files at the same time and affects all databases]'
  4662. AS [Deviation], TraceFlag
  4663. FROM @tracestatus
  4664. WHERE [Global] = 1 AND TraceFlag = 1117
  4665. END;
  4666. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1118)
  4667. BEGIN
  4668. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4669. '[INFORMATION: TF1118 forces uniform extent allocations instead of mixed page allocations]'
  4670. AS [Deviation], TraceFlag
  4671. FROM @tracestatus
  4672. WHERE [Global] = 1 AND TraceFlag = 1118
  4673. END;
  4674. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1204)
  4675. BEGIN
  4676. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4677. '[INFORMATION: TF1204 returns the resources and types of locks participating in a deadlock and also the current command affected]'
  4678. AS [Deviation], TraceFlag
  4679. FROM @tracestatus
  4680. WHERE [Global] = 1 AND TraceFlag = 1204
  4681. END;
  4682. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1211)
  4683. BEGIN
  4684. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4685. '[WARNING: TF1211 disables lock escalation based on memory pressure, or based on number of locks, increasing the amount of locks held]'
  4686. AS [Deviation], TraceFlag
  4687. FROM @tracestatus
  4688. WHERE [Global] = 1 AND TraceFlag = 1211
  4689. END;
  4690. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1222)
  4691. BEGIN
  4692. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4693. '[INFORMATION: TF1222 returns the resources and types of locks participating in a deadlock and also the current command affected]'
  4694. AS [Deviation], TraceFlag
  4695. FROM @tracestatus
  4696. WHERE [Global] = 1 AND TraceFlag = 1222
  4697. END;
  4698. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1224)
  4699. BEGIN
  4700. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4701. '[WARNING: TF1224 disables lock escalation based on the number of locks, and only escalates locks under memory pressure, increasing the amount of locks held]'
  4702. AS [Deviation], TraceFlag
  4703. FROM @tracestatus
  4704. WHERE [Global] = 1 AND TraceFlag = 1224
  4705. END;
  4706. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1229)
  4707. BEGIN
  4708. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4709. '[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
  4710. AS [Deviation], TraceFlag
  4711. FROM @tracestatus
  4712. WHERE [Global] = 1 AND TraceFlag = 1229
  4713. END;
  4714. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1236)
  4715. BEGIN
  4716. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4717. CASE WHEN @sqlmajorver = 9 OR @sqlmajorver = 10 OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 4100)
  4718. THEN '[INFORMATION: TF1236 enables database lock partitioning]'
  4719. WHEN (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 4100) OR @sqlmajorver = 13
  4720. THEN '[WARNING: TF1236 is not needed in SQL 2012 SP3, SQL Server 2014 SP1 and above]'
  4721. END AS [Deviation], TraceFlag
  4722. FROM @tracestatus
  4723. WHERE [Global] = 1 AND TraceFlag = 1236
  4724. END;
  4725. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1462)
  4726. BEGIN
  4727. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4728. '[WARNING: TF1462 disables log stream compression for asynchronous availability groups]'
  4729. AS [Deviation], TraceFlag
  4730. FROM @tracestatus
  4731. WHERE [Global] = 1 AND TraceFlag = 1462
  4732. END;
  4733. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2312)
  4734. BEGIN
  4735. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4736. CASE WHEN @sqlmajorver = 12
  4737. THEN '[INFORMATION: TF2312 enables New CE model, SQL Server 2014 version]'
  4738. WHEN @sqlmajorver = 13
  4739. THEN '[INFORMATION: TF2312 enables New CE model to SQL Server 2014 or SQL Server 2016 versions, dependent of the compatibility level of the database]'
  4740. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4741. END AS [Deviation], TraceFlag
  4742. FROM @tracestatus
  4743. WHERE [Global] = 1 AND TraceFlag = 2312
  4744. END;
  4745. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2330)
  4746. BEGIN
  4747. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4748. CASE WHEN @sqlmajorver = 9
  4749. 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
  4750. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4751. END AS [Deviation], TraceFlag
  4752. FROM @tracestatus
  4753. WHERE [Global] = 1 AND TraceFlag = 2330
  4754. END;
  4755. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2335)
  4756. BEGIN
  4757. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4758. CASE WHEN @sqlmajorver >= 9
  4759. AND @maxservermem >= 100000 * 1024 -- 100GB
  4760. AND @maxservermem <> 2147483647
  4761. THEN '[INFORMATION: TF2335 assumes a fixed amount of memory is available during query optimization. Recommended when server has more than 100GB of memory]'
  4762. WHEN @sqlmajorver >= 9
  4763. AND @maxservermem < 100000 * 1024 -- 100GB
  4764. AND @maxservermem <> 2147483647
  4765. THEN '[WARNING: TF2335 should not be set on servers with less than 100GB of memory]'
  4766. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4767. END AS [Deviation], TraceFlag
  4768. FROM @tracestatus
  4769. WHERE [Global] = 1 AND TraceFlag = 2335
  4770. END;
  4771. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2335)
  4772. AND @sqlmajorver >= 9
  4773. AND @maxservermem >= 100000 * 1024 -- 100GB
  4774. AND @maxservermem <> 2147483647
  4775. BEGIN
  4776. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4777. '[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
  4778. AS [Deviation]
  4779. END;
  4780. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2340)
  4781. BEGIN
  4782. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4783. '[INFORMATION: TF2340 causes SQL Server not to use a sort operation (batch sort) for optimized nested loop joins when generating a plan]'
  4784. AS [Deviation], TraceFlag
  4785. FROM @tracestatus
  4786. WHERE [Global] = 1 AND TraceFlag = 2340
  4787. END;
  4788. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2371)
  4789. BEGIN
  4790. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4791. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500) OR @sqlmajorver >= 11
  4792. THEN '[INFORMATION: TF2371 changes the fixed rate of the 20pct threshold for update statistics into a dynamic percentage rate]'
  4793. WHEN @sqlmajorver = 13
  4794. THEN '[WARNING: TF2371 is not needed in SQL 2016 and above]'
  4795. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4796. END AS [Deviation], TraceFlag
  4797. FROM @tracestatus
  4798. WHERE [Global] = 1 AND TraceFlag = 2371
  4799. END;
  4800. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2371)
  4801. AND ((@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500) OR @sqlmajorver >= 11)
  4802. BEGIN
  4803. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4804. '[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
  4805. AS [Deviation]
  4806. END;
  4807. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2389)
  4808. BEGIN
  4809. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4810. '[INFORMATION: TF2389 enables automatically generated quick statistics for ascending keys (histogram amendment)]'
  4811. AS [Deviation], TraceFlag
  4812. FROM @tracestatus
  4813. WHERE [Global] = 1 AND TraceFlag = 2389
  4814. END;
  4815. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2528)
  4816. BEGIN
  4817. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4818. '[INFORMATION: TF2528 disables parallel checking of objects by DBCC CHECKDB, DBCC CHECKFILEGROUP, and DBCC CHECKTABLE]'
  4819. AS [Deviation], TraceFlag
  4820. FROM @tracestatus
  4821. WHERE [Global] = 1 AND TraceFlag = 2528
  4822. END;
  4823. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2549)
  4824. BEGIN
  4825. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4826. '[INFORMATION: TF2549 runs the DBCC CHECKDB command assuming each database file is on a unique disk drive]'
  4827. AS [Deviation], TraceFlag
  4828. FROM @tracestatus
  4829. WHERE [Global] = 1 AND TraceFlag = 2549
  4830. END;
  4831. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2562)
  4832. BEGIN
  4833. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4834. '[INFORMATION: TF2562 runs the DBCC CHECKDB command in a single batch regardless of the number of indexes in the database]'
  4835. AS [Deviation], TraceFlag
  4836. FROM @tracestatus
  4837. WHERE [Global] = 1 AND TraceFlag = 2562
  4838. END;
  4839. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2566)
  4840. BEGIN
  4841. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4842. '[INFORMATION: TF2566 runs the DBCC CHECKDB command without data purity check unless DATA_PURITY option is specified]'
  4843. AS [Deviation], TraceFlag
  4844. FROM @tracestatus
  4845. WHERE [Global] = 1 AND TraceFlag = 2566
  4846. END;
  4847. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3023)
  4848. BEGIN
  4849. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4850. '[INFORMATION: TF3023 enables CHECKSUM option as default for BACKUP command]'
  4851. AS [Deviation], TraceFlag
  4852. FROM @tracestatus
  4853. WHERE [Global] = 1 AND TraceFlag = 3023
  4854. END;
  4855. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3042)
  4856. BEGIN
  4857. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4858. '[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]'
  4859. AS [Deviation], TraceFlag
  4860. FROM @tracestatus
  4861. WHERE [Global] = 1 AND TraceFlag = 3042
  4862. END;
  4863. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3226)
  4864. BEGIN
  4865. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4866. '[INFORMATION: TF3226 prevents SQL Server from recording an entry to Errorlog on every successful backup operation]'
  4867. AS [Deviation], TraceFlag
  4868. FROM @tracestatus
  4869. WHERE [Global] = 1 AND TraceFlag = 3226
  4870. END;
  4871. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4135)
  4872. BEGIN
  4873. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4874. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1818 AND 1835)
  4875. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1702)
  4876. THEN '[WARNING: TF4199 should be used instead of TF4135 in this SQL build]'
  4877. ELSE '[INFORMATION: TF4135 enables query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  4878. END AS [Deviation], TraceFlag
  4879. FROM @tracestatus
  4880. WHERE [Global] = 1 AND TraceFlag = 4135
  4881. END;
  4882. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4136)
  4883. BEGIN
  4884. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4885. CASE WHEN (@sqlmajorver = 9 AND @sqlbuild >= 4294)
  4886. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 2766)
  4887. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1720)
  4888. OR (@sqlmajorver = 11 AND @sqlbuild >= 2316)
  4889. OR @sqlmajorver >= 12
  4890. THEN '[INFORMATION: TF4136 disables parameter sniffing unless OPTION(RECOMPILE), WITH RECOMPILE or OPTIMIZE FOR value is used]'
  4891. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4892. END AS [Deviation], TraceFlag
  4893. FROM @tracestatus
  4894. WHERE [Global] = 1 AND TraceFlag = 4136
  4895. END;
  4896. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4137)
  4897. BEGIN
  4898. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4899. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 5794)
  4900. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 4326 AND 4371)
  4901. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2806)
  4902. OR (@sqlmajorver = 11 AND @sqlbuild >= 2316)
  4903. OR @sqlmajorver >= 12
  4904. 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]'
  4905. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4906. END AS [Deviation], TraceFlag
  4907. FROM @tracestatus
  4908. WHERE [Global] = 1 AND TraceFlag = 4137
  4909. END;
  4910. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4138)
  4911. BEGIN
  4912. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4913. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4260)
  4914. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 2817 AND 2881)
  4915. OR (@sqlmajorver = 11 AND @sqlbuild >= 2325)
  4916. OR @sqlmajorver >= 12
  4917. 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]'
  4918. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4919. END AS [Deviation], TraceFlag
  4920. FROM @tracestatus
  4921. WHERE [Global] = 1 AND TraceFlag = 4138
  4922. END;
  4923. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4139)
  4924. BEGIN
  4925. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4926. CASE WHEN (@sqlmajorver = 11 AND @sqlbuild >= 5532)
  4927. OR (@sqlmajorver = 11 AND @sqlbuild >= 3431 AND @sqlbuild < 5058)
  4928. OR @sqlmajorver >= 12
  4929. THEN '[INFORMATION: TF4139 enables automatically generated quick statistics (histogram amendment) regardless of key column status]'
  4930. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4931. END AS [Deviation], TraceFlag
  4932. FROM @tracestatus
  4933. WHERE [Global] = 1 AND TraceFlag = 4139
  4934. END;
  4935. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4199)
  4936. BEGIN
  4937. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4938. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1787 AND 1812)
  4939. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 2531 AND 2757)
  4940. OR (@sqlmajorver >= 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 1600 AND 1617)
  4941. THEN '[WARNING: TF4135 should be used instead of TF4199 in this SQL build]'
  4942. ELSE '[INFORMATION: TF4199 enables query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  4943. END AS [Deviation], TraceFlag
  4944. FROM @tracestatus
  4945. WHERE [Global] = 1 AND TraceFlag = 4199
  4946. END;
  4947. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 6498)
  4948. BEGIN
  4949. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4950. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 4416)
  4951. OR (@sqlmajorver = 12 AND @sqlbuild BETWEEN 2480 AND 2474)
  4952. THEN '[INFORMATION: TF6498 enables more than one large query compilation to gain access to the big gateway when there is sufficient memory available]'
  4953. WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver >= 13
  4954. THEN '[WARNING: TF6498 is not needed in SQL 2014 SP2, SQL Server 2016 and above]'
  4955. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4956. END AS [Deviation], TraceFlag
  4957. FROM @tracestatus
  4958. WHERE [Global] = 1 AND TraceFlag = 6498
  4959. END;
  4960. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag IN (6532,6533))
  4961. BEGIN
  4962. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4963. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000)
  4964. OR (@sqlmajorver = 11 AND @sqlbuild >= 6020)
  4965. THEN '[INFORMATION: TF6532 and TF 6533 enable performance improvement of query operations with spatial data types]'
  4966. WHEN @sqlmajorver = 13
  4967. THEN '[WARNING: TF6532 and TF 6533 are not needed in SQL Server 2016 and above]'
  4968. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4969. END AS [Deviation], TraceFlag
  4970. FROM @tracestatus
  4971. WHERE [Global] = 1 AND TraceFlag IN (6532,6533)
  4972. END;
  4973. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 6534)
  4974. BEGIN
  4975. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4976. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000)
  4977. OR (@sqlmajorver = 11 AND @sqlbuild >= 6020)
  4978. OR @sqlmajorver = 13
  4979. THEN '[INFORMATION: TF6534 enables performance improvement of query operations with spatial data types]'
  4980. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4981. END AS [Deviation], TraceFlag
  4982. FROM @tracestatus
  4983. WHERE [Global] = 1 AND TraceFlag = 6534
  4984. END;
  4985. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8015)
  4986. BEGIN
  4987. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4988. CASE WHEN (@sqlmajorver = 11 AND @sqlbuild >= 3349)
  4989. OR @sqlmajorver >= 12
  4990. 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
  4991. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4992. END AS [Deviation], TraceFlag
  4993. FROM @tracestatus
  4994. WHERE [Global] = 1 AND TraceFlag = 8015
  4995. END;
  4996. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8032)
  4997. BEGIN
  4998. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4999. CASE WHEN @sqlmajorver >= 10
  5000. 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]'
  5001. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5002. END AS [Deviation], TraceFlag
  5003. FROM @tracestatus
  5004. WHERE [Global] = 1 AND TraceFlag = 8032
  5005. END;
  5006. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8048)
  5007. BEGIN
  5008. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5009. CASE WHEN ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5010. OR (@sqlmajorver BETWEEN 9 AND 11))
  5011. AND (@cpucount/@numa) > 8
  5012. 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
  5013. WHEN (@sqlmajorver = 12 AND @sqlbuild >= 4100) OR @sqlmajorver >= 13
  5014. THEN '[WARNING: TF8048 is not needed in SQL Server 2014 SP2, SQL Server 2016 and above]'
  5015. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5016. END AS [Deviation], TraceFlag
  5017. FROM @tracestatus
  5018. WHERE [Global] = 1 AND TraceFlag = 8048
  5019. END;
  5020. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8048)
  5021. AND ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5022. OR (@sqlmajorver BETWEEN 9 AND 11))
  5023. AND (@cpucount/@numa) > 8
  5024. BEGIN
  5025. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5026. '[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
  5027. AS [Deviation];
  5028. -- If the top consumers are partitioned by Node, then use startup trace flag 8048 to further partition by CPU.
  5029. IF @sqlmajorver < 11
  5030. BEGIN
  5031. SELECT 'Instance_checks' AS [Category], 'Is_TF8048_Applicable' AS [Check], [type],
  5032. SUM(page_size_in_bytes)/8192 AS [pages],
  5033. SUM(page_size_in_bytes)/1024 AS pages_in_KB,
  5034. CASE WHEN (0x20 = creation_options & 0x20) THEN 'Global PMO. Cannot be partitioned by CPU/NUMA Node. TF8048 not applicable.'
  5035. WHEN (0x40 = creation_options & 0x40) THEN 'Partitioned by CPU. TF8048 not applicable.'
  5036. WHEN (0x80 = creation_options & 0x80) THEN 'Partitioned by Node. Use TF8048 to further partition by CPU'
  5037. ELSE 'Unknown' END AS [Comment]
  5038. FROM sys.dm_os_memory_objects
  5039. GROUP BY [type], creation_options
  5040. ORDER BY SUM(page_size_in_bytes) DESC;
  5041. END
  5042. ELSE
  5043. BEGIN
  5044. SET @sqlcmd = N'SELECT ''Instance_checks'' AS [Category], ''Is_TF8048_Applicable'' AS [Check], [type],
  5045. SUM(pages_in_bytes)/8192 AS [pages],
  5046. SUM(pages_in_bytes)/1024 AS pages_in_KB,
  5047. CASE WHEN (0x20 = creation_options & 0x20) THEN ''Global PMO. Cannot be partitioned by CPU/NUMA Node. TF8048 not applicable.''
  5048. WHEN (0x40 = creation_options & 0x40) THEN ''Partitioned by CPU. TF8048 not applicable.''
  5049. WHEN (0x80 = creation_options & 0x80) THEN ''Partitioned by Node. Use TF8048 to further partition by CPU''
  5050. ELSE ''Unknown'' END AS [Comment]
  5051. FROM sys.dm_os_memory_objects
  5052. GROUP BY [type], creation_options
  5053. ORDER BY SUM(pages_in_bytes) DESC;'
  5054. EXECUTE sp_executesql @sqlcmd
  5055. END;
  5056. END;
  5057. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8744)
  5058. BEGIN
  5059. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5060. CASE WHEN @sqlmajorver >= 12 THEN
  5061. '[INFORMATION: TF8744 disables pre-fetching for the Nested Loop operator]'
  5062. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5063. END AS [Deviation], TraceFlag
  5064. FROM @tracestatus
  5065. WHERE [Global] = 1 AND TraceFlag = 8744
  5066. END;
  5067. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9024)
  5068. BEGIN
  5069. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5070. CASE WHEN ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5071. OR (@sqlmajorver = 11 AND @sqlbuild >= 3349 AND @sqlbuild < 6020))
  5072. AND (@cpucount/@numa) > 8
  5073. THEN '[INFORMATION: TF9024 converts a global log pool memory object into NUMA node partitioned memory object]'
  5074. WHEN (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427) OR @sqlmajorver > 12
  5075. THEN '[WARNING: TF9024 is not needed in SQL Server 2012 SP3, SQL Server 2014 SP1 and above]'
  5076. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5077. END AS [Deviation], TraceFlag
  5078. FROM @tracestatus
  5079. WHERE [Global] = 1 AND TraceFlag = 9024
  5080. END;
  5081. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9347)
  5082. BEGIN
  5083. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5084. CASE WHEN @sqlmajorver >= 13 THEN
  5085. '[INFORMATION: TF9347 disables batch mode for sort operator]'
  5086. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5087. END AS [Deviation], TraceFlag
  5088. FROM @tracestatus
  5089. WHERE [Global] = 1 AND TraceFlag = 9347
  5090. END;
  5091. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9349)
  5092. BEGIN
  5093. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5094. CASE WHEN @sqlmajorver >= 13 THEN
  5095. '[INFORMATION: TF9349 disables batch mode for top N sort operator]'
  5096. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5097. END AS [Deviation], TraceFlag
  5098. FROM @tracestatus
  5099. WHERE [Global] = 1 AND TraceFlag = 9349
  5100. END;
  5101. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9389)
  5102. BEGIN
  5103. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5104. CASE WHEN @sqlmajorver >= 13 THEN
  5105. '[INFORMATION: TF9389 enables dynamic memory grant for batch mode operators]'
  5106. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5107. END AS [Deviation], TraceFlag
  5108. FROM @tracestatus
  5109. WHERE [Global] = 1 AND TraceFlag = 9389
  5110. END;
  5111. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9476)
  5112. BEGIN
  5113. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5114. CASE WHEN @sqlmajorver >= 13 THEN
  5115. '[INFORMATION: TF9476 causes SQL Server to generate a plan using the Simple Containment instead of the default Base Containment under New CE]'
  5116. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5117. END AS [Deviation], TraceFlag
  5118. FROM @tracestatus
  5119. WHERE [Global] = 1 AND TraceFlag = 9476
  5120. END;
  5121. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9481)
  5122. BEGIN
  5123. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5124. CASE WHEN @sqlmajorver >= 12
  5125. THEN '[INFORMATION: TF9481 enables Legacy CE model, irrespective of the compatibility level of the database]'
  5126. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5127. END AS [Deviation], TraceFlag
  5128. FROM @tracestatus
  5129. WHERE [Global] = 1 AND TraceFlag = 9481
  5130. END;
  5131. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 10204)
  5132. BEGIN
  5133. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5134. CASE WHEN @sqlmajorver >= 13
  5135. THEN '[INFORMATION: TF10204 disables merge/recompress during columnstore index reorganization]'
  5136. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5137. END AS [Deviation], TraceFlag
  5138. FROM @tracestatus
  5139. WHERE [Global] = 1 AND TraceFlag = 10204
  5140. END;
  5141. END;
  5142. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag IN (4135,4199))
  5143. BEGIN
  5144. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5145. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1787 AND 1812)
  5146. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 2531 AND 2757)
  5147. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 2766)
  5148. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 1600 AND 1617)
  5149. THEN '[INFORMATION: Consider enabling TF4135 to support fixes and enhancements on the query optimizer]'
  5150. WHEN (@sqlmajorver = 9 AND @sqlbuild >= 4266)
  5151. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1818 AND 1835)
  5152. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1702) OR @sqlmajorver >= 11
  5153. THEN '[INFORMATION: Consider enabling TF4199 to enable query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  5154. END AS [Deviation]
  5155. END;
  5156. --------------------------------------------------------------------------------------------------------------------------------
  5157. -- System configurations subsection
  5158. --------------------------------------------------------------------------------------------------------------------------------
  5159. RAISERROR (N' |-Starting System configurations', 10, 1) WITH NOWAIT
  5160. -- Focus on:
  5161. -- backup compression default
  5162. -- clr enabled (only enable if needed)
  5163. -- lightweight pooling (should be zero)
  5164. -- max degree of parallelism
  5165. -- cost threshold for parallelism
  5166. -- max server memory (MB) (set to an appropriate value)
  5167. -- priority boost (should be zero)
  5168. -- remote admin connections (should be enabled in a cluster configuration, to allow remote DAC)
  5169. -- scan for startup procs (should be disabled unless business requirement, like replication)
  5170. -- min memory per query (default is 1024KB)
  5171. -- allow updates (no effect in 2005 or above, but should be off)
  5172. -- max worker threads (should be zero in 2005 or above)
  5173. -- affinity mask and affinity I/O mask (must not overlap)
  5174. DECLARE @awe tinyint, @ssp bit, @bckcomp bit, @clr bit, @costparallel tinyint, @chain bit, @lpooling bit
  5175. DECLARE @adhoc smallint, @pboost bit, @qtimeout int, @cmdshell bit, @deftrace bit, @remote bit, @autoNUMA bit
  5176. DECLARE @minmemqry int, @allowupd bit, @mwthreads int, @recinterval int, @netsize smallint
  5177. DECLARE @ixmem smallint, @adhocqry bit, @locks int, @qrywait int--, @mwthreads_count int
  5178. DECLARE @affin int, @affinIO int, @affin64 int, @affin64IO int, @block_threshold int, @oleauto int
  5179. --SELECT @mwthreads_count = max_workers_count FROM sys.dm_os_sys_info;
  5180. SELECT @adhocqry = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'Ad Hoc Distributed Queries';
  5181. SELECT @affin = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity mask';
  5182. SELECT @affinIO = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity I/O mask';
  5183. SELECT @affin64 = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity64 mask';
  5184. SELECT @affin64IO = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity64 I/O mask';
  5185. SELECT @allowupd = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'allow updates';
  5186. SELECT @block_threshold = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'blocked process threshold (s)';
  5187. SELECT @awe = CONVERT(tinyint, [value]) FROM sys.configurations WHERE [Name] = 'awe enabled';
  5188. SELECT @autoNUMA = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'automatic soft-NUMA disabled';
  5189. SELECT @bckcomp = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'backup compression default';
  5190. SELECT @clr = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'clr enabled';
  5191. SELECT @costparallel = CONVERT(tinyint, [value]) FROM sys.configurations WHERE [Name] = 'cost threshold for parallelism';
  5192. SELECT @chain = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'cross db ownership chaining';
  5193. SELECT @deftrace = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'default trace enabled';
  5194. SELECT @ixmem = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'index create memory (KB)';
  5195. SELECT @locks = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'locks';
  5196. SELECT @minmemqry = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'min memory per query (KB)';
  5197. SELECT @mwthreads = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'max worker threads';
  5198. SELECT @netsize = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'network packet size (B)';
  5199. SELECT @lpooling = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'lightweight pooling';
  5200. SELECT @recinterval = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'recovery interval (min)';
  5201. SELECT @remote = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'remote admin connections';
  5202. SELECT @qrywait = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'query wait (s)';
  5203. SELECT @adhoc = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'optimize for ad hoc workloads';
  5204. SELECT @oleauto = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'Ole Automation Procedures';
  5205. SELECT @pboost = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'priority boost';
  5206. SELECT @qtimeout = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'remote query timeout (s)';
  5207. SELECT @ssp = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'scan for startup procs';
  5208. SELECT @cmdshell = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'xp_cmdshell';
  5209. 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]
  5210. UNION ALL
  5211. 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]
  5212. UNION ALL
  5213. 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]
  5214. UNION ALL
  5215. 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]
  5216. UNION ALL
  5217. 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]
  5218. UNION ALL
  5219. 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]
  5220. UNION ALL
  5221. 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]
  5222. UNION ALL
  5223. 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]
  5224. UNION ALL
  5225. 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]
  5226. UNION ALL
  5227. 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]
  5228. UNION ALL
  5229. 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]
  5230. UNION ALL
  5231. 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]
  5232. UNION ALL
  5233. 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]
  5234. UNION ALL
  5235. 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]
  5236. UNION ALL
  5237. 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]
  5238. UNION ALL
  5239. 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]
  5240. UNION ALL
  5241. 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]
  5242. UNION ALL
  5243. 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]
  5244. UNION ALL
  5245. 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]
  5246. UNION ALL
  5247. 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]
  5248. UNION ALL
  5249. 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]
  5250. UNION ALL
  5251. 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]
  5252. UNION ALL
  5253. 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]
  5254. UNION ALL
  5255. 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]
  5256. UNION ALL
  5257. 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]
  5258. UNION ALL
  5259. 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]
  5260. UNION ALL
  5261. 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];
  5262. IF (SELECT COUNT([Name]) FROM master.sys.configurations WHERE [value] <> [value_in_use] AND [is_dynamic] = 0) > 0
  5263. BEGIN
  5264. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Check], '[WARNING: There are system configurations with differences between running and configured values]' AS [Deviation]
  5265. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Information], [Name] AS [Setting],
  5266. [value] AS 'Config_Value',
  5267. [value_in_use] AS 'Run_Value'
  5268. FROM master.sys.configurations (NOLOCK)
  5269. WHERE [value] <> [value_in_use] AND [is_dynamic] = 0;
  5270. END
  5271. ELSE
  5272. BEGIN
  5273. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Check], '[OK]' AS [Deviation]
  5274. END;
  5275. --------------------------------------------------------------------------------------------------------------------------------
  5276. -- IFI subsection
  5277. --------------------------------------------------------------------------------------------------------------------------------
  5278. RAISERROR (N' |-Starting IFI', 10, 1) WITH NOWAIT
  5279. DECLARE @ifi bit, @IFIStatus NVARCHAR(256)
  5280. IF ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13)
  5281. BEGIN
  5282. IF @allow_xpcmdshell = 1
  5283. BEGIN
  5284. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  5285. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5286. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  5287. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5288. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  5289. BEGIN
  5290. RAISERROR (' |-Configuration options set for IFI check', 10, 1) WITH NOWAIT
  5291. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  5292. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  5293. IF @sao = 0
  5294. BEGIN
  5295. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  5296. END
  5297. IF @xcmd = 0
  5298. BEGIN
  5299. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  5300. END
  5301. BEGIN TRY
  5302. DECLARE @xp_cmdshell_output2 TABLE ([Output] VARCHAR (8000));
  5303. SET @CMD = ('whoami /priv')
  5304. INSERT INTO @xp_cmdshell_output2
  5305. EXEC master.dbo.xp_cmdshell @CMD;
  5306. IF EXISTS (SELECT * FROM @xp_cmdshell_output2 WHERE [Output] LIKE '%SeManageVolumePrivilege%')
  5307. BEGIN
  5308. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[OK]' AS [Deviation];
  5309. SET @ifi = 1;
  5310. END
  5311. ELSE
  5312. BEGIN
  5313. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[WARNING: Instant File Initialization is disabled. This can impact data file autogrowth times]' AS [Deviation];
  5314. SET @ifi = 0
  5315. END
  5316. END TRY
  5317. BEGIN CATCH
  5318. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  5319. SELECT @ErrorMessage = 'IFI subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  5320. RAISERROR (@ErrorMessage, 16, 1);
  5321. END CATCH
  5322. IF @xcmd = 0
  5323. BEGIN
  5324. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  5325. END
  5326. IF @sao = 0
  5327. BEGIN
  5328. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  5329. END
  5330. END
  5331. ELSE
  5332. BEGIN
  5333. 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')
  5334. 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')
  5335. --RETURN
  5336. END
  5337. END
  5338. ELSE
  5339. BEGIN
  5340. RAISERROR(' |- [INFORMATION: "Instant Initialization" check was skipped because xp_cmdshell was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  5341. --RETURN
  5342. END
  5343. END
  5344. ELSE IF ((@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13)
  5345. BEGIN
  5346. 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%''';
  5347. SET @params = N'@IFIStatusOUT NVARCHAR(256) OUTPUT';
  5348. EXECUTE sp_executesql @sqlcmd, @params, @IFIStatusOUT=@IFIStatus OUTPUT;
  5349. IF @IFIStatus = 'Y'
  5350. BEGIN
  5351. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[OK]' AS [Deviation];
  5352. SET @ifi = 1;
  5353. END
  5354. ELSE
  5355. BEGIN
  5356. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[WARNING: Instant File Initialization is disabled. This can impact data file autogrowth times]' AS [Deviation];
  5357. SET @ifi = 0
  5358. END
  5359. END;
  5360. --------------------------------------------------------------------------------------------------------------------------------
  5361. -- Full Text Configurations subsection
  5362. --------------------------------------------------------------------------------------------------------------------------------
  5363. RAISERROR (N' |-Starting Full Text Configurations', 10, 1) WITH NOWAIT
  5364. DECLARE @FullTextDefaultPath NVARCHAR(512), @fterr tinyint
  5365. DECLARE @fttbl TABLE ([KeyExist] int)
  5366. DECLARE @FullTextDetails TABLE (FullText_ResourceUsage tinyint,
  5367. [DefaultPath] NVARCHAR(512),
  5368. [ConnectTimeout] int,
  5369. [DataTimeout] int,
  5370. [AllowUnsignedBinaries] bit,
  5371. [LoadOSResourcesEnabled] bit,
  5372. [CatalogUpgradeOption] tinyint)
  5373. SET @fterr = 0
  5374. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  5375. BEGIN
  5376. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 1)
  5377. BEGIN
  5378. BEGIN TRY
  5379. INSERT INTO @fttbl
  5380. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup' -- check if Full-Text path exists
  5381. IF (SELECT [KeyExist] FROM @fttbl) = 1
  5382. BEGIN
  5383. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup', N'FullTextDefaultPath', @FullTextDefaultPath OUTPUT, NO_OUTPUT;
  5384. END
  5385. END TRY
  5386. BEGIN CATCH
  5387. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  5388. SELECT @ErrorMessage = 'Full Text Configurations subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  5389. RAISERROR (@ErrorMessage, 16, 1);
  5390. END CATCH
  5391. END
  5392. ELSE
  5393. BEGIN
  5394. RAISERROR('[WARNING: Missing permissions for full "Full Text Configurations" checks. Bypassing Full Text path check]', 16, 1, N'sysadmin')
  5395. --RETURN
  5396. END
  5397. INSERT INTO @FullTextDetails
  5398. SELECT FULLTEXTSERVICEPROPERTY('ResourceUsage'), ISNULL(@FullTextDefaultPath, N'') AS [Default Path],
  5399. ISNULL(FULLTEXTSERVICEPROPERTY('ConnectTimeout'),0), ISNULL(FULLTEXTSERVICEPROPERTY('DataTimeout'),0),
  5400. CASE WHEN @sqlmajorver >= 9 THEN
  5401. FULLTEXTSERVICEPROPERTY('VerifySignature') ELSE NULL
  5402. END AS [AllowUnsignedBinaries],
  5403. CASE WHEN @sqlmajorver >= 9 THEN
  5404. FULLTEXTSERVICEPROPERTY('LoadOSResources') ELSE NULL
  5405. END AS [LoadOSResourcesEnabled],
  5406. CASE WHEN @sqlmajorver >= 10 THEN
  5407. FULLTEXTSERVICEPROPERTY('UpgradeOption') ELSE NULL
  5408. END AS [CatalogUpgradeOption];
  5409. IF @sqlmajorver <= 9 AND (SELECT FullText_ResourceUsage FROM @FullTextDetails) <> 3
  5410. BEGIN
  5411. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[INFORMATION: FullText Resource usage setting is not default]' AS [Deviation],
  5412. CASE WHEN FullText_ResourceUsage < 3 THEN '[Least Aggressive Usage Level]'
  5413. WHEN FullText_ResourceUsage = 4 THEN '[More Aggressive Usage Level]'
  5414. WHEN FullText_ResourceUsage = 5 THEN '[Most Aggressive Usage Level]'
  5415. END AS [Comment]
  5416. FROM @FullTextDetails;
  5417. SET @fterr = @fterr + 1
  5418. END
  5419. IF @sqlmajorver >= 9 AND (SELECT [AllowUnsignedBinaries] FROM @FullTextDetails) = 0
  5420. BEGIN
  5421. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[WARNING: FullText Binaries verification setting is not default]' AS [Deviation],
  5422. '[Do not verify whether or not binaries are signed]' AS [Comment];
  5423. SET @fterr = @fterr + 1
  5424. END
  5425. IF @sqlmajorver >= 9 AND (SELECT [LoadOSResourcesEnabled] FROM @FullTextDetails) = 1
  5426. BEGIN
  5427. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[WARNING: FullText OS Resource utilization setting is not default]' AS [Deviation],
  5428. '[Load OS filters and word breakers]' AS [Comment];
  5429. SET @fterr = @fterr + 1
  5430. END
  5431. IF @fterr = 0
  5432. BEGIN
  5433. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[OK]' AS [Deviation],
  5434. '[All FullText settings are aligned with defaults]' AS [Comment];
  5435. END
  5436. END;
  5437. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 0
  5438. BEGIN
  5439. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], NULL AS [Deviation], '[FullText search is not installed]' AS [Comment];
  5440. END;
  5441. --------------------------------------------------------------------------------------------------------------------------------
  5442. -- Deprecated features subsection
  5443. --------------------------------------------------------------------------------------------------------------------------------
  5444. IF @ptochecks = 1
  5445. BEGIN
  5446. RAISERROR (N' |-Starting Deprecated features', 10, 1) WITH NOWAIT
  5447. IF (SELECT COUNT(instance_name) FROM sys.dm_os_performance_counters WHERE [object_name] = 'SQLServer:Deprecated Features' AND cntr_value > 0) > 0
  5448. BEGIN
  5449. 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]
  5450. SELECT 'Instance_checks' AS [Category], 'Deprecated_features' AS [Information], instance_name, cntr_value AS [Times_used_since_startup]
  5451. FROM sys.dm_os_performance_counters (NOLOCK)
  5452. WHERE [object_name] LIKE '%Deprecated Features%' AND cntr_value > 0
  5453. ORDER BY instance_name;
  5454. END
  5455. ELSE
  5456. BEGIN
  5457. SELECT 'Instance_checks' AS [Category], 'Deprecated_features' AS [Check], '[OK]' AS [Deviation]
  5458. END;
  5459. END;
  5460. --------------------------------------------------------------------------------------------------------------------------------
  5461. -- Default data collections subsection
  5462. --------------------------------------------------------------------------------------------------------------------------------
  5463. RAISERROR (N' |-Starting default data collections', 10, 1) WITH NOWAIT
  5464. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE is_default = 1 AND status = 1)
  5465. BEGIN
  5466. SELECT 'Instance_checks' AS [Category], 'Default_Trace' AS [Check], '[OK]' AS [Deviation]
  5467. END
  5468. ELSE
  5469. BEGIN
  5470. 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]
  5471. END;
  5472. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE [path] LIKE '%blackbox%.trc' AND status = 1)
  5473. BEGIN
  5474. 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]
  5475. END
  5476. ELSE
  5477. BEGIN
  5478. SELECT 'Instance_checks' AS [Category], 'Blackbox_Trace' AS [Information], '[OK]' AS [Deviation]
  5479. END;
  5480. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE (is_default = 1 OR [path] LIKE '%blackbox%.trc') AND status = 1)
  5481. BEGIN
  5482. 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
  5483. FROM sys.traces
  5484. WHERE (is_default = 1 OR [path] LIKE '%blackbox%.trc') AND status = 1
  5485. END;
  5486. IF @sqlmajorver > 10
  5487. BEGIN
  5488. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] = 'system_health')
  5489. BEGIN
  5490. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_SystemHealth' AS [Check], '[OK]' AS [Deviation]
  5491. END
  5492. ELSE
  5493. BEGIN
  5494. 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]
  5495. END;
  5496. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] = 'sp_server_diagnostics session')
  5497. BEGIN
  5498. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_sp_server_diagnostics' AS [Check], '[OK]' AS [Deviation]
  5499. END
  5500. ELSE
  5501. BEGIN
  5502. 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]
  5503. END;
  5504. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] IN ('system_health', 'sp_server_diagnostics session'))
  5505. BEGIN
  5506. 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,
  5507. dropped_event_count, dropped_buffer_count, blocked_event_fire_time, create_time, largest_event_dropped_size
  5508. FROM sys.dm_xe_sessions
  5509. WHERE [name] IN ('system_health', 'sp_server_diagnostics session')
  5510. END;
  5511. END;
  5512. RAISERROR (N'|-Starting Database and tempDB Checks', 10, 1) WITH NOWAIT
  5513. --------------------------------------------------------------------------------------------------------------------------------
  5514. -- User objects in master DB
  5515. --------------------------------------------------------------------------------------------------------------------------------
  5516. RAISERROR (N' |-Starting User Objects in master DB', 10, 1) WITH NOWAIT
  5517. 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
  5518. BEGIN
  5519. SELECT 'Database_checks' AS [Category], 'User_Objects_in_master' AS [Check], '[WARNING: User objects are created in the master database]' AS [Deviation]
  5520. 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
  5521. FROM master.sys.all_objects sao
  5522. INNER JOIN master.sys.schemas ss ON sao.[schema_id] = ss.[schema_id]
  5523. WHERE sao.is_ms_shipped = 0
  5524. AND sao.[type] IN ('AF','FN','P','IF','PC','TF','TR','T','V')
  5525. ORDER BY sao.name, sao.type_desc;
  5526. END
  5527. ELSE
  5528. BEGIN
  5529. SELECT 'Database_checks' AS [Category], 'User_Objects_in_master' AS [Check], '[OK]' AS [Deviation]
  5530. END;
  5531. --------------------------------------------------------------------------------------------------------------------------------
  5532. -- DBs with collation <> master subsection
  5533. --------------------------------------------------------------------------------------------------------------------------------
  5534. RAISERROR (N' |-Starting DBs with collation <> master', 10, 1) WITH NOWAIT
  5535. DECLARE @master_collate NVARCHAR(128), @dif_collate int
  5536. SELECT @master_collate = collation_name FROM master.sys.databases (NOLOCK) WHERE database_id = 1;
  5537. SELECT @dif_collate = COUNT(collation_name) FROM master.sys.databases (NOLOCK) WHERE collation_name <> @master_collate;
  5538. IF @dif_collate >= 1
  5539. BEGIN
  5540. SELECT 'Database_checks' AS [Category], 'Collations' AS [Check], '[WARNING: Some user databases collation differ from the master Database_Collation]' AS [Deviation]
  5541. SELECT 'Database_checks' AS [Category], 'Collations' AS [Information], name AS [Database_Name], collation_name AS [Database_Collation], @master_collate AS [Master_Collation]
  5542. FROM master.sys.databases (NOLOCK)
  5543. WHERE collation_name <> @master_collate;
  5544. END
  5545. ELSE
  5546. BEGIN
  5547. SELECT 'Database_checks' AS [Category], 'Collations' AS [Check], '[OK]' AS [Deviation]
  5548. END;
  5549. --------------------------------------------------------------------------------------------------------------------------------
  5550. -- DBs with skewed compatibility level subsection
  5551. --------------------------------------------------------------------------------------------------------------------------------
  5552. RAISERROR (N' |-Starting DBs with skewed compatibility level', 10, 1) WITH NOWAIT
  5553. DECLARE @dif_compat int
  5554. SELECT @dif_compat = COUNT([compatibility_level]) FROM master.sys.databases (NOLOCK) WHERE [compatibility_level] <> @sqlmajorver * 10;
  5555. IF @dif_compat >= 1
  5556. BEGIN
  5557. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Check], '[WARNING: Some user databases have a non-optimal compatibility level]' AS [Deviation]
  5558. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Information], name AS [Database_Name], [compatibility_level] AS [Compatibility_Level]
  5559. FROM master.sys.databases (NOLOCK)
  5560. WHERE [compatibility_level] <> @sqlmajorver * 10;
  5561. END
  5562. ELSE
  5563. BEGIN
  5564. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Check], '[OK]' AS [Deviation]
  5565. END;
  5566. --------------------------------------------------------------------------------------------------------------------------------
  5567. -- User DBs with non-default options subsection
  5568. --------------------------------------------------------------------------------------------------------------------------------
  5569. RAISERROR (N' |-Starting User DBs with non-default options', 10, 1) WITH NOWAIT
  5570. DECLARE @cnt int, @cnt_i int
  5571. DECLARE @is_auto_close_on bit, @is_auto_shrink_on bit, @page_verify_option bit
  5572. DECLARE @is_auto_create_stats_on bit, @is_auto_update_stats_on bit
  5573. DECLARE @is_db_chaining_on bit, @is_auto_create_stats_incremental_on bit--, @is_indirect_checkpoint_on bit
  5574. DECLARE @is_trustworthy_on bit, @is_parameterization_forced bit
  5575. DECLARE @dbopterrtb TABLE (id int,
  5576. name sysname,
  5577. is_auto_close_on bit,
  5578. is_auto_shrink_on bit,
  5579. page_verify_option tinyint,
  5580. page_verify_option_desc NVARCHAR(60),
  5581. is_auto_create_stats_on bit,
  5582. is_auto_update_stats_on bit,
  5583. is_db_chaining_on bit,
  5584. --is_indirect_checkpoint_on bit,
  5585. is_auto_create_stats_incremental_on bit NULL,
  5586. is_trustworthy_on bit,
  5587. is_parameterization_forced bit)
  5588. IF @sqlmajorver < 12
  5589. BEGIN
  5590. SET @sqlcmd = 'SELECT ROW_NUMBER() OVER(ORDER BY name), name, is_auto_close_on,
  5591. is_auto_shrink_on, page_verify_option, page_verify_option_desc,
  5592. is_auto_create_stats_on, is_auto_update_stats_on, is_db_chaining_on,
  5593. --0 AS is_indirect_checkpoint_on,
  5594. NULL AS is_auto_create_stats_incremental_on,
  5595. is_trustworthy_on, is_parameterization_forced
  5596. FROM master.sys.databases (NOLOCK)
  5597. WHERE database_id > 4 OR name = ''model'''
  5598. END
  5599. ELSE
  5600. BEGIN
  5601. SET @sqlcmd = 'SELECT ROW_NUMBER() OVER(ORDER BY name), name, is_auto_close_on,
  5602. is_auto_shrink_on, page_verify_option, page_verify_option_desc,
  5603. is_auto_create_stats_on, is_auto_update_stats_on,
  5604. is_db_chaining_on,
  5605. --CASE WHEN target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  5606. is_auto_create_stats_incremental_on,
  5607. is_trustworthy_on, is_parameterization_forced
  5608. FROM master.sys.databases (NOLOCK)
  5609. WHERE database_id > 4 OR name = ''model'''
  5610. END;
  5611. INSERT INTO @dbopterrtb
  5612. EXECUTE sp_executesql @sqlcmd;
  5613. SET @cnt = (SELECT COUNT(id) FROM @dbopterrtb)
  5614. SET @cnt_i = 1
  5615. 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
  5616. WHILE @cnt_i <> @cnt
  5617. BEGIN
  5618. 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,
  5619. @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,
  5620. @page_verify_option = CASE WHEN page_verify_option <> 2 AND @page_verify_option = 0 THEN 1 ELSE @page_verify_option END,
  5621. @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,
  5622. @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,
  5623. @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,
  5624. --@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,
  5625. @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,
  5626. @is_trustworthy_on = CASE WHEN is_trustworthy_on = 1 AND @is_trustworthy_on = 0 THEN 1 ELSE @is_trustworthy_on END,
  5627. @is_parameterization_forced = CASE WHEN is_parameterization_forced = 1 AND @is_parameterization_forced = 0 THEN 1 ELSE @is_parameterization_forced END
  5628. FROM @dbopterrtb
  5629. WHERE id = @cnt_i;
  5630. SET @cnt_i = @cnt_i + 1
  5631. END
  5632. 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
  5633. BEGIN
  5634. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Check], '[WARNING: Some user databases may have Non-optimal_Settings]' AS [Deviation]
  5635. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Information],
  5636. name AS [Database_Name],
  5637. RTRIM(
  5638. CASE WHEN is_auto_close_on = 1 THEN 'Auto_Close;' ELSE '' END +
  5639. CASE WHEN is_auto_shrink_on = 1 THEN 'Auto_Shrink;' ELSE '' END +
  5640. CASE WHEN page_verify_option <> 2 THEN 'Page_Verify;' ELSE '' END +
  5641. CASE WHEN is_auto_create_stats_on = 0 THEN 'Auto_Create_Stats;' ELSE '' END +
  5642. CASE WHEN is_auto_update_stats_on = 0 THEN 'Auto_Update_Stats;' ELSE '' END +
  5643. CASE WHEN is_db_chaining_on = 1 THEN 'DB_Chaining;' ELSE '' END +
  5644. --CASE WHEN is_indirect_checkpoint_on = 1 THEN 'Indirect_Checkpoint;' ELSE '' END +
  5645. CASE WHEN is_auto_create_stats_incremental_on = 0 THEN 'Incremental_Stats;' ELSE '' END +
  5646. CASE WHEN is_trustworthy_on = 1 THEN 'Trustworthy_bit;' ELSE '' END +
  5647. CASE WHEN is_parameterization_forced = 1 THEN 'Forced_Parameterization;' ELSE '' END
  5648. ) AS [Non-optimal_Settings],
  5649. CASE WHEN is_auto_close_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Close],
  5650. CASE WHEN is_auto_shrink_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Shrink],
  5651. page_verify_option_desc AS [Page_Verify],
  5652. CASE WHEN is_auto_create_stats_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Create_Stats],
  5653. CASE WHEN is_auto_update_stats_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Update_Stats],
  5654. CASE WHEN is_db_chaining_on = 1 THEN 'ON' ELSE 'OFF' END AS [DB_Chaining],
  5655. --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.
  5656. 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],
  5657. CASE WHEN is_trustworthy_on = 1 THEN 'ON' ELSE 'OFF' END AS [Trustworthy_bit],
  5658. CASE WHEN is_parameterization_forced = 1 THEN 'ON' ELSE 'OFF' END AS [Forced_Parameterization]
  5659. FROM @dbopterrtb
  5660. 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)
  5661. 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;
  5662. END
  5663. ELSE
  5664. BEGIN
  5665. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Check], '[OK]' AS [Deviation]
  5666. END;
  5667. IF (SELECT COUNT(*) FROM master.sys.databases (NOLOCK) WHERE is_auto_update_stats_on = 0 AND is_auto_update_stats_async_on = 1) > 0
  5668. BEGIN
  5669. 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]
  5670. 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
  5671. END
  5672. ELSE
  5673. BEGIN
  5674. SELECT 'Database_checks' AS [Category], 'Database_Options_Disabled_Async_AutoUpdate' AS [Check], '[OK]' AS [Deviation]
  5675. END;
  5676. --------------------------------------------------------------------------------------------------------------------------------
  5677. -- DBs with Sparse files subsection
  5678. --------------------------------------------------------------------------------------------------------------------------------
  5679. RAISERROR (N' |-Starting DBs with Sparse files', 10, 1) WITH NOWAIT
  5680. -- 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
  5681. -- http://blogs.msdn.com/b/jorgepc/archive/2010/11/25/what-are-sparse-files-and-why-should-i-care-as-sql-server-dba.aspx
  5682. 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
  5683. BEGIN
  5684. 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]
  5685. SELECT 'Database_checks' AS [Category], 'DB_nonSnap_Sparse' AS [Information], DB_NAME(sd.database_id) AS database_name, smf.name, smf.physical_name
  5686. FROM sys.databases sd
  5687. INNER JOIN sys.master_files smf ON sd.database_id = smf.database_id
  5688. WHERE sd.source_database_id IS NULL AND smf.is_sparse = 1
  5689. END
  5690. ELSE
  5691. BEGIN
  5692. SELECT 'Database_checks' AS [Category], 'DB_nonSnap_Sparse' AS [Check], '[OK]' AS [Deviation]
  5693. END;
  5694. --------------------------------------------------------------------------------------------------------------------------------
  5695. -- DBs Autogrow in percentage subsection
  5696. --------------------------------------------------------------------------------------------------------------------------------
  5697. RAISERROR (N' |-Starting DBs Autogrow in percentage', 10, 1) WITH NOWAIT
  5698. IF (SELECT COUNT(is_percent_growth) FROM sys.master_files WHERE is_percent_growth = 1) > 0
  5699. BEGIN
  5700. 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]
  5701. SELECT 'Database_checks' AS [Category], 'Percent_Autogrows' AS [Information], database_id,
  5702. DB_NAME(database_id) AS [Database_Name],
  5703. mf.name AS [Logical_Name],
  5704. mf.size*8 AS [Current_Size_KB],
  5705. mf.type_desc AS [File_Type],
  5706. mf.[state_desc] AS [File_State],
  5707. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  5708. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount_KB],
  5709. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((mf.size*8)*CONVERT(bigint, mf.growth))/100
  5710. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  5711. ELSE 0 END AS [Next_Growth_KB],
  5712. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  5713. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  5714. ELSE '' END AS [Comments],
  5715. mf.is_read_only
  5716. FROM sys.master_files mf (NOLOCK)
  5717. WHERE is_percent_growth = 1
  5718. 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
  5719. ORDER BY DB_NAME(mf.database_id), mf.name
  5720. END
  5721. ELSE
  5722. BEGIN
  5723. SELECT 'Database_checks' AS [Category], 'Percent_Autogrows' AS [Check], '[OK]' AS [Deviation]
  5724. END;
  5725. --------------------------------------------------------------------------------------------------------------------------------
  5726. -- DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled) subsection
  5727. --------------------------------------------------------------------------------------------------------------------------------
  5728. RAISERROR (N' |-Starting DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled)', 10, 1) WITH NOWAIT
  5729. IF (SELECT COUNT(growth) FROM sys.master_files (NOLOCK)
  5730. WHERE [type] >= CASE WHEN @ifi = 1 THEN 1 ELSE 0 END
  5731. AND [type] < 2
  5732. AND ((is_percent_growth = 1 AND ((CONVERT(bigint,size)*8)*growth)/100 > 1048576)
  5733. OR (is_percent_growth = 0 AND growth*8 > 1048576))) > 0
  5734. BEGIN
  5735. 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]
  5736. SELECT 'Database_checks' AS [Category], 'Large_Autogrows' AS [Information], database_id,
  5737. DB_NAME(database_id) AS [Database_Name],
  5738. mf.name AS [Logical_Name],
  5739. mf.size*8 AS [Current_Size_KB],
  5740. mf.[type_desc] AS [File_Type],
  5741. mf.[state_desc] AS [File_State],
  5742. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  5743. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount],
  5744. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((CONVERT(bigint,mf.size)*8)*mf.growth)/100
  5745. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  5746. ELSE 0 END AS [Next_Growth_KB],
  5747. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  5748. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  5749. ELSE '' END AS [Comments],
  5750. mf.is_read_only
  5751. FROM sys.master_files mf (NOLOCK)
  5752. WHERE mf.[type] >= CASE WHEN @ifi = 1 THEN 1 ELSE 0 END
  5753. AND mf.[type] < 2
  5754. AND ((is_percent_growth = 1 AND ((CONVERT(bigint,mf.size)*8)*mf.growth)/100 > 1048576)
  5755. OR (is_percent_growth = 0 AND mf.growth*8 > 1048576))
  5756. 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
  5757. ORDER BY DB_NAME(mf.database_id), mf.name
  5758. END
  5759. ELSE
  5760. BEGIN
  5761. SELECT 'Database_checks' AS [Category], 'Large_Autogrows' AS [Check], '[OK]' AS [Deviation]
  5762. END;
  5763. --------------------------------------------------------------------------------------------------------------------------------
  5764. -- VLF subsection
  5765. --------------------------------------------------------------------------------------------------------------------------------
  5766. RAISERROR (N' |-Starting VLF', 10, 1) WITH NOWAIT
  5767. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1
  5768. BEGIN
  5769. 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)
  5770. DECLARE @potsize DECIMAL(20,1), @n_iter int, @n_iter_final int, @initgrow DECIMAL(20,1), @n_init_iter int
  5771. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  5772. DROP TABLE #log_info1;
  5773. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  5774. CREATE TABLE #log_info1 (dbname VARCHAR(100),
  5775. Current_log_size_MB DECIMAL(20,1),
  5776. Used_Log_size_MB DECIMAL(20,1),
  5777. Potential_log_size_MB DECIMAL(20,1),
  5778. Current_VLFs int,
  5779. Used_VLFs int,
  5780. Avg_VLF_size_KB DECIMAL(20,1),
  5781. Potential_VLFs int,
  5782. Growth_iterations int,
  5783. Log_Initial_size_MB DECIMAL(20,1),
  5784. File_autogrow_MB DECIMAL(20,1))
  5785. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  5786. DROP TABLE #log_info2;
  5787. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  5788. CREATE TABLE #log_info2 (dbname VARCHAR(100),
  5789. Current_VLFs int,
  5790. VLF_size_KB DECIMAL(20,1),
  5791. growth_iteration int)
  5792. UPDATE #tmpdbs0
  5793. SET isdone = 0;
  5794. UPDATE #tmpdbs0
  5795. SET isdone = 1
  5796. WHERE [state] <> 0;
  5797. UPDATE #tmpdbs0
  5798. SET isdone = 1
  5799. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  5800. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  5801. BEGIN
  5802. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  5803. BEGIN
  5804. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  5805. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info3'))
  5806. DROP TABLE #log_info3;
  5807. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info3'))
  5808. CREATE TABLE #log_info3 (recoveryunitid int NULL,
  5809. fileid tinyint,
  5810. file_size bigint,
  5811. start_offset bigint,
  5812. FSeqNo int,
  5813. [status] tinyint,
  5814. parity tinyint,
  5815. create_lsn numeric(25,0))
  5816. SET @query = 'DBCC LOGINFO (' + '''' + @dbname + ''') WITH NO_INFOMSGS'
  5817. IF @sqlmajorver < 11
  5818. BEGIN
  5819. INSERT INTO #log_info3 (fileid, file_size, start_offset, FSeqNo, [status], parity, create_lsn)
  5820. EXEC (@query)
  5821. END
  5822. ELSE
  5823. BEGIN
  5824. INSERT INTO #log_info3 (recoveryunitid, fileid, file_size, start_offset, FSeqNo, [status], parity, create_lsn)
  5825. EXEC (@query)
  5826. END
  5827. SET @count = @@ROWCOUNT
  5828. SET @count_used = (SELECT COUNT(fileid) FROM #log_info3 l WHERE l.[status] = 2)
  5829. SET @logsize = (SELECT (MIN(l.start_offset) + SUM(l.file_size))/1048576.00 FROM #log_info3 l)
  5830. 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)
  5831. SET @avgvlfsize = (SELECT AVG(l.file_size)/1024.00 FROM #log_info3 l)
  5832. INSERT INTO #log_info2
  5833. SELECT @dbname, COUNT(create_lsn), MIN(l.file_size)/1024.00,
  5834. ROW_NUMBER() OVER(ORDER BY l.create_lsn) FROM #log_info3 l
  5835. GROUP BY l.create_lsn
  5836. ORDER BY l.create_lsn
  5837. DROP TABLE #log_info3;
  5838. -- Grow logs in MB instead of GB because of known issue prior to SQL 2012.
  5839. -- More detail here: http://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx
  5840. -- and http://connect.microsoft.com/SQLServer/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately
  5841. -- or https://connect.microsoft.com/SQLServer/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb
  5842. IF @sqlmajorver >= 11
  5843. BEGIN
  5844. SET @n_iter = (SELECT CASE WHEN @logsize <= 64 THEN 1
  5845. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)
  5846. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)
  5847. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)
  5848. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)
  5849. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4096, 0)
  5850. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8192, 0)
  5851. END)
  5852. SET @potsize = (SELECT CASE WHEN @logsize <= 64 THEN 1*64
  5853. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)*256
  5854. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)*512
  5855. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)*1024
  5856. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)*2048
  5857. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4096, 0)*4096
  5858. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8192, 0)*8192
  5859. END)
  5860. END
  5861. ELSE
  5862. BEGIN
  5863. SET @n_iter = (SELECT CASE WHEN @logsize <= 64 THEN 1
  5864. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)
  5865. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)
  5866. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)
  5867. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)
  5868. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4000, 0)
  5869. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8000, 0)
  5870. END)
  5871. SET @potsize = (SELECT CASE WHEN @logsize <= 64 THEN 1*64
  5872. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)*256
  5873. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)*512
  5874. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)*1024
  5875. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)*2048
  5876. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4000, 0)*4000
  5877. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8000, 0)*8000
  5878. END)
  5879. END
  5880. -- If the proposed log size is smaller than current log, and also smaller than 4GB,
  5881. -- and there is less than 512MB of diff between the current size and proposed size, add 1 grow.
  5882. SET @n_iter_final = @n_iter
  5883. IF @logsize > @potsize AND @potsize <= 4096 AND ABS(@logsize - @potsize) < 512
  5884. BEGIN
  5885. SET @n_iter_final = @n_iter + 1
  5886. END
  5887. -- If the proposed log size is larger than current log, and also larger than 50GB,
  5888. -- and there is less than 1GB of diff between the current size and proposed size, take 1 grow.
  5889. ELSE IF @logsize < @potsize AND @potsize <= 51200 AND ABS(@logsize - @potsize) > 1024
  5890. BEGIN
  5891. SET @n_iter_final = @n_iter - 1
  5892. END
  5893. IF @potsize = 0
  5894. BEGIN
  5895. SET @potsize = 64
  5896. END
  5897. IF @n_iter = 0
  5898. BEGIN
  5899. SET @n_iter = 1
  5900. END
  5901. SET @potsize = (SELECT CASE WHEN @n_iter < @n_iter_final THEN @potsize + (@potsize/@n_iter)
  5902. WHEN @n_iter > @n_iter_final THEN @potsize - (@potsize/@n_iter)
  5903. ELSE @potsize END)
  5904. SET @n_init_iter = @n_iter_final
  5905. IF @potsize >= 8192
  5906. BEGIN
  5907. SET @initgrow = @potsize/@n_iter_final
  5908. END
  5909. IF @potsize >= 64 AND @potsize <= 512
  5910. BEGIN
  5911. SET @n_init_iter = 1
  5912. SET @initgrow = 512
  5913. END
  5914. IF @potsize > 512 AND @potsize <= 1024
  5915. BEGIN
  5916. SET @n_init_iter = 1
  5917. SET @initgrow = 1023
  5918. END
  5919. IF @potsize > 1024 AND @potsize < 8192
  5920. BEGIN
  5921. SET @n_init_iter = 1
  5922. SET @initgrow = @potsize
  5923. END
  5924. INSERT INTO #log_info1
  5925. VALUES(@dbname, @logsize, @usedlogsize, @potsize, @count, @count_used, @avgvlfsize,
  5926. CASE WHEN @potsize <= 64 THEN (@potsize/(@potsize/@n_init_iter))*4
  5927. WHEN @potsize > 64 AND @potsize < 1024 THEN (@potsize/(@potsize/@n_init_iter))*8
  5928. WHEN @potsize >= 1024 THEN (@potsize/(@potsize/@n_init_iter))*16
  5929. END,
  5930. @n_init_iter, @initgrow,
  5931. CASE WHEN (@potsize/@n_iter_final) <= 1024 THEN (@potsize/@n_iter_final) ELSE 1024 END
  5932. );
  5933. UPDATE #tmpdbs0
  5934. SET isdone = 1
  5935. WHERE [dbid] = @dbid
  5936. END
  5937. END;
  5938. IF (SELECT COUNT(dbname) FROM #log_info1 WHERE Current_VLFs >= 50) > 0
  5939. BEGIN
  5940. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Check], '[WARNING: Some user databases have many VLFs. Please review these]' AS [Deviation]
  5941. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Information], dbname AS [Database_Name], Current_log_size_MB, Used_Log_size_MB,
  5942. Potential_log_size_MB, Current_VLFs, Used_VLFs, Potential_VLFs, Growth_iterations, Log_Initial_size_MB, File_autogrow_MB
  5943. FROM #log_info1
  5944. WHERE Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5945. ORDER BY dbname;
  5946. 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
  5947. FROM #log_info2
  5948. INNER JOIN #log_info1 ON #log_info2.dbname = #log_info1.dbname
  5949. WHERE #log_info1.Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5950. ORDER BY #log_info2.dbname, growth_iteration
  5951. 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
  5952. FROM #log_info2
  5953. INNER JOIN #log_info1 ON #log_info2.dbname = #log_info1.dbname
  5954. WHERE #log_info1.Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5955. GROUP BY #log_info2.dbname, VLF_size_KB
  5956. ORDER BY #log_info2.dbname, VLF_size_KB DESC
  5957. END
  5958. ELSE
  5959. BEGIN
  5960. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Check], '[OK]' AS [Deviation]
  5961. /*
  5962. 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
  5963. FROM #log_info1
  5964. ORDER BY dbname;
  5965. 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
  5966. FROM #log_info2
  5967. ORDER BY dbname, growth_iteration
  5968. 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
  5969. FROM #log_info2
  5970. GROUP BY dbname, VLF_size_KB
  5971. ORDER BY dbname, VLF_size_KB DESC
  5972. */
  5973. END
  5974. END
  5975. ELSE
  5976. BEGIN
  5977. RAISERROR('[WARNING: Only a sysadmin can run the "VLF" check. Bypassing check]', 16, 1, N'sysadmin')
  5978. --RETURN
  5979. END;
  5980. --------------------------------------------------------------------------------------------------------------------------------
  5981. -- Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware) subsection
  5982. --------------------------------------------------------------------------------------------------------------------------------
  5983. RAISERROR (N' |-Starting Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware)', 10, 1) WITH NOWAIT
  5984. IF @allow_xpcmdshell = 1
  5985. BEGIN
  5986. DECLARE /*@dbid int,*/ @ctr2 int, @ctr3 int, @ctr4 int, @pserr bit
  5987. SET @pserr = 0
  5988. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  5989. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5990. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  5991. AND (SELECT COUNT(l.name)
  5992. FROM sys.server_permissions p (NOLOCK) INNER JOIN sys.server_principals l (NOLOCK)
  5993. ON p.grantee_principal_id = l.principal_id
  5994. AND p.class = 100 -- Server
  5995. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  5996. AND l.is_disabled = 0
  5997. AND p.permission_name = 'ALTER SETTINGS'
  5998. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  5999. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  6000. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  6001. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  6002. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  6003. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  6004. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  6005. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  6006. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  6007. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  6008. BEGIN
  6009. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild <= 2500)
  6010. BEGIN
  6011. DECLARE @pstbl TABLE ([KeyExist] int)
  6012. BEGIN TRY
  6013. INSERT INTO @pstbl
  6014. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\PowerShell\1' -- check if Powershell is installed
  6015. END TRY
  6016. BEGIN CATCH
  6017. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  6018. SELECT @ErrorMessage = 'Data files and Logs in same volume (Mountpoint aware) subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  6019. RAISERROR (@ErrorMessage, 16, 1);
  6020. END CATCH
  6021. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  6022. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  6023. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  6024. RAISERROR (' |-Configuration options set for Data and Log location check', 10, 1) WITH NOWAIT
  6025. IF @sao = 0
  6026. BEGIN
  6027. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  6028. END
  6029. IF @xcmd = 0
  6030. BEGIN
  6031. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  6032. END
  6033. IF @ole = 0
  6034. BEGIN
  6035. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  6036. END
  6037. IF (SELECT [KeyExist] FROM @pstbl) = 1
  6038. BEGIN
  6039. DECLARE @ctr int
  6040. DECLARE @output_hw_tot TABLE ([PS_OUTPUT] NVARCHAR(2048));
  6041. DECLARE @output_hw_format TABLE ([volid] smallint IDENTITY(1,1), [HD_Volume] NVARCHAR(2048) NULL)
  6042. IF @custompath IS NULL
  6043. BEGIN
  6044. IF @sqlmajorver < 11
  6045. BEGIN
  6046. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  6047. SET @path = @path + '\LOG'
  6048. END
  6049. ELSE
  6050. BEGIN
  6051. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  6052. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  6053. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  6054. END
  6055. -- Create COM object with FSO
  6056. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  6057. IF @OLEResult <> 0
  6058. BEGIN
  6059. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  6060. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  6061. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6062. END
  6063. ELSE
  6064. BEGIN
  6065. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  6066. IF @OLEResult <> 0
  6067. BEGIN
  6068. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  6069. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  6070. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6071. END
  6072. ELSE
  6073. BEGIN
  6074. IF @existout <> 1
  6075. BEGIN
  6076. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  6077. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  6078. END
  6079. END
  6080. EXEC @OLEResult = sp_OADestroy @FSO
  6081. END
  6082. END
  6083. ELSE
  6084. BEGIN
  6085. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  6086. END
  6087. SET @FileName = @path + '\checkbp_' + RTRIM(@server) + '.ps1'
  6088. EXEC master.dbo.xp_fileexist @FileName, @existout out
  6089. IF @existout = 0
  6090. BEGIN
  6091. -- Scan for local disks
  6092. SET @Text1 = '[string] $serverName = ''localhost''
  6093. $vols = Get-WmiObject -computername $serverName -query "select Name from Win32_Volume where Capacity <> NULL and DriveType = 3"
  6094. foreach($vol in $vols)
  6095. {
  6096. [string] $drive = "{0}" -f $vol.name
  6097. Write-Output $drive
  6098. }'
  6099. -- Create COM object with FSO
  6100. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  6101. IF @OLEResult <> 0
  6102. BEGIN
  6103. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6104. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  6105. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6106. END
  6107. --Open file
  6108. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  6109. IF @OLEResult <> 0
  6110. BEGIN
  6111. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6112. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  6113. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6114. END
  6115. ELSE
  6116. BEGIN
  6117. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  6118. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6119. END
  6120. --Write Text1
  6121. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  6122. IF @OLEResult <> 0
  6123. BEGIN
  6124. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6125. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  6126. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6127. END
  6128. EXEC @OLEResult = sp_OADestroy @FileID
  6129. EXEC @OLEResult = sp_OADestroy @FS
  6130. END;
  6131. ELSE
  6132. BEGIN
  6133. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  6134. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6135. END
  6136. IF @psver = 1
  6137. BEGIN
  6138. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  6139. END
  6140. ELSE
  6141. BEGIN
  6142. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  6143. END;
  6144. INSERT INTO @output_hw_tot
  6145. EXEC master.dbo.xp_cmdshell @CMD
  6146. SET @CMD = 'del /Q "' + @FileName + '"'
  6147. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  6148. IF (SELECT COUNT([PS_OUTPUT])
  6149. FROM @output_hw_tot WHERE [PS_OUTPUT] LIKE '%cannot be loaded because%'
  6150. OR [PS_OUTPUT] LIKE '%scripts is disabled%'
  6151. OR [PS_OUTPUT] LIKE '%scripts est désactivée%') = 0
  6152. BEGIN
  6153. INSERT INTO @output_hw_format ([HD_Volume])
  6154. SELECT RTRIM([PS_OUTPUT])
  6155. FROM @output_hw_tot
  6156. WHERE [PS_OUTPUT] IS NOT NULL
  6157. END
  6158. ELSE
  6159. BEGIN
  6160. SET @pserr = 1
  6161. RAISERROR ('[WARNING: Powershell script cannot be loaded because the execution of scripts is disabled on this system.
  6162. To change the execution policy, type the following command in Powershell console: Set-ExecutionPolicy RemoteSigned
  6163. The Set-ExecutionPolicy cmdlet enables you to determine which Windows PowerShell scripts (if any) will be allowed to run on your computer.
  6164. Windows PowerShell has four different execution policies:
  6165. Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  6166. AllSigned - Only scripts signed by a trusted publisher can be run.
  6167. RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  6168. |- REQUIRED by BP Check
  6169. Unrestricted - No restrictions; all Windows PowerShell scripts can be run.]
  6170. ',16,1);
  6171. END
  6172. SET @CMD2 = 'del ' + @FileName
  6173. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  6174. END
  6175. ELSE
  6176. BEGIN
  6177. SET @pserr = 1
  6178. RAISERROR ('[WARNING: Powershell is not present. Bypassing Data files and Logs in same volume check]',16,1);
  6179. END
  6180. IF @xcmd = 0
  6181. BEGIN
  6182. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  6183. END
  6184. IF @ole = 0
  6185. BEGIN
  6186. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  6187. END
  6188. IF @sao = 0
  6189. BEGIN
  6190. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  6191. END
  6192. END
  6193. ELSE
  6194. BEGIN
  6195. INSERT INTO @output_hw_format ([HD_Volume])
  6196. 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')
  6197. END;
  6198. IF @pserr = 0
  6199. BEGIN
  6200. -- select mountpoints only
  6201. DECLARE @intertbl TABLE (physical_name nvarchar(260))
  6202. INSERT INTO @intertbl
  6203. SELECT physical_name
  6204. FROM sys.master_files t1 (NOLOCK)
  6205. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6206. WHERE ([database_id] > 4 OR [database_id] = 2)
  6207. AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3
  6208. -- select database files in mountpoints
  6209. DECLARE @filetbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6210. INSERT INTO @filetbl
  6211. SELECT database_id, type, file_id, physical_name, volid
  6212. FROM sys.master_files t1 (NOLOCK)
  6213. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6214. WHERE ([database_id] > 4 OR [database_id] = 2) AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3
  6215. UNION ALL
  6216. -- select database files not in mountpoints
  6217. SELECT database_id, type, file_id, physical_name, volid
  6218. FROM sys.master_files t1 (NOLOCK)
  6219. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6220. WHERE ([database_id] > 4 OR [database_id] = 2) AND [database_id] <> 32767 AND physical_name NOT IN (SELECT physical_name FROM @intertbl)
  6221. SELECT @ctr = COUNT(DISTINCT(t1.[database_id])) FROM @filetbl t1
  6222. INNER JOIN @filetbl t2 ON t1.database_id = t2.database_id
  6223. AND t1.[type] <> t2.[type]
  6224. AND ((t1.[type] = 1 AND t2.[type] <> 1) OR (t2.[type] = 1 AND t1.[type] <> 1))
  6225. AND t1.volid = t2.volid;
  6226. IF @ctr > 0
  6227. BEGIN
  6228. 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]
  6229. 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
  6230. FROM sys.master_files mf (NOLOCK) INNER JOIN @filetbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6231. INNER JOIN @filetbl t2 ON t1.database_id = t2.database_id
  6232. AND t1.[type] <> t2.[type]
  6233. AND ((t1.[type] = 1 AND t2.[type] <> 1) OR (t2.[type] = 1 AND t1.[type] <> 1))
  6234. AND t1.volid = t2.volid
  6235. ORDER BY mf.physical_name OPTION (RECOMPILE);
  6236. END
  6237. ELSE
  6238. BEGIN
  6239. SELECT 'Database_checks' AS [Category], 'Data_and_Log_locations' AS [Check], '[OK]' AS [Deviation]
  6240. END;
  6241. -- select backup mountpoints only
  6242. DECLARE @interbcktbl TABLE (physical_device_name nvarchar(260))
  6243. INSERT INTO @interbcktbl
  6244. SELECT physical_device_name
  6245. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6246. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6247. WHERE LEN(t2.HD_Volume) > 3
  6248. -- select backups in mountpoints only
  6249. DECLARE @bcktbl TABLE (physical_device_name nvarchar(260), HD_Volume nvarchar(260))
  6250. INSERT INTO @bcktbl
  6251. SELECT physical_device_name, RTRIM(t2.HD_Volume)
  6252. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6253. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6254. WHERE LEN(t2.HD_Volume) > 3
  6255. -- select backups not in mountpoints
  6256. UNION ALL
  6257. SELECT physical_device_name, RTRIM(t2.HD_Volume)
  6258. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6259. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6260. WHERE physical_device_name NOT IN (SELECT physical_device_name FROM @interbcktbl);
  6261. SELECT @ctr4 = COUNT(DISTINCT(physical_device_name)) FROM @bcktbl;
  6262. IF @ctr4 > 0
  6263. BEGIN
  6264. 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]
  6265. 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]
  6266. FROM @bcktbl
  6267. OPTION (RECOMPILE);
  6268. END
  6269. ELSE
  6270. BEGIN
  6271. SELECT 'Database_checks' AS [Category], 'Backup_and_Database_locations' AS [Check], '[OK]' AS [Deviation]
  6272. END;
  6273. -- select tempDB mountpoints only
  6274. DECLARE @intertbl2 TABLE (physical_name nvarchar(260))
  6275. INSERT INTO @intertbl2
  6276. SELECT physical_name
  6277. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2
  6278. ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6279. WHERE [database_id] = 2 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6280. -- select user DBs mountpoints only
  6281. DECLARE @intertbl3 TABLE (physical_name nvarchar(260))
  6282. INSERT INTO @intertbl3
  6283. SELECT physical_name
  6284. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2
  6285. ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6286. WHERE [database_id] > 4 AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6287. -- select tempDB files in mountpoints
  6288. DECLARE @tempDBtbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6289. INSERT INTO @tempDBtbl
  6290. SELECT database_id, type, file_id, physical_name, volid
  6291. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6292. WHERE [database_id] = 2 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6293. UNION ALL
  6294. SELECT database_id, type, file_id, physical_name, volid
  6295. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6296. WHERE [database_id] = 2 AND [type] = 0 AND physical_name NOT IN (SELECT physical_name FROM @intertbl2)
  6297. -- select user DBs files in mountpoints
  6298. DECLARE @otherstbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6299. INSERT INTO @otherstbl
  6300. SELECT database_id, type, file_id, physical_name, volid
  6301. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6302. WHERE [database_id] > 4 AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6303. UNION ALL
  6304. SELECT database_id, type, file_id, physical_name, volid
  6305. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6306. WHERE [database_id] > 4 AND [database_id] <> 32767 AND [type] = 0 AND physical_name NOT IN (SELECT physical_name FROM @intertbl3)
  6307. SELECT @ctr2 = COUNT(*) FROM @tempDBtbl WHERE LEFT(physical_name, 1) = 'C'
  6308. SELECT @ctr3 = COUNT(DISTINCT(t1.[database_id])) FROM @otherstbl t1 INNER JOIN @tempDBtbl t2 ON t1.volid = t2.volid;
  6309. IF @ctr3 > 0
  6310. BEGIN
  6311. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: tempDB is on the same physical volume as user databases]' AS [Deviation];
  6312. END
  6313. ELSE IF @ctr2 > 0
  6314. BEGIN
  6315. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: tempDB is on C: drive]' AS [Deviation]
  6316. END
  6317. ELSE
  6318. BEGIN
  6319. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[OK]' AS [Deviation]
  6320. END;
  6321. IF @ctr2 > 0 OR @ctr3 > 0
  6322. BEGIN
  6323. 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
  6324. FROM sys.master_files mf (NOLOCK) INNER JOIN @otherstbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6325. INNER JOIN @tempDBtbl t2 ON t1.volid = t2.volid
  6326. UNION ALL
  6327. 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
  6328. FROM sys.master_files mf (NOLOCK) INNER JOIN @tempDBtbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6329. ORDER BY DB_NAME(mf.[database_id]) OPTION (RECOMPILE);
  6330. END
  6331. END
  6332. ELSE
  6333. BEGIN
  6334. SELECT 'Database_checks' AS [Category], 'Data_and_Log_locations' AS [Check], '[WARNING: Could not gather information on file locations]' AS [Deviation]
  6335. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: Could not gather information on file locations]' AS [Deviation]
  6336. END
  6337. END
  6338. ELSE
  6339. BEGIN
  6340. 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')
  6341. 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')
  6342. --RETURN
  6343. END
  6344. END
  6345. ELSE
  6346. BEGIN
  6347. 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')
  6348. --RETURN
  6349. END;
  6350. --------------------------------------------------------------------------------------------------------------------------------
  6351. -- tempDB data file configurations subsection
  6352. --------------------------------------------------------------------------------------------------------------------------------
  6353. RAISERROR (N' |-Starting tempDB data file configurations', 10, 1) WITH NOWAIT
  6354. DECLARE @tdb_files int, @online_count int, @filesizes smallint
  6355. SELECT @tdb_files = COUNT(physical_name) FROM sys.master_files (NOLOCK) WHERE database_id = 2 AND [type] = 0;
  6356. SELECT @online_count = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE is_online = 1 AND scheduler_id < 255 AND parent_node_id < 64;
  6357. SELECT @filesizes = COUNT(DISTINCT size) FROM tempdb.sys.database_files WHERE [type] = 0;
  6358. 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)*/
  6359. OR (@tdb_files >= (@online_count / 2) AND @tdb_files >= 8 AND @tdb_files % 4 = 0)) THEN 0 ELSE 1 END) = 0
  6360. BEGIN
  6361. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Check], '[OK]' AS [Deviation]
  6362. 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]
  6363. FROM tempdb.sys.database_files (NOLOCK)
  6364. WHERE type = 0;
  6365. END
  6366. ELSE
  6367. BEGIN
  6368. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Check],
  6369. 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]'
  6370. 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]'
  6371. 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]'
  6372. WHEN @filesizes = 1 AND @tdb_files >= 4 AND @tdb_files % 4 > 0 THEN '[WARNING: Number of data files is not multiple of 4]'
  6373. WHEN @filesizes > 1 AND @tdb_files >= 4 AND @tdb_files % 4 = 0 THEN '[WARNING: Data file sizes do not match]'
  6374. ELSE '[OK]' END AS [Deviation];
  6375. 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]
  6376. FROM tempdb.sys.database_files (NOLOCK)
  6377. WHERE type = 0;
  6378. END;
  6379. --------------------------------------------------------------------------------------------------------------------------------
  6380. -- tempDB data files autogrow of equal size subsection
  6381. --------------------------------------------------------------------------------------------------------------------------------
  6382. RAISERROR (N' |-Starting tempDB Files autogrow of equal size', 10, 1) WITH NOWAIT
  6383. IF (SELECT COUNT(DISTINCT growth) FROM sys.master_files WHERE [database_id] = 2 AND [type] = 0) > 1
  6384. OR (SELECT COUNT(DISTINCT is_percent_growth) FROM sys.master_files WHERE [database_id] = 2 AND [type] = 0) > 1
  6385. BEGIN
  6386. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Check], '[WARNING: Some tempDB data files have different growth settings]' AS [Deviation]
  6387. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Information],
  6388. DB_NAME(2) AS [Database_Name],
  6389. mf.name AS [Logical_Name],
  6390. mf.[size]*8 AS [Current_Size_KB],
  6391. mf.type_desc AS [File_Type],
  6392. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  6393. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount],
  6394. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((mf.size*8)*CONVERT(bigint, mf.growth))/100
  6395. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  6396. ELSE 0 END AS [Next_Growth_KB],
  6397. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  6398. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  6399. ELSE '' END AS [Comments]
  6400. FROM tempdb.sys.database_files mf (NOLOCK)
  6401. WHERE [type] = 0
  6402. GROUP BY mf.name, mf.[size], is_percent_growth, mf.growth, mf.type_desc, mf.[type]
  6403. ORDER BY 3, 4
  6404. END
  6405. ELSE
  6406. BEGIN
  6407. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Check], '[OK]' AS [Deviation]
  6408. END;
  6409. IF @ptochecks = 1
  6410. RAISERROR (N'|-Starting Performance Checks', 10, 1) WITH NOWAIT
  6411. --------------------------------------------------------------------------------------------------------------------------------
  6412. -- Perf counters, Waits, Latches and Spinlocks subsection
  6413. --------------------------------------------------------------------------------------------------------------------------------
  6414. IF @ptochecks = 1
  6415. BEGIN
  6416. SELECT @ErrorMessage = ' |-Starting Perf counters, Waits and Latches (wait for ' + CONVERT(VARCHAR(3), @duration) + 's)'
  6417. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6418. DECLARE @minctr DATETIME, @maxctr DATETIME, @durationstr NVARCHAR(24)
  6419. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  6420. DROP TABLE #tblPerfCount;
  6421. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  6422. CREATE TABLE #tblPerfCount (
  6423. [retrieval_time] [datetime],
  6424. [object_name] [NVARCHAR](128),
  6425. [counter_name] [NVARCHAR](128),
  6426. [instance_name] [NVARCHAR](128),
  6427. [counter_name_type] int,
  6428. [cntr_value] float NULL
  6429. );
  6430. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  6431. DROP TABLE tempdb.dbo.tblPerfThresholds;
  6432. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  6433. CREATE TABLE tempdb.dbo.tblPerfThresholds (
  6434. [counter_family] [NVARCHAR](128),
  6435. [counter_name] [NVARCHAR](128),
  6436. [counter_instance] [NVARCHAR](128),
  6437. [counter_name_type] int,
  6438. [counter_value] float NULL
  6439. );
  6440. -- Create the helper function
  6441. 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')
  6442. EXEC ('USE tempdb; EXEC(''
  6443. CREATE FUNCTION dbo.fn_perfctr (@ctr1Fam NVARCHAR(128), @ctr1 NVARCHAR(128))
  6444. RETURNS float
  6445. AS
  6446. BEGIN
  6447. DECLARE @ReturnVals float, @ctr1Val float, @ctr2Val float, @ctr2Fam NVARCHAR(128), @ctr2 NVARCHAR(128), @type tinyint
  6448. -- ctr1Fam = source counter object; ctr1 = source counter; ctr2Fam = counter object to compare with; ctr2 = counter to compare with
  6449. -- 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
  6450. IF @ctr1 IN (''''Forwarded Records/sec'''',''''FreeSpace Scans/sec'''',''''Page Splits/sec'''',''''Workfiles Created/sec'''',''''Page lookups/sec'''',''''SQL Compilations/sec'''')
  6451. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''Batch Requests/sec'''', @type = 1
  6452. ELSE IF @ctr1 = ''''Lock Requests/sec''''
  6453. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''Batch Requests/sec'''', @type = 0
  6454. ELSE IF @ctr1 = ''''Full Scans/sec''''
  6455. SELECT @ctr2Fam = ''''SQLServer:Access Methods'''', @ctr2 = ''''Index Searches/sec'''', @type = 1
  6456. ELSE IF @ctr1 = ''''Index Searches/sec''''
  6457. SELECT @ctr2Fam = ''''SQLServer:Access Methods'''', @ctr2 = ''''Full Scans/sec'''', @type = 3
  6458. ELSE IF @ctr1 = ''''Readahead pages/sec''''
  6459. SELECT @ctr2Fam = ''''SQLServer:Buffer Manager'''', @ctr2 = ''''Page reads/sec'''', @type = 1
  6460. ELSE IF @ctr1 = ''''Target Server Memory (KB)''''
  6461. SELECT @ctr2Fam = ''''SQLServer:Memory Manager'''', @ctr2 = ''''Total Server Memory (KB)'''', @type = 2
  6462. ELSE IF @ctr1 = ''''SQL Re-Compilations/sec''''
  6463. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''SQL Compilations/sec'''', @type = 1
  6464. ELSE IF @ctr1 = ''''Page writes/sec''''
  6465. SELECT @ctr2Fam = ''''SQLServer:Buffer Manager'''', @ctr2 = ''''Page reads/sec'''', @type = 3
  6466. SELECT @ctr1Val = [counter_value] FROM tempdb.dbo.tblPerfThresholds WHERE [counter_family] = @ctr1Fam AND [counter_name] = @ctr1
  6467. SELECT @ctr2Val = [counter_value] FROM tempdb.dbo.tblPerfThresholds WHERE [counter_family] = @ctr2Fam AND [counter_name] = @ctr2
  6468. IF @ctr1 = ''''Target Server Memory (KB)''''
  6469. SELECT @ctr1Val = @ctr1Val / 1024, @ctr2Val = @ctr2Val / 1024
  6470. --Find ratio between counter 1 and 2
  6471. IF @ctr1Val IS NULL OR @ctr2Val IS NULL
  6472. BEGIN
  6473. SELECT @ReturnVals = NULL
  6474. END
  6475. ELSE IF @ctr1Val > 1 AND @ctr2Val > 1
  6476. BEGIN
  6477. IF @type = 0
  6478. SELECT @ReturnVals = (@ctr1Val / @ctr2Val)
  6479. IF @type = 1
  6480. SELECT @ReturnVals = (@ctr1Val / @ctr2Val) * 100
  6481. If @type = 2
  6482. SELECT @ReturnVals = (@ctr1Val - @ctr2Val)
  6483. IF @type = 3
  6484. SELECT @ReturnVals = (@ctr2Val / @ctr1Val) * 100
  6485. END
  6486. ELSE
  6487. BEGIN
  6488. SELECT @ReturnVals = 0
  6489. END
  6490. RETURN (@ReturnVals)
  6491. END'')
  6492. ')
  6493. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  6494. DROP TABLE #tblWaits;
  6495. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  6496. CREATE TABLE [dbo].[#tblWaits](
  6497. [retrieval_time] [datetime],
  6498. [wait_type] [nvarchar](60) NOT NULL,
  6499. [wait_time_ms] bigint NULL,
  6500. [signal_wait_time_ms] bigint NULL,
  6501. [resource_wait_time_ms] bigint NULL
  6502. );
  6503. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  6504. DROP TABLE #tblFinalWaits;
  6505. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  6506. CREATE TABLE [dbo].[#tblFinalWaits](
  6507. [wait_type] [nvarchar](60) NOT NULL,
  6508. [wait_time_s] [numeric](16, 6) NULL,
  6509. [signal_wait_time_s] [numeric](16, 6) NULL,
  6510. [resource_wait_time_s] [numeric](16, 6) NULL,
  6511. [pct] [numeric](12, 2) NULL,
  6512. [rn] [bigint] NULL,
  6513. [signal_wait_pct] [numeric](12, 2) NULL,
  6514. [resource_wait_pct] [numeric](12, 2) NULL
  6515. );
  6516. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  6517. DROP TABLE #tblLatches;
  6518. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  6519. CREATE TABLE [dbo].[#tblLatches](
  6520. [retrieval_time] [datetime],
  6521. [latch_class] [nvarchar](60) NOT NULL,
  6522. [wait_time_ms] bigint NULL,
  6523. [waiting_requests_count] [bigint] NULL
  6524. );
  6525. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  6526. DROP TABLE #tblFinalLatches;
  6527. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  6528. CREATE TABLE [dbo].[#tblFinalLatches](
  6529. [latch_class] [nvarchar](60) NOT NULL,
  6530. [wait_time_s] [decimal](16, 6) NULL,
  6531. [waiting_requests_count] [bigint] NULL,
  6532. [pct] [decimal](12, 2) NULL,
  6533. [rn] [bigint] NULL
  6534. );
  6535. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  6536. DROP TABLE #tblSpinlocksBefore;
  6537. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  6538. CREATE TABLE [dbo].[#tblSpinlocksBefore](
  6539. [name] NVARCHAR(512) NOT NULL,
  6540. [collisions] bigint NULL,
  6541. [spins] bigint NULL,
  6542. [spins_per_collision] real NULL,
  6543. [sleep_time] bigint NULL,
  6544. [backoffs] int NULL
  6545. );
  6546. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  6547. DROP TABLE #tblSpinlocksAfter;
  6548. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  6549. CREATE TABLE [dbo].[#tblSpinlocksAfter](
  6550. [name] NVARCHAR(512) NOT NULL,
  6551. [collisions] bigint NULL,
  6552. [spins] bigint NULL,
  6553. [spins_per_collision] real NULL,
  6554. [sleep_time] bigint NULL,
  6555. [backoffs] int NULL
  6556. );
  6557. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  6558. DROP TABLE #tblFinalSpinlocks;
  6559. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  6560. CREATE TABLE [dbo].[#tblFinalSpinlocks](
  6561. [name] NVARCHAR(512) NOT NULL,
  6562. [collisions] bigint NULL,
  6563. [spins] bigint NULL,
  6564. [spins_per_collision] real NULL,
  6565. [sleep_time] bigint NULL,
  6566. [backoffs] int NULL,
  6567. [spins_pct] [decimal](12, 2) NULL,
  6568. [rn] [bigint] NULL
  6569. );
  6570. SELECT @minctr = GETDATE()
  6571. -- When counter type = 272696576 (find delta from two collection points)
  6572. -- When counter type = 65792 (face value)
  6573. -- When counter type = 1073939712 (base value, check next counter types)
  6574. -- When counter type = 1073874176 (find delta from current value and base value between two collection points). Base value is counter with type 1073939712.
  6575. -- When counter type = 537003264 (find delta from current value and base value). Base value is counter with type 1073939712.
  6576. INSERT INTO #tblPerfCount
  6577. SELECT @minctr, [object_name], counter_name, instance_name, cntr_type AS counter_name_type, cntr_value
  6578. FROM sys.dm_os_performance_counters pc0 (NOLOCK)
  6579. WHERE ([object_name] LIKE '%:Access Methods%'
  6580. OR [object_name] LIKE '%:Buffer Manager%'
  6581. OR [object_name] LIKE '%:Buffer Node%'
  6582. OR [object_name] LIKE '%:Latches%'
  6583. OR [object_name] LIKE '%:Locks%'
  6584. OR [object_name] LIKE '%:Memory Manager%'
  6585. OR [object_name] LIKE '%:Memory Node%'
  6586. OR [object_name] LIKE '%:Plan Cache%'
  6587. OR [object_name] LIKE '%:SQL Statistics%'
  6588. OR [object_name] LIKE '%:Wait Statistics%'
  6589. OR [object_name] LIKE '%:Workload Group Stats%'
  6590. OR [object_name] LIKE '%:Memory Broker Clerks%'
  6591. OR [object_name] LIKE '%:Databases%'
  6592. OR [object_name] LIKE '%:Database Replica%')
  6593. AND (counter_name LIKE '%FreeSpace Scans/sec%'
  6594. OR counter_name LIKE '%Forwarded Records/sec%'
  6595. OR counter_name LIKE '%Full Scans/sec%'
  6596. OR counter_name LIKE '%Index Searches/sec%'
  6597. OR counter_name LIKE '%Page Splits/sec%'
  6598. OR counter_name LIKE '%Scan Point Revalidations/sec%'
  6599. OR counter_name LIKE '%Table Lock Escalations/sec%'
  6600. OR counter_name LIKE '%Workfiles Created/sec%'
  6601. OR counter_name LIKE '%Worktables Created/sec%'
  6602. OR counter_name LIKE '%Worktables From Cache%'
  6603. OR counter_name LIKE '%Buffer cache hit ratio%'
  6604. OR counter_name LIKE '%Buffer cache hit ratio base%'
  6605. OR counter_name LIKE '%Checkpoint pages/sec%'
  6606. OR counter_name LIKE '%Background writer pages/sec%'
  6607. OR counter_name LIKE '%Lazy writes/sec%'
  6608. OR counter_name LIKE '%Free pages%'
  6609. OR counter_name LIKE '%Page life expectancy%'
  6610. OR counter_name LIKE '%Page lookups/sec%'
  6611. OR counter_name LIKE '%Page reads/sec%'
  6612. OR counter_name LIKE '%Page writes/sec%'
  6613. OR counter_name LIKE '%Readahead pages/sec%'
  6614. OR counter_name LIKE '%Average Latch Wait Time (ms)%'
  6615. OR counter_name LIKE '%Average Latch Wait Time Base%'
  6616. OR counter_name LIKE '%Total Latch Wait Time (ms)%'
  6617. OR counter_name LIKE '%Average Wait Time (ms)%'
  6618. OR counter_name LIKE '%Average Wait Time Base%'
  6619. OR counter_name LIKE '%Number of Deadlocks/sec%'
  6620. OR counter_name LIKE '%Free Memory (KB)%'
  6621. OR counter_name LIKE '%Stolen Server Memory (KB)%'
  6622. OR counter_name LIKE '%Target Server Memory (KB)%'
  6623. OR counter_name LIKE '%Total Server Memory (KB)%'
  6624. OR counter_name LIKE '%Free Node Memory (KB)%'
  6625. OR counter_name LIKE '%Foreign Node Memory (KB)%'
  6626. OR counter_name LIKE '%Stolen Node Memory (KB)%'
  6627. OR counter_name LIKE '%Target Node Memory (KB)%'
  6628. OR counter_name LIKE '%Total Node Memory (KB)%'
  6629. OR counter_name LIKE '%Batch Requests/sec%'
  6630. OR counter_name LIKE '%SQL Compilations/sec%'
  6631. OR counter_name LIKE '%SQL Re-Compilations/sec%'
  6632. OR counter_name LIKE '%Lock waits%'
  6633. OR counter_name LIKE '%Log buffer waits%'
  6634. OR counter_name LIKE '%Log write waits%'
  6635. OR counter_name LIKE '%Memory grant queue waits%'
  6636. OR counter_name LIKE '%Network IO waits%'
  6637. OR counter_name LIKE '%Non-Page latch waits%'
  6638. OR counter_name LIKE '%Page IO latch waits%'
  6639. OR counter_name LIKE '%Page latch waits%'
  6640. OR counter_name LIKE '%Active parallel threads%'
  6641. OR counter_name LIKE '%Blocked tasks%'
  6642. OR counter_name LIKE '%CPU usage %'
  6643. OR counter_name LIKE '%CPU usage % base%'
  6644. OR counter_name LIKE '%Query optimizations/sec%'
  6645. OR counter_name LIKE '%Requests completed/sec%'
  6646. OR counter_name LIKE '%Suboptimal plans/sec%'
  6647. OR counter_name LIKE '%Temporary Tables & Table Variables%'
  6648. OR counter_name LIKE '%Extended Stored Procedures%'
  6649. OR counter_name LIKE '%Bound Trees%'
  6650. OR counter_name LIKE '%SQL Plans%'
  6651. OR counter_name LIKE '%Object Plans%'
  6652. OR counter_name LIKE '%_Total%'
  6653. OR counter_name LIKE 'Transactions/sec%'
  6654. OR counter_name LIKE '%Log Flush Wait Time%'
  6655. OR counter_name LIKE '%Log Flush Waits/sec%'
  6656. OR counter_name LIKE '%Recovery Queue%'
  6657. OR counter_name LIKE '%Log Send Queue%'
  6658. OR counter_name LIKE '%Transaction Delay%'
  6659. OR counter_name LIKE '%Redo blocked/sec%'
  6660. OR counter_name LIKE '%Resent Messages/sec%'
  6661. OR instance_name LIKE '%Buffer Pool%'
  6662. OR instance_name LIKE '%Column store object pool%');
  6663. INSERT INTO #tblWaits
  6664. SELECT @minctr, wait_type, wait_time_ms, signal_wait_time_ms,(wait_time_ms-signal_wait_time_ms) AS resource_wait_time_ms
  6665. FROM sys.dm_os_wait_stats (NOLOCK)
  6666. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
  6667. 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT',
  6668. 'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH',
  6669. 'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6670. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6671. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6672. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6673. AND wait_type NOT LIKE N'SLEEP_%'
  6674. AND wait_time_ms > 0;
  6675. INSERT INTO #tblLatches
  6676. SELECT @minctr, latch_class, wait_time_ms, waiting_requests_count
  6677. FROM sys.dm_os_latch_stats (NOLOCK)
  6678. WHERE /*latch_class NOT IN ('BUFFER')
  6679. AND*/ wait_time_ms > 0;
  6680. IF @sqlmajorver > 9
  6681. BEGIN
  6682. INSERT INTO #tblSpinlocksBefore
  6683. SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs
  6684. FROM sys.dm_os_spinlock_stats;
  6685. END
  6686. ELSE IF @sqlmajorver = 9
  6687. BEGIN
  6688. INSERT INTO #tblSpinlocksBefore
  6689. EXEC ('DBCC SQLPERF(''spinlockstats'')');
  6690. END;
  6691. IF @duration > 255
  6692. SET @duration = 255;
  6693. IF @duration < 10
  6694. SET @duration = 10;
  6695. SELECT @durationstr = 'WAITFOR DELAY ''00:' + CASE WHEN LEN(CONVERT(VARCHAR(3),@duration/60%60)) = 1
  6696. THEN '0' + CONVERT(VARCHAR(3),@duration/60%60)
  6697. ELSE CONVERT(VARCHAR(3),@duration/60%60) END
  6698. + ':' + CONVERT(VARCHAR(3),@duration-(@duration/60)*60) + ''''
  6699. EXECUTE sp_executesql @durationstr;
  6700. SELECT @maxctr = GETDATE()
  6701. INSERT INTO #tblPerfCount
  6702. SELECT @maxctr, [object_name], counter_name, instance_name, cntr_type AS counter_name_type, cntr_value
  6703. FROM sys.dm_os_performance_counters pc0 (NOLOCK)
  6704. WHERE (cntr_type = 272696576 OR cntr_type = 1073874176 OR cntr_type = 1073939712) -- Get only counters whose delta between collection points matters
  6705. AND ([object_name] LIKE '%:Access Methods%'
  6706. OR [object_name] LIKE '%:Buffer Manager%'
  6707. OR [object_name] LIKE '%:Buffer Node%'
  6708. OR [object_name] LIKE '%:Latches%'
  6709. OR [object_name] LIKE '%:Locks%'
  6710. OR [object_name] LIKE '%:Memory Manager%'
  6711. OR [object_name] LIKE '%:Memory Node%'
  6712. OR [object_name] LIKE '%:Plan Cache%'
  6713. OR [object_name] LIKE '%:SQL Statistics%'
  6714. OR [object_name] LIKE '%:Wait Statistics%'
  6715. OR [object_name] LIKE '%:Workload Group Stats%'
  6716. OR [object_name] LIKE '%:Memory Broker Clerks%'
  6717. OR [object_name] LIKE '%:Databases%'
  6718. OR [object_name] LIKE '%:Database Replica%')
  6719. AND (counter_name LIKE '%FreeSpace Scans/sec%'
  6720. OR counter_name LIKE '%Forwarded Records/sec%'
  6721. OR counter_name LIKE '%Full Scans/sec%'
  6722. OR counter_name LIKE '%Index Searches/sec%'
  6723. OR counter_name LIKE '%Page Splits/sec%'
  6724. OR counter_name LIKE '%Scan Point Revalidations/sec%'
  6725. OR counter_name LIKE '%Table Lock Escalations/sec%'
  6726. OR counter_name LIKE '%Workfiles Created/sec%'
  6727. OR counter_name LIKE '%Worktables Created/sec%'
  6728. OR counter_name LIKE '%Worktables From Cache%'
  6729. OR counter_name LIKE '%Buffer cache hit ratio%'
  6730. OR counter_name LIKE '%Buffer cache hit ratio base%'
  6731. OR counter_name LIKE '%Checkpoint pages/sec%'
  6732. OR counter_name LIKE '%Background writer pages/sec%'
  6733. OR counter_name LIKE '%Lazy writes/sec%'
  6734. OR counter_name LIKE '%Free pages%'
  6735. OR counter_name LIKE '%Page life expectancy%'
  6736. OR counter_name LIKE '%Page lookups/sec%'
  6737. OR counter_name LIKE '%Page reads/sec%'
  6738. OR counter_name LIKE '%Page writes/sec%'
  6739. OR counter_name LIKE '%Readahead pages/sec%'
  6740. OR counter_name LIKE '%Average Latch Wait Time (ms)%'
  6741. OR counter_name LIKE '%Average Latch Wait Time Base%'
  6742. OR counter_name LIKE '%Total Latch Wait Time (ms)%'
  6743. OR counter_name LIKE '%Average Wait Time (ms)%'
  6744. OR counter_name LIKE '%Average Wait Time Base%'
  6745. OR counter_name LIKE '%Number of Deadlocks/sec%'
  6746. OR counter_name LIKE '%Free Memory (KB)%'
  6747. OR counter_name LIKE '%Stolen Server Memory (KB)%'
  6748. OR counter_name LIKE '%Target Server Memory (KB)%'
  6749. OR counter_name LIKE '%Total Server Memory (KB)%'
  6750. OR counter_name LIKE '%Free Node Memory (KB)%'
  6751. OR counter_name LIKE '%Foreign Node Memory (KB)%'
  6752. OR counter_name LIKE '%Stolen Node Memory (KB)%'
  6753. OR counter_name LIKE '%Target Node Memory (KB)%'
  6754. OR counter_name LIKE '%Total Node Memory (KB)%'
  6755. OR counter_name LIKE '%Batch Requests/sec%'
  6756. OR counter_name LIKE '%SQL Compilations/sec%'
  6757. OR counter_name LIKE '%SQL Re-Compilations/sec%'
  6758. OR counter_name LIKE '%Lock waits%'
  6759. OR counter_name LIKE '%Log buffer waits%'
  6760. OR counter_name LIKE '%Log write waits%'
  6761. OR counter_name LIKE '%Memory grant queue waits%'
  6762. OR counter_name LIKE '%Network IO waits%'
  6763. OR counter_name LIKE '%Non-Page latch waits%'
  6764. OR counter_name LIKE '%Page IO latch waits%'
  6765. OR counter_name LIKE '%Page latch waits%'
  6766. OR counter_name LIKE '%Active parallel threads%'
  6767. OR counter_name LIKE '%Blocked tasks%'
  6768. OR counter_name LIKE '%CPU usage %'
  6769. OR counter_name LIKE '%CPU usage % base%'
  6770. OR counter_name LIKE '%Query optimizations/sec%'
  6771. OR counter_name LIKE '%Requests completed/sec%'
  6772. OR counter_name LIKE '%Suboptimal plans/sec%'
  6773. OR counter_name LIKE '%Temporary Tables & Table Variables%'
  6774. OR counter_name LIKE '%Extended Stored Procedures%'
  6775. OR counter_name LIKE '%Bound Trees%'
  6776. OR counter_name LIKE '%SQL Plans%'
  6777. OR counter_name LIKE '%Object Plans%'
  6778. OR counter_name LIKE '%_Total%'
  6779. OR counter_name LIKE 'Transactions/sec%'
  6780. OR counter_name LIKE '%Log Flush Wait Time%'
  6781. OR counter_name LIKE '%Log Flush Waits/sec%'
  6782. OR counter_name LIKE '%Recovery Queue%'
  6783. OR counter_name LIKE '%Log Send Queue%'
  6784. OR counter_name LIKE '%Transaction Delay%'
  6785. OR counter_name LIKE '%Redo blocked/sec%'
  6786. OR counter_name LIKE '%Resent Messages/sec%'
  6787. OR instance_name LIKE '%Buffer Pool%'
  6788. OR instance_name LIKE '%Column store object pool%');
  6789. INSERT INTO #tblWaits
  6790. SELECT @maxctr, wait_type, wait_time_ms, signal_wait_time_ms,(wait_time_ms-signal_wait_time_ms) AS resource_wait_time_ms
  6791. FROM sys.dm_os_wait_stats (NOLOCK)
  6792. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
  6793. 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT',
  6794. 'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH',
  6795. 'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6796. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6797. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6798. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6799. AND wait_type NOT LIKE N'SLEEP_%'
  6800. AND wait_time_ms > 0;
  6801. INSERT INTO #tblLatches
  6802. SELECT @maxctr, latch_class, wait_time_ms, waiting_requests_count
  6803. FROM sys.dm_os_latch_stats (NOLOCK)
  6804. WHERE /*latch_class NOT IN ('BUFFER')
  6805. AND*/ wait_time_ms > 0;
  6806. IF @sqlmajorver > 9
  6807. BEGIN
  6808. INSERT INTO #tblSpinlocksAfter
  6809. SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs
  6810. FROM sys.dm_os_spinlock_stats;
  6811. END
  6812. ELSE IF @sqlmajorver = 9
  6813. BEGIN
  6814. INSERT INTO #tblSpinlocksAfter
  6815. EXEC ('DBCC SQLPERF(''spinlockstats'')');
  6816. END;
  6817. INSERT INTO tempdb.dbo.tblPerfThresholds
  6818. SELECT DISTINCT t1.[object_name], t1.counter_name, t1.instance_name, t1.[counter_name_type],
  6819. CASE WHEN t1.counter_name_type = 272696576
  6820. THEN CONVERT(float,(
  6821. (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) -
  6822. (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)
  6823. ) / DATEDIFF(ss,@minctr,@maxctr)) -- Get value per s over last xx s
  6824. WHEN t1.counter_name_type = 537003264
  6825. THEN (SELECT CONVERT(float,(t2.cntr_value / CASE WHEN t3.cntr_value <= 0 THEN 1 ELSE t3.cntr_value END) * 100.0)
  6826. 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')
  6827. 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
  6828. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6829. WHEN t1.counter_name_type = 1073874176 AND t1.counter_name = 'Average Latch Wait Time (ms)'
  6830. THEN CONVERT(float,(
  6831. (
  6832. (SELECT t2.cntr_value - t3.cntr_value
  6833. FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.counter_name = t3.counter_name
  6834. 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
  6835. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6836. /
  6837. (SELECT CASE WHEN t2.cntr_value - t3.cntr_value <= 0 THEN 1 ELSE t2.cntr_value - t3.cntr_value END
  6838. FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.counter_name = t3.counter_name
  6839. 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
  6840. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6841. )
  6842. / DATEDIFF(ss,@minctr,@maxctr))) -- Get value per s over last xx s
  6843. WHEN t1.counter_name_type = 1073874176 AND t1.counter_name = 'Average Wait Time (ms)'
  6844. THEN CONVERT(float,(
  6845. (
  6846. SELECT (t4.cntr_value / CASE WHEN t5.cntr_value <= 0 THEN 1 ELSE t5.cntr_value END) / DATEDIFF(ss,@minctr,@maxctr)
  6847. FROM
  6848. (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
  6849. 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
  6850. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name, t2.instance_name) AS t4
  6851. INNER JOIN
  6852. (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
  6853. 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
  6854. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name, t2.instance_name) AS t5
  6855. ON t4.instance_name = t5.instance_name
  6856. ))) -- Get value per s over last xx s
  6857. ELSE CONVERT(float,t1.cntr_value)
  6858. END
  6859. FROM #tblPerfCount t1
  6860. WHERE (t1.counter_name_type <> 1073939712)
  6861. GROUP BY t1.[object_name], t1.[counter_name], t1.instance_name, t1.counter_name_type, t1.cntr_value
  6862. ORDER BY t1.[object_name], t1.[counter_name], t1.instance_name;
  6863. ;WITH ctectr AS (SELECT [counter_family],[counter_name],[counter_instance],[counter_value],
  6864. CASE WHEN [counter_name] IN ('Worktables Created/sec','Worktables From Cache Ratio','Buffer cache hit ratio',
  6865. 'Free list stalls/sec','Free pages','Free Memory (KB)','Lazy writes/sec','Page life expectancy',
  6866. 'Page reads/sec','Log Flush Wait Time','Log Flush Waits/sec','Average Latch Wait Time (ms)',
  6867. 'Total Latch Wait Time (ms)','Lock Waits/sec','Number of Deadlocks/sec','Batch Requests/sec') THEN [counter_value]
  6868. ELSE tempdb.dbo.fn_perfctr([counter_family],[counter_name]) END AS [counter_calculated_threshold_value]
  6869. FROM tempdb.dbo.tblPerfThresholds)
  6870. SELECT 'Performance_checks' AS [Category], 'Perf_Counters' AS [Check],[counter_family],[counter_name],[counter_instance],[counter_value],[counter_calculated_threshold_value],
  6871. 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]'
  6872. 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]'
  6873. 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]'
  6874. 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]'
  6875. 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]'
  6876. WHEN [counter_name] = 'Worktables Created/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: Greater than 20 Worktables created per second]'
  6877. WHEN [counter_name] = 'Worktables From Cache Ratio' AND [counter_calculated_threshold_value] < 90 THEN '[WARNING: Less than 90 percent Worktables from Cache Ratio]'
  6878. WHEN [counter_name] = 'Buffer cache hit ratio' AND [counter_calculated_threshold_value] < 97 THEN '[WARNING: Less than 97 percent buffer cache hit ratio]'
  6879. WHEN [counter_name] = 'Buffer cache hit ratio' AND [counter_calculated_threshold_value] < 90 THEN '[WARNING: Less than 90 percent buffer cache hit ratio]'
  6880. WHEN [counter_name] = 'Free list stalls/sec' AND [counter_calculated_threshold_value] < 2 THEN '[WARNING: Free list stalls per second is less than 2]'
  6881. WHEN [counter_name] = 'Free pages' AND [counter_calculated_threshold_value] < 640 THEN '[WARNING: Less than 640 Free Pages]'
  6882. WHEN [counter_name] = 'Free Memory (KB)' AND [counter_calculated_threshold_value] < 5 THEN '[WARNING: Less than 5MB]'
  6883. WHEN [counter_name] = 'Lazy writes/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: Greater than 20 Lazy Writes per second]'
  6884. WHEN [counter_name] = 'Page life expectancy' AND [counter_calculated_threshold_value] < 300 THEN '[WARNING: Less than 300 seconds of Page Life Expectancy]'
  6885. WHEN [counter_name] = 'Page life expectancy' AND [counter_calculated_threshold_value] < 700 THEN '[WARNING: Less than 700 seconds of Page Life Expectancy]'
  6886. 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]'
  6887. WHEN [counter_name] = 'Page reads/sec' AND [counter_calculated_threshold_value] > 90 THEN '[WARNING: Greater than 90 page reads per second]'
  6888. 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]'
  6889. WHEN [counter_name] = 'Page writes/sec' AND [counter_value] > 90 THEN '[WARNING: Greater than 90 page writes per second]'
  6890. WHEN [counter_name] = 'Readahead pages/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: More than 20 percent of page reads per second]'
  6891. 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]'
  6892. 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]'
  6893. 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]'
  6894. 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]'
  6895. 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]'
  6896. 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]'
  6897. WHEN [counter_name] = 'Batch Requests/sec' AND [counter_calculated_threshold_value] > 1000 THEN '[WARNING: Greater than 1000 batch requests per second]'
  6898. 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]'
  6899. 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]'
  6900. WHEN [counter_calculated_threshold_value] IS NULL THEN NULL
  6901. ELSE '[OK]' END AS [Deviation]
  6902. FROM ctectr
  6903. ORDER BY [counter_family],[counter_name],[counter_instance];
  6904. IF @sqlmajorver >= 11
  6905. BEGIN
  6906. 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"
  6907. FROM (SELECT [counter_name],[instance_name],[cntr_value] FROM #tblPerfCount WHERE [object_name] LIKE '%Batch Resp Statistics%') AS pc
  6908. PIVOT(AVG([cntr_value]) FOR [instance_name]
  6909. IN ("CPU Time:Total(ms)", "CPU Time:Requests", "Elapsed Time:Total(ms)", "Elapsed Time:Requests")
  6910. ) AS Pvt;
  6911. END
  6912. ;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),
  6913. 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)
  6914. INSERT INTO #tblFinalWaits
  6915. SELECT DISTINCT t1.wait_type, (t2.wait_time_ms-t1.wait_time_ms) / 1000. AS wait_time_s,
  6916. (t2.signal_wait_time_ms-t1.signal_wait_time_ms) / 1000. AS signal_wait_time_s,
  6917. ((t2.wait_time_ms-t2.signal_wait_time_ms)-(t1.wait_time_ms-t1.signal_wait_time_ms)) / 1000. AS resource_wait_time_s,
  6918. 100.0 * (t2.wait_time_ms-t1.wait_time_ms) / SUM(t2.wait_time_ms-t1.wait_time_ms) OVER() AS pct,
  6919. ROW_NUMBER() OVER(ORDER BY (t2.wait_time_ms-t1.wait_time_ms) DESC) AS rn,
  6920. 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,
  6921. (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
  6922. FROM cteWaits1 t1 INNER JOIN cteWaits2 t2 ON t1.wait_type = t2.wait_type
  6923. 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
  6924. HAVING (t2.wait_time_ms-t1.wait_time_ms) > 0
  6925. ORDER BY wait_time_s DESC;
  6926. SELECT 'Performance_checks' AS [Category], 'Waits_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], W1.wait_type,
  6927. CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s,
  6928. CAST(W1.signal_wait_time_s AS DECIMAL(12, 2)) AS signal_wait_time_s,
  6929. CAST(W1.resource_wait_time_s AS DECIMAL(12, 2)) AS resource_wait_time_s,
  6930. CAST(W1.pct AS DECIMAL(12, 2)) AS pct,
  6931. CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  6932. CAST(W1.signal_wait_pct AS DECIMAL(12, 2)) AS signal_wait_pct,
  6933. CAST(W1.resource_wait_pct AS DECIMAL(12, 2)) AS resource_wait_pct,
  6934. CASE WHEN W1.wait_type LIKE N'LCK_%' OR W1.wait_type = N'LOCK' THEN N'Lock'
  6935. WHEN W1.wait_type LIKE N'LATCH_%' THEN N'Latch'
  6936. WHEN W1.wait_type LIKE N'PAGELATCH_%' THEN N'Buffer Latch'
  6937. WHEN W1.wait_type LIKE N'PAGEIOLATCH_%' THEN N'Buffer IO'
  6938. WHEN W1.wait_type LIKE N'HADR_SYNC_COMMIT' THEN N'AlwaysOn - Secondary Synch'
  6939. WHEN W1.wait_type LIKE N'HADR_%' THEN N'AlwaysOn'
  6940. WHEN W1.wait_type LIKE N'FFT_%' THEN N'FileTable'
  6941. 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;
  6942. WHEN W1.wait_type IN (N'IO_COMPLETION', N'ASYNC_IO_COMPLETION', /*N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',*/ N'DISKIO_SUSPEND') THEN N'Other IO'
  6943. WHEN W1.wait_type IN(N'BACKUPIO', N'BACKUPBUFFER') THEN 'Backup IO'
  6944. WHEN W1.wait_type = N'THREADPOOL' THEN 'CPU - Unavailable Worker Threads'
  6945. WHEN W1.wait_type = N'SOS_SCHEDULER_YIELD' THEN N'CPU - Scheduler Yielding'
  6946. WHEN W1.wait_type IN (N'CXPACKET', N'EXCHANGE') THEN N'CPU - Parallelism'
  6947. WHEN W1.wait_type IN (N'LOGMGR', N'LOGBUFFER', N'LOGMGR_RESERVE_APPEND', N'LOGMGR_FLUSH', N'WRITELOG') THEN N'Logging'
  6948. WHEN W1.wait_type IN (N'NET_WAITFOR_PACKET',N'NETWORK_IO') THEN N'Network IO'
  6949. WHEN W1.wait_type = N'ASYNC_NETWORK_IO' THEN N'Client Network IO'
  6950. WHEN W1.wait_type IN (N'UTIL_PAGE_ALLOC',N'SOS_VIRTUALMEMORY_LOW',N'CMEMTHREAD', N'SOS_RESERVEDMEMBLOCKLIST') THEN N'Memory'
  6951. WHEN W1.wait_type IN (N'RESOURCE_SEMAPHORE_SMALL_QUERY', N'RESOURCE_SEMAPHORE') THEN N'Memory - Hash or Sort'
  6952. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Memory - Compilation'
  6953. WHEN W1.wait_type LIKE N'CLR_%' OR W1.wait_type LIKE N'SQLCLR%' THEN N'CLR'
  6954. WHEN W1.wait_type LIKE N'DBMIRROR%' OR W1.wait_type = N'MIRROR_SEND_MESSAGE' THEN N'Mirroring'
  6955. 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'
  6956. -- 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'
  6957. WHEN W1.wait_type LIKE N'FT_%' THEN N'Full Text'
  6958. WHEN W1.wait_type = N'REPLICA_WRITE' THEN 'Snapshots'
  6959. ELSE N'Other' END AS 'wait_category'
  6960. FROM #tblFinalWaits AS W1 INNER JOIN #tblFinalWaits AS W2 ON W2.rn <= W1.rn
  6961. 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
  6962. HAVING W1.wait_time_s >= 0.01 AND (SUM(W2.pct)-W1.pct) < 100 -- percentage threshold
  6963. ORDER BY W1.rn;
  6964. ;WITH Waits AS
  6965. (SELECT wait_type, wait_time_ms / 1000. AS wait_time_s,
  6966. signal_wait_time_ms / 1000. AS signal_wait_time_s,
  6967. (wait_time_ms-signal_wait_time_ms) / 1000. AS resource_wait_time_s,
  6968. SUM(signal_wait_time_ms) * 1.0 / SUM(wait_time_ms) * 100 AS signal_wait_pct,
  6969. SUM(wait_time_ms-signal_wait_time_ms) * 1.0 / SUM(wait_time_ms) * 100 AS resource_wait_pct,
  6970. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  6971. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  6972. FROM sys.dm_os_wait_stats
  6973. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP'
  6974. , 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT'
  6975. ,'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH'
  6976. ,'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6977. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6978. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6979. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6980. AND wait_type NOT LIKE N'SLEEP_%'
  6981. GROUP BY wait_type, wait_time_ms, signal_wait_time_ms)
  6982. SELECT 'Performance_checks' AS [Category], 'Cumulative_Waits' AS [Information], W1.wait_type,
  6983. CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s,
  6984. CAST(W1.signal_wait_time_s AS DECIMAL(12, 2)) AS signal_wait_time_s,
  6985. CAST(W1.resource_wait_time_s AS DECIMAL(12, 2)) AS resource_wait_time_s,
  6986. CAST(W1.pct AS DECIMAL(12, 2)) AS pct,
  6987. CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  6988. CAST(W1.signal_wait_pct AS DECIMAL(12, 2)) AS signal_wait_pct,
  6989. CAST(W1.resource_wait_pct AS DECIMAL(12, 2)) AS resource_wait_pct,
  6990. CASE WHEN W1.wait_type LIKE N'LCK_%' OR W1.wait_type = N'LOCK' THEN N'Lock'
  6991. -- 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;
  6992. WHEN W1.wait_type LIKE N'LATCH_%' THEN N'Latch'
  6993. -- PAGELATCH = indicates contention for access to in-memory copies of pages, like PFS, SGAM and GAM;
  6994. -- PAGELATCH_UP = Does the filegroup have enough files? Contention in PFS?
  6995. -- PAGELATCH_EX = Contention while doing many UPDATE statements against small tables?
  6996. -- 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
  6997. WHEN W1.wait_type LIKE N'PAGELATCH_%' THEN N'Buffer Latch'
  6998. -- PAGEIOLATCH = indicates IO problems, or BP pressure.
  6999. WHEN W1.wait_type LIKE N'PAGEIOLATCH_%' THEN N'Buffer IO'
  7000. WHEN W1.wait_type LIKE N'HADR_SYNC_COMMIT' THEN N'AlwaysOn - Secondary Synch'
  7001. WHEN W1.wait_type LIKE N'HADR_%' THEN N'AlwaysOn'
  7002. WHEN W1.wait_type LIKE N'FFT_%' THEN N'FileTable'
  7003. -- PREEMPTIVE_OS_WRITEFILEGATHERER (2008+) = usually autogrow scenarios, usually together with WRITELOG;
  7004. 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;
  7005. -- IO_COMPLETION = usually TempDB spilling;
  7006. -- ASYNC_IO_COMPLETION = usually when not using IFI, or waiting on backups.
  7007. -- 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;
  7008. WHEN W1.wait_type IN (N'IO_COMPLETION', N'ASYNC_IO_COMPLETION', /*N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',*/ N'DISKIO_SUSPEND') THEN N'Other IO'
  7009. -- BACKUPIO = check for slow backup media slow, like Tapes or Disks;
  7010. -- BACKUPBUFFER = usually when backing up to Tape;
  7011. WHEN W1.wait_type IN(N'BACKUPIO', N'BACKUPBUFFER') THEN 'Backup IO'
  7012. -- THREADPOOL = Look for high blocking or contention problems with workers. This will not show up in sys.dm_exec_requests;
  7013. WHEN W1.wait_type = N'THREADPOOL' THEN 'CPU - Unavailable Worker Threads'
  7014. -- 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
  7015. WHEN W1.wait_type = N'SOS_SCHEDULER_YIELD' THEN N'CPU - Scheduler Yielding'
  7016. -- Check sys.dm_os_waiting_tasks for Exchange wait types in http://technet.microsoft.com/en-us/library/ms188743.aspx;
  7017. -- Wait Resource e_waitPipeNewRow in CXPACKET waits Producer waiting on consumer for a packet to fill;
  7018. -- Wait Resource e_waitPipeGetRow in CXPACKET waits Consumer waiting on producer to fill a packet;
  7019. -- 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;
  7020. WHEN W1.wait_type IN (N'CXPACKET', N'EXCHANGE') THEN N'CPU - Parallelism'
  7021. -- WRITELOG = log management system waiting for a log flush to disk. Examine the IO latency for the log file
  7022. WHEN W1.wait_type IN (N'LOGMGR', N'LOGBUFFER', N'LOGMGR_RESERVE_APPEND', N'LOGMGR_FLUSH', N'WRITELOG') THEN N'Logging'
  7023. WHEN W1.wait_type IN (N'NET_WAITFOR_PACKET',N'NETWORK_IO') THEN N'Network IO'
  7024. WHEN W1.wait_type = N'ASYNC_NETWORK_IO' THEN N'Client Network IO'
  7025. -- 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
  7026. -- 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
  7027. WHEN W1.wait_type IN (N'UTIL_PAGE_ALLOC',N'SOS_VIRTUALMEMORY_LOW',N'CMEMTHREAD', N'SOS_RESERVEDMEMBLOCKLIST') THEN N'Memory'
  7028. -- RESOURCE_SEMAPHORE_SMALL_QUERY or RESOURCE_SEMAPHORE = queries are waiting for execution memory. Look for plans with excessive hashing or sorts.
  7029. WHEN W1.wait_type IN (N'RESOURCE_SEMAPHORE_SMALL_QUERY', N'RESOURCE_SEMAPHORE') THEN N'Memory - Hash or Sort'
  7030. -- 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
  7031. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Memory - Compilation'
  7032. WHEN W1.wait_type LIKE N'CLR_%' OR W1.wait_type LIKE N'SQLCLR%' THEN N'CLR'
  7033. -- DBMIRROR_DBM_MUTEX = indicates contention for the send buffer that database mirroring shares between all the mirroring sessions.
  7034. WHEN W1.wait_type LIKE N'DBMIRROR%' OR W1.wait_type = N'MIRROR_SEND_MESSAGE' THEN N'Mirroring'
  7035. -- 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.
  7036. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Compilation'
  7037. 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'
  7038. -- 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'
  7039. WHEN W1.wait_type LIKE N'FT_%' THEN N'Full Text'
  7040. WHEN W1.wait_type = N'REPLICA_WRITE' THEN 'Snapshots'
  7041. ELSE N'Other' END AS 'wait_category'
  7042. FROM Waits AS W1 INNER JOIN Waits AS W2 ON W2.rn <= W1.rn
  7043. 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
  7044. HAVING W1.wait_time_s >= 0.01 AND (SUM(W2.pct)-W1.pct) < 100 -- percentage threshold
  7045. ORDER BY W1.rn;
  7046. ;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),
  7047. 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)
  7048. INSERT INTO #tblFinalLatches
  7049. SELECT DISTINCT t1.latch_class,
  7050. (t2.wait_time_ms-t1.wait_time_ms) / 1000.0 AS wait_time_s,
  7051. (t2.waiting_requests_count-t1.waiting_requests_count) AS waiting_requests_count,
  7052. 100.0 * (t2.wait_time_ms-t1.wait_time_ms) / SUM(t2.wait_time_ms-t1.wait_time_ms) OVER() AS pct,
  7053. ROW_NUMBER() OVER(ORDER BY t1.wait_time_ms DESC) AS rn
  7054. FROM cteLatches1 t1 INNER JOIN cteLatches2 t2 ON t1.latch_class = t2.latch_class
  7055. GROUP BY t1.latch_class, t1.wait_time_ms, t2.wait_time_ms, t1.waiting_requests_count, t2.waiting_requests_count
  7056. HAVING (t2.wait_time_ms-t1.wait_time_ms) > 0
  7057. ORDER BY wait_time_s DESC;
  7058. SELECT 'Performance_checks' AS [Category], 'Latches_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], W1.latch_class,
  7059. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7060. W1.waiting_requests_count,
  7061. CAST (W1.pct AS DECIMAL(14, 2)) AS pct,
  7062. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7063. CAST ((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7064. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7065. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7066. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7067. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7068. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7069. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7070. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7071. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER' THEN N'[Parallelism - DBCC CHECK_]'
  7072. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7073. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION' THEN N'[Mirroring - Busy]'
  7074. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7075. ELSE N'[Other]' END AS 'latch_category'
  7076. FROM #tblFinalLatches AS W1 INNER JOIN #tblFinalLatches AS W2 ON W2.rn <= W1.rn
  7077. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7078. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7079. ;WITH Latches AS
  7080. (SELECT latch_class,
  7081. wait_time_ms / 1000.0 AS wait_time_s,
  7082. waiting_requests_count,
  7083. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  7084. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  7085. FROM sys.dm_os_latch_stats
  7086. WHERE /*latch_class NOT IN ('BUFFER')
  7087. AND*/ wait_time_ms > 0
  7088. )
  7089. SELECT 'Performance_checks' AS [Category], 'Cumulative_Latches' AS [Information], W1.latch_class,
  7090. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7091. W1.waiting_requests_count,
  7092. CAST(W1.pct AS DECIMAL(14, 2)) AS pct,
  7093. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7094. CAST((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7095. -- 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).
  7096. -- 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.
  7097. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7098. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7099. -- 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.);
  7100. -- 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.
  7101. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7102. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7103. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7104. -- 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.
  7105. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7106. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7107. -- 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.
  7108. -- http://blogs.msdn.com/b/psssql/archive/2012/02/23/a-faster-checkdb-part-ii.aspx
  7109. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER ' THEN N'[Parallelism - DBCC CHECK_]'
  7110. -- 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.
  7111. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7112. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION ' THEN N'[Mirroring - Busy]'
  7113. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7114. ELSE N'Other' END AS 'latch_category'
  7115. FROM Latches AS W1
  7116. INNER JOIN Latches AS W2
  7117. ON W2.rn <= W1.rn
  7118. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7119. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7120. ;WITH Latches AS
  7121. (SELECT latch_class,
  7122. wait_time_ms / 1000.0 AS wait_time_s,
  7123. waiting_requests_count,
  7124. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  7125. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  7126. FROM sys.dm_os_latch_stats (NOLOCK)
  7127. WHERE latch_class NOT IN ('BUFFER')
  7128. AND wait_time_ms > 0
  7129. )
  7130. SELECT 'Performance_checks' AS [Category], 'Cumulative_Latches_wo_BUFFER' AS [Information], W1.latch_class,
  7131. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7132. W1.waiting_requests_count,
  7133. CAST(W1.pct AS DECIMAL(14, 2)) AS pct,
  7134. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7135. CAST((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7136. -- 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).
  7137. -- 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.
  7138. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7139. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7140. -- 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.);
  7141. -- 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.
  7142. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7143. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7144. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7145. -- 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.
  7146. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7147. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7148. -- 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.
  7149. -- http://blogs.msdn.com/b/psssql/archive/2012/02/23/a-faster-checkdb-part-ii.aspx
  7150. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER ' THEN N'[Parallelism - DBCC CHECK_]'
  7151. -- 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.
  7152. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7153. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION ' THEN N'[Mirroring - Busy]'
  7154. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7155. ELSE N'Other' END AS 'latch_category'
  7156. FROM Latches AS W1
  7157. INNER JOIN Latches AS W2
  7158. ON W2.rn <= W1.rn
  7159. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7160. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7161. ;WITH cteSpinlocks1 AS (SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs FROM #tblSpinlocksBefore),
  7162. cteSpinlocks2 AS (SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs FROM #tblSpinlocksAfter)
  7163. INSERT INTO #tblFinalSpinlocks
  7164. SELECT DISTINCT t1.name,
  7165. (t2.collisions-t1.collisions) AS collisions,
  7166. (t2.spins-t1.spins) AS spins,
  7167. (t2.spins_per_collision-t1.spins_per_collision) AS spins_per_collision,
  7168. (t2.sleep_time-t1.sleep_time) AS sleep_time,
  7169. (t2.backoffs-t1.backoffs) AS backoffs,
  7170. 100.0 * (t2.spins-t1.spins) / SUM(t2.spins-t1.spins) OVER() AS spins_pct,
  7171. ROW_NUMBER() OVER(ORDER BY t2.spins DESC) AS rn
  7172. FROM cteSpinlocks1 t1 INNER JOIN cteSpinlocks2 t2 ON t1.name = t2.name
  7173. 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
  7174. HAVING (t2.spins-t1.spins) > 0
  7175. ORDER BY spins DESC;
  7176. SELECT 'Performance_checks' AS [Category], 'Spinlocks_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], S1.name,
  7177. S1.collisions, S1.spins, S1.spins_per_collision, S1.sleep_time, S1.backoffs,
  7178. CAST(S1.spins_pct AS DECIMAL(14, 2)) AS spins_pct,
  7179. CAST(SUM(S1.spins_pct) AS DECIMAL(12, 2)) AS overall_running_spins_pct
  7180. FROM #tblFinalSpinlocks AS S1 INNER JOIN #tblFinalSpinlocks AS S2 ON S2.rn <= S1.rn
  7181. GROUP BY S1.rn, S1.name, S1.collisions, S1.spins, S1.spins_per_collision, S1.sleep_time, S1.backoffs, S1.spins_pct
  7182. HAVING SUM(S2.spins_pct) - S1.spins_pct < 100 -- percentage threshold
  7183. ORDER BY spins DESC;
  7184. END;
  7185. --------------------------------------------------------------------------------------------------------------------------------
  7186. -- Worker thread exhaustion subsection
  7187. --------------------------------------------------------------------------------------------------------------------------------
  7188. IF @ptochecks = 1
  7189. BEGIN
  7190. RAISERROR (N' |-Starting Worker thread exhaustion', 10, 1) WITH NOWAIT
  7191. DECLARE @avgtskcnt int, @workqcnt int
  7192. SELECT @avgtskcnt = SUM(runnable_tasks_count)/COUNT(scheduler_id), @workqcnt = SUM(work_queue_count) FROM sys.dm_os_schedulers
  7193. WHERE parent_node_id < 64 AND scheduler_id < 255
  7194. IF @avgtskcnt <= 2 AND @workqcnt > 1
  7195. BEGIN
  7196. 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]
  7197. END
  7198. ELSE IF @avgtskcnt > 2 AND @workqcnt > 1
  7199. BEGIN
  7200. 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]
  7201. END
  7202. ELSE
  7203. BEGIN
  7204. SELECT 'Performance_checks' AS [Category], 'Worker_thread_exhaustion' AS [Check], '[OK]' AS [Deviation], '' AS [Comment]
  7205. END
  7206. END;
  7207. --------------------------------------------------------------------------------------------------------------------------------
  7208. -- Blocking Chains subsection
  7209. -- Checks for blocking chains taking over 5s.
  7210. --------------------------------------------------------------------------------------------------------------------------------
  7211. IF @ptochecks = 1
  7212. BEGIN
  7213. RAISERROR (N' |-Starting Blocking Chains', 10, 1) WITH NOWAIT
  7214. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  7215. DROP TABLE #tblBlkChains;
  7216. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  7217. CREATE TABLE #tblBlkChains ([blocked_spid] [smallint], [blocked_spid_status] NVARCHAR(30), [blocked_task_status] NVARCHAR(60),
  7218. [blocked_spid_wait_type] NVARCHAR(60), [blocked_spid_wait_time_ms] [bigint], [blocked_spid_res_desc] NVARCHAR(1024),
  7219. [blocked_pageid] [int], [blocked_spid_res_type] VARCHAR(24), [blocked_batch] [xml], [blocked_statement] [xml],
  7220. [blocked_last_start] [datetime], [blocked_tran_isolation_level] VARCHAR(30), [blocker_spid] [smallint],
  7221. [is_head_blocker] [int], [blocker_batch] [xml], [blocker_statement] [xml], [blocker_last_start] [datetime],
  7222. [blocker_tran_isolation_level] VARCHAR(30), [blocked_database] NVARCHAR(128), [blocked_host] NVARCHAR(128),
  7223. [blocked_program] NVARCHAR(128), [blocked_login] NVARCHAR(128), [blocked_session_comment] VARCHAR(25),
  7224. [blocked_is_user_process] [bit], [blocker_database] NVARCHAR(128), [blocker_host] NVARCHAR(128),
  7225. [blocker_program] NVARCHAR(128), [blocker_login] NVARCHAR(128), [blocker_session_comment] VARCHAR(25), [blocker_is_user_process] [bit])
  7226. INSERT INTO #tblBlkChains
  7227. SELECT
  7228. -- blocked
  7229. es.session_id AS blocked_spid,
  7230. es.[status] AS [blocked_spid_status],
  7231. ot.task_state AS [blocked_task_status],
  7232. owt.wait_type AS blocked_spid_wait_type,
  7233. COALESCE(owt.wait_duration_ms, ABS(CONVERT(BIGINT,(DATEDIFF(mi, es.last_request_start_time, GETDATE())))*60)) AS blocked_spid_wait_time_ms,
  7234. --er.total_elapsed_time AS blocked_elapsed_time_ms,
  7235. /*
  7236. Check sys.dm_os_waiting_tasks for Exchange wait types in http://technet.microsoft.com/en-us/library/ms188743.aspx.
  7237. - Wait Resource e_waitPipeNewRow in CXPACKET waits – Producer waiting on consumer for a packet to fill.
  7238. - Wait Resource e_waitPipeGetRow in CXPACKET waits – Consumer waiting on producer to fill a packet.
  7239. */
  7240. owt.resource_description AS blocked_spid_res_desc,
  7241. owt.pageid AS blocked_pageid,
  7242. CASE WHEN owt.pageid = 1 OR owt.pageid % 8088 = 0 THEN 'Is_PFS_Page'
  7243. WHEN owt.pageid = 2 OR owt.pageid % 511232 = 0 THEN 'Is_GAM_Page'
  7244. WHEN owt.pageid = 3 OR (owt.pageid - 1) % 511232 = 0 THEN 'Is_SGAM_Page'
  7245. WHEN owt.pageid IS NULL THEN NULL
  7246. ELSE 'Is_not_PFS_GAM_SGAM_page' END AS blocked_spid_res_type,
  7247. (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(
  7248. qt.[text],
  7249. 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'?')
  7250. AS [text()]
  7251. FROM sys.dm_exec_sql_text(COALESCE(er.sql_handle, ec.most_recent_sql_handle)) AS qt
  7252. FOR XML PATH(''), TYPE) AS [blocked_batch],
  7253. (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(
  7254. SUBSTRING(qt2.text,
  7255. (CASE WHEN er.statement_start_offset = 0 THEN 0 ELSE er.statement_start_offset/2 END),
  7256. (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))),
  7257. 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'?')
  7258. AS [text()]
  7259. FROM sys.dm_exec_sql_text(COALESCE(er.sql_handle, ec.most_recent_sql_handle)) AS qt2
  7260. FOR XML PATH(''), TYPE) AS [blocked_statement],
  7261. es.last_request_start_time AS blocked_last_start,
  7262. LEFT (CASE COALESCE(es.transaction_isolation_level, er.transaction_isolation_level)
  7263. WHEN 0 THEN '0-Unspecified'
  7264. WHEN 1 THEN '1-ReadUncommitted(NOLOCK)'
  7265. WHEN 2 THEN '2-ReadCommitted'
  7266. WHEN 3 THEN '3-RepeatableRead'
  7267. WHEN 4 THEN '4-Serializable'
  7268. WHEN 5 THEN '5-Snapshot'
  7269. ELSE CONVERT (VARCHAR(30), COALESCE(es.transaction_isolation_level, er.transaction_isolation_level)) + '-UNKNOWN'
  7270. END, 30) AS blocked_tran_isolation_level,
  7271. -- blocker
  7272. er.blocking_session_id As blocker_spid,
  7273. CASE
  7274. -- session has an active request, is blocked, but is blocking others or session is idle but has an open tran and is blocking others
  7275. 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
  7276. -- session is either not blocking someone, or is blocking someone but is blocked by another party
  7277. ELSE 0
  7278. END AS is_head_blocker,
  7279. (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(
  7280. qt2.[text],
  7281. 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'?')
  7282. AS [text()]
  7283. FROM sys.dm_exec_sql_text(COALESCE(er2.sql_handle, ec2.most_recent_sql_handle)) AS qt2
  7284. FOR XML PATH(''), TYPE) AS [blocker_batch],
  7285. (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(
  7286. SUBSTRING(qt2.text,
  7287. (CASE WHEN er2.statement_start_offset = 0 THEN 0 ELSE er2.statement_start_offset/2 END),
  7288. (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))),
  7289. 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'?')
  7290. AS [text()]
  7291. FROM sys.dm_exec_sql_text(COALESCE(er2.sql_handle, ec2.most_recent_sql_handle)) AS qt2
  7292. FOR XML PATH(''), TYPE) AS [blocker_statement],
  7293. es2.last_request_start_time AS blocker_last_start,
  7294. LEFT (CASE COALESCE(er2.transaction_isolation_level, es.transaction_isolation_level)
  7295. WHEN 0 THEN '0-Unspecified'
  7296. WHEN 1 THEN '1-ReadUncommitted(NOLOCK)'
  7297. WHEN 2 THEN '2-ReadCommitted'
  7298. WHEN 3 THEN '3-RepeatableRead'
  7299. WHEN 4 THEN '4-Serializable'
  7300. WHEN 5 THEN '5-Snapshot'
  7301. ELSE CONVERT (VARCHAR(30), COALESCE(er2.transaction_isolation_level, es.transaction_isolation_level)) + '-UNKNOWN'
  7302. END, 30) AS blocker_tran_isolation_level,
  7303. -- blocked - other data
  7304. DB_NAME(er.database_id) AS blocked_database,
  7305. es.[host_name] AS blocked_host,
  7306. es.[program_name] AS blocked_program,
  7307. es.login_name AS blocked_login,
  7308. CASE WHEN es.session_id = -2 THEN 'Orphaned_distributed_tran'
  7309. WHEN es.session_id = -3 THEN 'Defered_recovery_tran'
  7310. WHEN es.session_id = -4 THEN 'Unknown_tran' ELSE NULL END AS blocked_session_comment,
  7311. es.is_user_process AS [blocked_is_user_process],
  7312. -- blocker - other data
  7313. DB_NAME(er2.database_id) AS blocker_database,
  7314. es2.[host_name] AS blocker_host,
  7315. es2.[program_name] AS blocker_program,
  7316. es2.login_name AS blocker_login,
  7317. CASE WHEN es2.session_id = -2 THEN 'Orphaned_distributed_tran'
  7318. WHEN es2.session_id = -3 THEN 'Defered_recovery_tran'
  7319. WHEN es2.session_id = -4 THEN 'Unknown_tran' ELSE NULL END AS blocker_session_comment,
  7320. es2.is_user_process AS [blocker_is_user_process]
  7321. FROM sys.dm_exec_sessions es
  7322. LEFT OUTER JOIN sys.dm_exec_requests er ON es.session_id = er.session_id
  7323. LEFT OUTER JOIN sys.dm_exec_connections ec ON es.session_id = ec.session_id
  7324. LEFT OUTER JOIN sys.dm_os_tasks ot ON er.session_id = ot.session_id AND er.request_id = ot.request_id
  7325. LEFT OUTER JOIN sys.dm_exec_sessions es2 ON er.blocking_session_id = es2.session_id
  7326. LEFT OUTER JOIN sys.dm_exec_requests er2 ON es2.session_id = er2.session_id
  7327. LEFT OUTER JOIN sys.dm_exec_connections ec2 ON es2.session_id = ec2.session_id
  7328. LEFT OUTER JOIN
  7329. (
  7330. -- In some cases (e.g. parallel queries, also waiting for a worker), one thread can be flagged as
  7331. -- waiting for several different threads. This will cause that thread to show up in multiple rows
  7332. -- in our grid, which we don't want. Use ROW_NUMBER to select the longest wait for each thread,
  7333. -- and use it as representative of the other wait relationships this thread is involved in.
  7334. SELECT waiting_task_address, session_id, exec_context_id, wait_duration_ms,
  7335. wait_type, resource_address, blocking_task_address, blocking_session_id,
  7336. blocking_exec_context_id, resource_description,
  7337. 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)
  7338. ELSE NULL END AS pageid,
  7339. ROW_NUMBER() OVER (PARTITION BY waiting_task_address ORDER BY wait_duration_ms DESC) AS row_num
  7340. FROM sys.dm_os_waiting_tasks
  7341. WHERE wait_type <> 'SP_SERVER_DIAGNOSTICS_SLEEP'
  7342. ) owt ON ot.task_address = owt.waiting_task_address AND owt.row_num = 1
  7343. --OUTER APPLY sys.dm_exec_sql_text (er.sql_handle) est
  7344. --OUTER APPLY sys.dm_exec_query_plan (er.plan_handle) eqp
  7345. WHERE es.session_id <> @@SPID AND es.is_user_process = 1
  7346. 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
  7347. AND (es.session_id IN (SELECT er3.blocking_session_id FROM sys.dm_exec_requests er3) OR er.blocking_session_id IS NOT NULL)
  7348. ORDER BY blocked_spid, is_head_blocker DESC, blocked_spid_wait_time_ms DESC, blocker_spid;
  7349. IF (SELECT COUNT(blocked_spid) FROM #tblBlkChains WHERE CONVERT(VARCHAR(max), blocked_batch) <> 'sp_server_diagnostics') > 0
  7350. BEGIN
  7351. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Check], '[WARNING: Blocking chains in excess of 5s were found.]' AS [Deviation]
  7352. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Information],[blocked_spid],[blocked_spid_status],[blocked_task_status],
  7353. [blocked_spid_wait_type],[blocked_spid_wait_time_ms],[blocked_spid_res_desc],[blocked_pageid],[blocked_spid_res_type],
  7354. [blocked_batch],[blocked_statement],[blocked_last_start],[blocked_tran_isolation_level],[blocker_spid],[is_head_blocker],
  7355. [blocker_batch],[blocker_statement],[blocker_last_start],[blocker_tran_isolation_level],[blocked_database],
  7356. [blocked_host],[blocked_program],[blocked_login],[blocked_session_comment],[blocked_is_user_process],[blocker_database],
  7357. [blocker_host],[blocker_program],[blocker_login],[blocker_session_comment],[blocker_is_user_process]
  7358. FROM #tblBlkChains
  7359. END
  7360. ELSE
  7361. BEGIN
  7362. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Check], '[OK]' AS [Deviation]
  7363. END;
  7364. END;
  7365. --------------------------------------------------------------------------------------------------------------------------------
  7366. -- Plan use ratio subsection
  7367. --------------------------------------------------------------------------------------------------------------------------------
  7368. IF @ptochecks = 1
  7369. BEGIN
  7370. RAISERROR (N' |-Starting Plan use ratio', 10, 1) WITH NOWAIT
  7371. IF (SELECT SUM(CAST(size_in_bytes AS bigint))/1024/1024 AS Size_MB
  7372. FROM sys.dm_exec_cached_plans (NOLOCK)
  7373. WHERE cacheobjtype LIKE '%Plan%' AND usecounts = 1)
  7374. >=
  7375. (SELECT SUM(CAST(size_in_bytes AS bigint))/1024/1024 AS Size_MB
  7376. FROM sys.dm_exec_cached_plans (NOLOCK)
  7377. WHERE cacheobjtype LIKE '%Plan%' AND usecounts > 1)
  7378. BEGIN
  7379. 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]
  7380. END
  7381. ELSE
  7382. BEGIN
  7383. SELECT 'Performance_checks' AS [Category], 'Plan_use_ratio' AS [Check], '[OK]' AS [Deviation], '' AS [Comment]
  7384. END;
  7385. --High number of cached plans with usecounts = 1.
  7386. 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
  7387. FROM sys.dm_exec_cached_plans (NOLOCK)
  7388. WHERE cacheobjtype LIKE '%Plan%' AND usecounts = 1
  7389. GROUP BY objtype, cacheobjtype
  7390. UNION ALL
  7391. --High number of cached plans with usecounts > 1.
  7392. 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
  7393. FROM sys.dm_exec_cached_plans (NOLOCK)
  7394. WHERE cacheobjtype LIKE '%Plan%' AND usecounts > 1
  7395. GROUP BY objtype, cacheobjtype
  7396. ORDER BY objtype, cacheobjtype;
  7397. END;
  7398. --------------------------------------------------------------------------------------------------------------------------------
  7399. -- Hints usage subsection
  7400. -- Refer to "Hints" BOL entry for more information (http://msdn.microsoft.com/en-us/library/ms187713.aspx)
  7401. --------------------------------------------------------------------------------------------------------------------------------
  7402. IF @ptochecks = 1
  7403. BEGIN
  7404. RAISERROR (N' |-Starting Hints usage', 10, 1) WITH NOWAIT
  7405. IF (SELECT COUNT([counter]) FROM sys.dm_exec_query_optimizer_info WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1) > 0
  7406. BEGIN
  7407. RAISERROR (N' |-Hints are being used - finding usage in SQL modules', 10, 1) WITH NOWAIT
  7408. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  7409. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  7410. DROP TABLE #tblHints;
  7411. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  7412. CREATE TABLE #tblHints ([DBName] sysname, [Schema] VARCHAR(100), [Object] VARCHAR(255), [Type] VARCHAR(100), Hint VARCHAR(30));
  7413. UPDATE #tmpdbs0
  7414. SET isdone = 0;
  7415. UPDATE #tmpdbs0
  7416. SET isdone = 1
  7417. WHERE [state] <> 0 OR [dbid] < 5;
  7418. UPDATE #tmpdbs0
  7419. SET isdone = 1
  7420. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  7421. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  7422. BEGIN
  7423. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  7424. BEGIN
  7425. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  7426. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  7427. SELECT ''' + @dbname + ''' AS [DBName], ss.name AS [Schema_Name], so.name AS [Object_Name], so.type_desc,
  7428. CASE WHEN sm.[definition] LIKE ''%FORCE ORDER%'' THEN ''[FORCE ORDER Hint]''
  7429. WHEN sm.[definition] LIKE ''%MERGE JOIN%''
  7430. OR sm.[definition] LIKE ''%LOOP JOIN%''
  7431. OR sm.[definition] LIKE ''%HASH JOIN%'' THEN ''[JOIN Hint]'' END AS Hint
  7432. FROM sys.sql_modules sm
  7433. INNER JOIN sys.objects so ON sm.[object_id] = so.[object_id]
  7434. INNER JOIN sys.schemas ss ON so.[schema_id] = ss.[schema_id]
  7435. WHERE sm.[definition] LIKE ''%FORCE ORDER%''
  7436. OR sm.[definition] LIKE ''%MERGE JOIN%''
  7437. OR sm.[definition] LIKE ''%LOOP JOIN%''
  7438. OR sm.[definition] LIKE ''%HASH JOIN%'';'
  7439. BEGIN TRY
  7440. INSERT INTO #tblHints
  7441. EXECUTE sp_executesql @sqlcmd
  7442. END TRY
  7443. BEGIN CATCH
  7444. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  7445. SELECT @ErrorMessage = 'Hints usage subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  7446. RAISERROR (@ErrorMessage, 16, 1);
  7447. END CATCH
  7448. UPDATE #tmpdbs0
  7449. SET isdone = 1
  7450. WHERE [dbid] = @dbid
  7451. END
  7452. END;
  7453. 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]
  7454. 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
  7455. FROM sys.dm_exec_query_optimizer_info (NOLOCK)
  7456. WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1;
  7457. IF (SELECT COUNT(*) FROM #tblHints WHERE [DBName] IS NOT NULL) > 0
  7458. BEGIN
  7459. SELECT 'Performance_checks' AS [Category], 'Hints_usage_in_Objects' AS [Information], [DBName], [Schema], [Object], [Type], Hint, '' AS Comment
  7460. FROM #tblHints (NOLOCK)
  7461. ORDER BY [DBName], Hint, [Type], [Object];
  7462. END
  7463. ELSE
  7464. BEGIN
  7465. SELECT 'Performance_checks' AS [Category], 'Hints_usage_in_Objects' AS [Information], NULL AS [DBName], NULL AS [Schema], NULL AS [Object], NULL AS [Type],
  7466. 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
  7467. FROM sys.dm_exec_query_optimizer_info (NOLOCK)
  7468. WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1;
  7469. END
  7470. END
  7471. ELSE
  7472. BEGIN
  7473. SELECT 'Performance_checks' AS [Category], 'Hints_usage' AS [Check], '[OK]' AS [Deviation]
  7474. END
  7475. END;
  7476. --------------------------------------------------------------------------------------------------------------------------------
  7477. -- Cached Query Plans issues subsection
  7478. --------------------------------------------------------------------------------------------------------------------------------
  7479. IF @ptochecks = 1
  7480. BEGIN
  7481. RAISERROR (N' |-Starting Cached Query Plans issues', 10, 1) WITH NOWAIT
  7482. --DECLARE @sqlcmd NVARCHAR(max), @params NVARCHAR(500), @sqlmajorver int, @sqlminorver int, @sqlbuild int
  7483. --SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  7484. --SELECT @sqlminorver = CONVERT(int, (@@microsoftversion / 0x10000) & 0xff);
  7485. --SELECT @sqlbuild = CONVERT(int, @@microsoftversion & 0xffff);
  7486. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  7487. DROP TABLE #tmp_dm_exec_query_stats;
  7488. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  7489. CREATE TABLE #tmp_dm_exec_query_stats ([plan_id] [int] NOT NULL IDENTITY(1, 1),
  7490. [sql_handle] [varbinary](64) NOT NULL,
  7491. [statement_start_offset] [int] NOT NULL,
  7492. [statement_end_offset] [int] NOT NULL,
  7493. [plan_generation_num] [bigint] NOT NULL,
  7494. [plan_handle] [varbinary](64) NOT NULL,
  7495. [creation_time] [datetime] NOT NULL,
  7496. [last_execution_time] [datetime] NOT NULL,
  7497. [execution_count] [bigint] NOT NULL,
  7498. [total_worker_time] [bigint] NOT NULL,
  7499. [last_worker_time] [bigint] NOT NULL,
  7500. [min_worker_time] [bigint] NOT NULL,
  7501. [max_worker_time] [bigint] NOT NULL,
  7502. [total_physical_reads] [bigint] NOT NULL,
  7503. [last_physical_reads] [bigint] NOT NULL,
  7504. [min_physical_reads] [bigint] NOT NULL,
  7505. [max_physical_reads] [bigint] NOT NULL,
  7506. [total_logical_writes] [bigint] NOT NULL,
  7507. [last_logical_writes] [bigint] NOT NULL,
  7508. [min_logical_writes] [bigint] NOT NULL,
  7509. [max_logical_writes] [bigint] NOT NULL,
  7510. [total_logical_reads] [bigint] NOT NULL,
  7511. [last_logical_reads] [bigint] NOT NULL,
  7512. [min_logical_reads] [bigint] NOT NULL,
  7513. [max_logical_reads] [bigint] NOT NULL,
  7514. [total_clr_time] [bigint] NOT NULL,
  7515. [last_clr_time] [bigint] NOT NULL,
  7516. [min_clr_time] [bigint] NOT NULL,
  7517. [max_clr_time] [bigint] NOT NULL,
  7518. [total_elapsed_time] [bigint] NOT NULL,
  7519. [last_elapsed_time] [bigint] NOT NULL,
  7520. [min_elapsed_time] [bigint] NOT NULL,
  7521. [max_elapsed_time] [bigint] NOT NULL,
  7522. --2008 only
  7523. [query_hash] [binary](8) NULL,
  7524. [query_plan_hash] [binary](8) NULL,
  7525. --2008R2 only
  7526. [total_rows] bigint NULL,
  7527. [last_rows] bigint NULL,
  7528. [min_rows] bigint NULL,
  7529. [max_rows] bigint NULL,
  7530. --post 2012 SP3, 2014 SP2 and 2016
  7531. [Last_grant_kb] bigint NULL,
  7532. [Min_grant_kb] bigint NULL,
  7533. [Max_grant_kb] bigint NULL,
  7534. [Total_grant_kb] bigint NULL,
  7535. [Last_used_grant_kb] bigint NULL,
  7536. [Min_used_grant_kb] bigint NULL,
  7537. [Max_used_grant_kb] bigint NULL,
  7538. [Total_used_grant_kb] bigint NULL,
  7539. [Last_ideal_grant_kb] bigint NULL,
  7540. [Min_ideal_grant_kb] bigint NULL,
  7541. [Max_ideal_grant_kb] bigint NULL,
  7542. [Total_ideal_grant_kb] bigint NULL,
  7543. [Last_dop] bigint NULL,
  7544. [Min_dop] bigint NULL,
  7545. [Max_dop] bigint NULL,
  7546. [Total_dop] bigint NULL,
  7547. [Last_reserved_threads] bigint NULL,
  7548. [Min_reserved_threads] bigint NULL,
  7549. [Max_reserved_threads] bigint NULL,
  7550. [Total_reserved_threads] bigint NULL,
  7551. [Last_used_threads] bigint NULL,
  7552. [Min_used_threads] bigint NULL,
  7553. [Max_used_threads] bigint NULL,
  7554. [Total_used_threads] bigint NULL,
  7555. [Grant2Used_Ratio] float NULL)
  7556. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  7557. DROP TABLE #dm_exec_query_stats;
  7558. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  7559. CREATE TABLE #dm_exec_query_stats ([plan_id] [int] NOT NULL IDENTITY(1, 1),
  7560. [sql_handle] [varbinary](64) NOT NULL,
  7561. [statement_start_offset] [int] NOT NULL,
  7562. [statement_end_offset] [int] NOT NULL,
  7563. [plan_generation_num] [bigint] NOT NULL,
  7564. [plan_handle] [varbinary](64) NOT NULL,
  7565. [creation_time] [datetime] NOT NULL,
  7566. [last_execution_time] [datetime] NOT NULL,
  7567. [execution_count] [bigint] NOT NULL,
  7568. [total_worker_time] [bigint] NOT NULL,
  7569. [last_worker_time] [bigint] NOT NULL,
  7570. [min_worker_time] [bigint] NOT NULL,
  7571. [max_worker_time] [bigint] NOT NULL,
  7572. [total_physical_reads] [bigint] NOT NULL,
  7573. [last_physical_reads] [bigint] NOT NULL,
  7574. [min_physical_reads] [bigint] NOT NULL,
  7575. [max_physical_reads] [bigint] NOT NULL,
  7576. [total_logical_writes] [bigint] NOT NULL,
  7577. [last_logical_writes] [bigint] NOT NULL,
  7578. [min_logical_writes] [bigint] NOT NULL,
  7579. [max_logical_writes] [bigint] NOT NULL,
  7580. [total_logical_reads] [bigint] NOT NULL,
  7581. [last_logical_reads] [bigint] NOT NULL,
  7582. [min_logical_reads] [bigint] NOT NULL,
  7583. [max_logical_reads] [bigint] NOT NULL,
  7584. [total_clr_time] [bigint] NOT NULL,
  7585. [last_clr_time] [bigint] NOT NULL,
  7586. [min_clr_time] [bigint] NOT NULL,
  7587. [max_clr_time] [bigint] NOT NULL,
  7588. [total_elapsed_time] [bigint] NOT NULL,
  7589. [last_elapsed_time] [bigint] NOT NULL,
  7590. [min_elapsed_time] [bigint] NOT NULL,
  7591. [max_elapsed_time] [bigint] NOT NULL,
  7592. --2008 only
  7593. [query_hash] [binary](8) NULL,
  7594. [query_plan_hash] [binary](8) NULL,
  7595. --2008R2 only
  7596. [total_rows] bigint NULL,
  7597. [last_rows] bigint NULL,
  7598. [min_rows] bigint NULL,
  7599. [max_rows] bigint NULL,
  7600. --post 2012 SP3, 2014 SP2 and 2016
  7601. [Last_grant_kb] bigint NULL,
  7602. [Min_grant_kb] bigint NULL,
  7603. [Max_grant_kb] bigint NULL,
  7604. [Total_grant_kb] bigint NULL,
  7605. [Last_used_grant_kb] bigint NULL,
  7606. [Min_used_grant_kb] bigint NULL,
  7607. [Max_used_grant_kb] bigint NULL,
  7608. [Total_used_grant_kb] bigint NULL,
  7609. [Last_ideal_grant_kb] bigint NULL,
  7610. [Min_ideal_grant_kb] bigint NULL,
  7611. [Max_ideal_grant_kb] bigint NULL,
  7612. [Total_ideal_grant_kb] bigint NULL,
  7613. [Last_dop] bigint NULL,
  7614. [Min_dop] bigint NULL,
  7615. [Max_dop] bigint NULL,
  7616. [Total_dop] bigint NULL,
  7617. [Last_reserved_threads] bigint NULL,
  7618. [Min_reserved_threads] bigint NULL,
  7619. [Max_reserved_threads] bigint NULL,
  7620. [Total_reserved_threads] bigint NULL,
  7621. [Last_used_threads] bigint NULL,
  7622. [Min_used_threads] bigint NULL,
  7623. [Max_used_threads] bigint NULL,
  7624. [Total_used_threads] bigint NULL,
  7625. [Grant2Used_Ratio] float NULL,
  7626. --end
  7627. [query_plan] [xml] NULL,
  7628. [text] [nvarchar](MAX) COLLATE database_default NULL,
  7629. [text_filtered] [nvarchar](MAX) COLLATE database_default NULL)
  7630. IF @sqlmajorver = 9
  7631. BEGIN
  7632. --CPU
  7633. 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])
  7634. --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]
  7635. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7636. --ORDER BY qs.total_worker_time DESC');
  7637. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7638. 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]
  7639. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7640. ORDER BY qs.total_worker_time DESC),
  7641. 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
  7642. FROM TopSearch ts
  7643. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7644. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7645. 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]
  7646. FROM TopFineSearch tfs
  7647. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7648. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7649. ORDER BY tfs.total_worker_time DESC');
  7650. --IO
  7651. 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])
  7652. --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]
  7653. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7654. --ORDER BY qs.total_logical_reads DESC');
  7655. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7656. 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]
  7657. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7658. ORDER BY qs.total_logical_reads DESC),
  7659. 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
  7660. FROM TopSearch ts
  7661. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7662. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7663. 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]
  7664. FROM TopFineSearch tfs
  7665. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7666. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7667. ORDER BY tfs.total_logical_reads DESC');
  7668. --Recompiles
  7669. 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])
  7670. --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]
  7671. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7672. --ORDER BY qs.plan_generation_num DESC');
  7673. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7674. 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]
  7675. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7676. ORDER BY qs.plan_generation_num DESC),
  7677. 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
  7678. FROM TopSearch ts
  7679. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7680. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7681. 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]
  7682. FROM TopFineSearch tfs
  7683. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7684. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7685. ORDER BY tfs.plan_generation_num DESC');
  7686. END
  7687. ELSE IF @sqlmajorver = 10 AND (@sqlminorver = 0 OR (@sqlminorver = 50 AND @sqlbuild < 2500))
  7688. BEGIN
  7689. --CPU
  7690. 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])
  7691. --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]
  7692. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7693. --ORDER BY qs.total_worker_time DESC');
  7694. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7695. 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]
  7696. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7697. ORDER BY qs.total_worker_time DESC),
  7698. 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
  7699. FROM TopSearch ts
  7700. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7701. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7702. 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]
  7703. FROM TopFineSearch tfs
  7704. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7705. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7706. ORDER BY tfs.total_worker_time DESC');
  7707. --IO
  7708. 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])
  7709. --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]
  7710. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7711. --ORDER BY qs.total_logical_reads DESC');
  7712. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7713. 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]
  7714. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7715. ORDER BY qs.total_logical_reads DESC),
  7716. 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
  7717. FROM TopSearch ts
  7718. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7719. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7720. 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]
  7721. FROM TopFineSearch tfs
  7722. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7723. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7724. ORDER BY tfs.total_logical_reads DESC');
  7725. --Recompiles
  7726. 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])
  7727. --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]
  7728. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7729. --ORDER BY qs.plan_generation_num DESC');
  7730. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7731. 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]
  7732. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7733. ORDER BY qs.plan_generation_num DESC),
  7734. 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
  7735. FROM TopSearch ts
  7736. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7737. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7738. 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]
  7739. FROM TopFineSearch tfs
  7740. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7741. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7742. ORDER BY tfs.plan_generation_num DESC');
  7743. END
  7744. ELSE IF (@sqlmajorver = 10 AND @sqlminorver = 50) OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  7745. BEGIN
  7746. --CPU
  7747. 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])
  7748. --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]
  7749. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7750. --ORDER BY qs.total_worker_time DESC');
  7751. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7752. 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]
  7753. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7754. ORDER BY qs.total_worker_time DESC),
  7755. 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
  7756. FROM TopSearch ts
  7757. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7758. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7759. 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]
  7760. FROM TopFineSearch tfs
  7761. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7762. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7763. ORDER BY tfs.total_worker_time DESC');
  7764. --IO
  7765. 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])
  7766. --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]
  7767. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7768. --ORDER BY qs.total_logical_reads DESC');
  7769. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7770. 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]
  7771. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7772. ORDER BY qs.total_logical_reads DESC),
  7773. 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
  7774. FROM TopSearch ts
  7775. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7776. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7777. 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]
  7778. FROM TopFineSearch tfs
  7779. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7780. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7781. ORDER BY tfs.total_logical_reads DESC');
  7782. --Recompiles
  7783. 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])
  7784. --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]
  7785. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7786. --ORDER BY qs.plan_generation_num DESC');
  7787. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7788. 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]
  7789. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7790. ORDER BY qs.plan_generation_num DESC),
  7791. 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
  7792. FROM TopSearch ts
  7793. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7794. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7795. 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]
  7796. FROM TopFineSearch tfs
  7797. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7798. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7799. ORDER BY tfs.plan_generation_num DESC');
  7800. END
  7801. ELSE IF (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  7802. BEGIN
  7803. --CPU
  7804. 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])
  7805. --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]
  7806. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7807. --ORDER BY qs.total_worker_time DESC');
  7808. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7809. 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
  7810. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7811. ORDER BY qs.total_worker_time DESC),
  7812. 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
  7813. FROM TopSearch ts
  7814. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7815. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7816. 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
  7817. FROM TopFineSearch tfs
  7818. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7819. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7820. ORDER BY tfs.total_worker_time DESC');
  7821. --IO
  7822. 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])
  7823. --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]
  7824. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7825. --ORDER BY qs.total_logical_reads DESC');
  7826. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7827. 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
  7828. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7829. ORDER BY qs.total_logical_reads DESC),
  7830. 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
  7831. FROM TopSearch ts
  7832. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7833. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7834. 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
  7835. FROM TopFineSearch tfs
  7836. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7837. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7838. ORDER BY tfs.total_logical_reads DESC');
  7839. --Recompiles
  7840. 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])
  7841. --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]
  7842. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7843. --ORDER BY qs.plan_generation_num DESC');
  7844. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7845. 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
  7846. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7847. ORDER BY qs.plan_generation_num DESC),
  7848. 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
  7849. FROM TopSearch ts
  7850. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7851. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7852. 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
  7853. FROM TopFineSearch tfs
  7854. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7855. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7856. ORDER BY tfs.plan_generation_num DESC');
  7857. --Mem Grants
  7858. 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])
  7859. --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]
  7860. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7861. --ORDER BY qs.Total_grant_kb DESC');
  7862. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7863. 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
  7864. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7865. WHERE [Total_used_grant_kb] > 0
  7866. ORDER BY Total_used_grant_kb DESC, COALESCE((([Total_used_grant_kb] * 100.00) / NULLIF([Total_grant_kb],0)), 0) ASC),
  7867. 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
  7868. FROM TopSearch ts
  7869. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7870. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7871. 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
  7872. FROM TopFineSearch tfs
  7873. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7874. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7875. ORDER BY tfs.Grant2Used_Ratio ASC');
  7876. END;
  7877. -- Remove duplicates before inserting XML
  7878. IF @sqlmajorver = 9
  7879. BEGIN
  7880. 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])
  7881. 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]
  7882. FROM #tmp_dm_exec_query_stats;
  7883. END
  7884. ELSE IF @sqlmajorver = 10 AND (@sqlminorver = 0 OR (@sqlminorver = 50 AND @sqlbuild < 2500))
  7885. BEGIN
  7886. 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])
  7887. 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]
  7888. FROM #tmp_dm_exec_query_stats;
  7889. END
  7890. ELSE IF (@sqlmajorver = 10 AND @sqlminorver = 50) OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  7891. BEGIN
  7892. 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])
  7893. 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]
  7894. FROM #tmp_dm_exec_query_stats;
  7895. END
  7896. ELSE IF (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  7897. BEGIN
  7898. 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])
  7899. 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]
  7900. FROM #tmp_dm_exec_query_stats;
  7901. END;
  7902. UPDATE #dm_exec_query_stats
  7903. SET query_plan = qp.query_plan,
  7904. [text] = st.[text],
  7905. text_filtered = SUBSTRING(st.[text],
  7906. (CASE WHEN qs.statement_start_offset = 0 THEN 0 ELSE qs.statement_start_offset/2 END),
  7907. (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)))
  7908. FROM #dm_exec_query_stats qs
  7909. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
  7910. CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
  7911. -- Delete own queries
  7912. DELETE FROM #dm_exec_query_stats
  7913. WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE '%Query_Plan_Warnings%';
  7914. -- Aggregate results
  7915. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  7916. DROP TABLE #qpwarnings;
  7917. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  7918. CREATE TABLE #qpwarnings ([Deviation] VARCHAR(50), [Comment] VARCHAR(255), query_plan XML, [statement] XML)
  7919. -- Find issues
  7920. INSERT INTO #qpwarnings
  7921. SELECT 'Scalar_UDFs'AS [Deviation],
  7922. ('[WARNING: Scalar UDF found in a top resource-intensive query, which that may inhibit parallelism]') AS [Comment],
  7923. 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(
  7924. qs.text_filtered,
  7925. 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'?')
  7926. FOR XML PATH(''), TYPE) AS [statement]
  7927. FROM #dm_exec_query_stats qs
  7928. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%UserDefinedFunction%'
  7929. UNION ALL
  7930. SELECT 'Implicit_Conversion_with_IX_Scan'AS [Deviation],
  7931. ('[WARNING: Implicit type conversions found where an Index Scan is present]') AS Details ,
  7932. 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(
  7933. qs.text_filtered,
  7934. 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'?')
  7935. FOR XML PATH(''), TYPE) AS [statement]
  7936. FROM #dm_exec_query_stats qs
  7937. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%CONVERT_IMPLICIT%'
  7938. AND CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%PhysicalOp="Index Scan"%'
  7939. UNION ALL
  7940. SELECT 'Missing_Index'AS [Deviation],
  7941. ('[WARNING: One of the top resource-intensive queries may be improved by adding an index]') AS [Comment],
  7942. 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(
  7943. qs.text_filtered,
  7944. 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'?')
  7945. FOR XML PATH(''), TYPE) AS [statement]
  7946. FROM #dm_exec_query_stats qs
  7947. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%MissingIndexGroup%'
  7948. UNION ALL
  7949. SELECT 'Cursor'AS [Deviation],
  7950. ('[WARNING: Cursor usage found in a top resource-intensive query. Check if it can be rewritten as a WHILE cycle]') AS [Comment],
  7951. 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(
  7952. qs.text_filtered,
  7953. 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'?')
  7954. FOR XML PATH(''), TYPE) AS [statement]
  7955. FROM #dm_exec_query_stats qs
  7956. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<CursorType%'
  7957. UNION ALL
  7958. SELECT 'Missing_Join_Predicate'AS [Deviation],
  7959. ('[WARNING: NO JOIN predicate event fired for a top resource-intensive query]') AS [Comment],
  7960. 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(
  7961. qs.text_filtered,
  7962. 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'?')
  7963. FOR XML PATH(''), TYPE) AS [statement]
  7964. FROM #dm_exec_query_stats qs
  7965. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings NoJoinPredicate="true"%'
  7966. UNION ALL
  7967. SELECT 'Columns_with_no_Statistics'AS [Deviation],
  7968. ('[WARNING: Missing Column Statistics event fired for a top resource-intensive query]') AS [Comment],
  7969. 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(
  7970. qs.text_filtered,
  7971. 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'?')
  7972. FOR XML PATH(''), TYPE) AS [statement]
  7973. FROM #dm_exec_query_stats qs
  7974. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings ColumnsWithNoStatistics%';
  7975. IF @sqlmajorver > 10
  7976. BEGIN
  7977. INSERT INTO #qpwarnings
  7978. -- Note that currently SpillToTempDb warnings are only found in actual execution plans
  7979. SELECT 'Spill_to_TempDb'AS [Deviation],
  7980. ('[WARNING: Spill to TempDB found during a HASH or SORT operation]') AS [Comment],
  7981. 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(
  7982. qs.text_filtered,
  7983. 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'?')
  7984. FOR XML PATH(''), TYPE) AS [statement]
  7985. FROM #dm_exec_query_stats qs
  7986. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<SpillToTempDb SpillLevel%'
  7987. UNION ALL
  7988. SELECT 'Implicit_Convert_affecting_Seek_Plan'AS [Deviation],
  7989. ('[WARNING: Implicit type conversions found, which can be affecting the choice of seek plans]') AS [Comment],
  7990. 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(
  7991. qs.text_filtered,
  7992. 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'?')
  7993. FOR XML PATH(''), TYPE) AS [statement]
  7994. FROM #dm_exec_query_stats qs
  7995. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Seek Plan" Expression="CONVERT_IMPLICIT%'
  7996. UNION ALL
  7997. SELECT 'Explicit_Conversion_affecting_Cardinality'AS [Deviation],
  7998. ('[WARNING: Explicit type conversions found, which can be affecting cardinality estimates]') AS [Comment],
  7999. 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(
  8000. qs.text_filtered,
  8001. 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'?')
  8002. FOR XML PATH(''), TYPE) AS [statement]
  8003. FROM #dm_exec_query_stats qs
  8004. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Cardinality Estimate" Expression="CONVERT%'
  8005. UNION ALL
  8006. SELECT 'Implicit_Conversion_affecting_Cardinality'AS [Deviation],
  8007. ('[WARNING: Implicit type conversions found, which can be affecting cardinality estimates]') AS [Comment],
  8008. 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(
  8009. qs.text_filtered,
  8010. 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'?')
  8011. FOR XML PATH(''), TYPE) AS [statement]
  8012. FROM #dm_exec_query_stats qs
  8013. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Cardinality Estimate" Expression="CONVERT_IMPLICIT%'
  8014. UNION ALL
  8015. SELECT 'Unmatched_Indexes'AS [Deviation],
  8016. ('[WARNING: An unmatched indexes warning fired, where an index could not be used due to parameterization]') AS [Comment],
  8017. 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(
  8018. qs.text_filtered,
  8019. 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'?')
  8020. FOR XML PATH(''), TYPE) AS [statement]
  8021. FROM #dm_exec_query_stats qs
  8022. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings UnmatchedIndexes="true"%';
  8023. END;
  8024. IF (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  8025. BEGIN
  8026. INSERT INTO #qpwarnings
  8027. -- Note that currently MemoryGrant warnings are only found in actual execution plans
  8028. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8029. ('[WARNING: Granted memory was much larger than maximum used memory]') AS [Comment],
  8030. 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(
  8031. qs.text_filtered,
  8032. 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'?')
  8033. FOR XML PATH(''), TYPE) AS [statement]
  8034. FROM #dm_exec_query_stats qs
  8035. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Excessive Grant"%'
  8036. UNION ALL
  8037. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8038. ('[WARNING: Maximum used memory exceeds granted memory]') AS [Comment],
  8039. 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(
  8040. qs.text_filtered,
  8041. 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'?')
  8042. FOR XML PATH(''), TYPE) AS [statement]
  8043. FROM #dm_exec_query_stats qs
  8044. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Used More Than Granted"%'
  8045. UNION ALL
  8046. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8047. ('[WARNING: Dynamic grant increased too much when compared to initial grant request]') AS [Comment],
  8048. 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(
  8049. qs.text_filtered,
  8050. 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'?')
  8051. FOR XML PATH(''), TYPE) AS [statement]
  8052. FROM #dm_exec_query_stats qs
  8053. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Grant Increase"%'
  8054. END;
  8055. IF (SELECT COUNT(*) FROM #qpwarnings) > 0
  8056. BEGIN
  8057. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], '[WARNING: Top resource-intensive queries issued plan level warnings]' AS [Deviation]
  8058. END
  8059. ELSE
  8060. BEGIN
  8061. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], '[OK]' AS [Deviation]
  8062. END;
  8063. IF (SELECT COUNT(*) FROM #qpwarnings) > 0
  8064. BEGIN
  8065. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], [Comment], query_plan, [statement]
  8066. FROM #qpwarnings;
  8067. END;
  8068. IF (SELECT COUNT(*) FROM #dm_exec_query_stats) > 0
  8069. BEGIN
  8070. SELECT 'Performance_checks' AS [Category], 'Inefficient_Plans_Reads' AS [Check], query_plan,
  8071. (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(
  8072. text_filtered,
  8073. 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'?')
  8074. FOR XML PATH(''), TYPE) AS [statement],
  8075. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8076. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8077. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8078. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8079. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8080. [Grant2Used_Ratio],
  8081. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8082. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8083. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8084. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8085. FROM #dm_exec_query_stats
  8086. ORDER BY [Avg_Logical_Reads] DESC;
  8087. SELECT 'Performance_checks' AS [Category], 'Inefficient_Plans_CPU' AS [Check], query_plan,
  8088. (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(
  8089. text_filtered,
  8090. 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'?')
  8091. FOR XML PATH(''), TYPE) AS [statement],
  8092. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8093. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8094. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8095. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8096. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8097. [Grant2Used_Ratio],
  8098. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8099. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8100. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8101. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8102. FROM #dm_exec_query_stats
  8103. ORDER BY [Avg_Worker_Time] DESC;
  8104. SELECT 'Performance_checks' AS [Category], 'Inefficient_Memory_Use' AS [Check], query_plan,
  8105. (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(
  8106. text_filtered,
  8107. 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'?')
  8108. FOR XML PATH(''), TYPE) AS [statement],
  8109. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8110. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8111. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8112. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8113. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8114. [Grant2Used_Ratio],
  8115. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8116. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8117. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8118. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8119. FROM #dm_exec_query_stats
  8120. ORDER BY Grant2Used_Ratio ASC;
  8121. END;
  8122. END;
  8123. --------------------------------------------------------------------------------------------------------------------------------
  8124. -- Declarative Referential Integrity - Untrusted Constraints subsection
  8125. --------------------------------------------------------------------------------------------------------------------------------
  8126. IF @ptochecks = 1
  8127. BEGIN
  8128. RAISERROR (N' |-Starting Declarative Referential Integrity - Untrusted Constraints', 10, 1) WITH NOWAIT
  8129. /*
  8130. Declarative Referential Integrity (DRI), meaning “trusting” constraints will allow SQL Server to introduce optimizations that would otherwise not be possible,
  8131. such as eliminating JOINs or even not reading any table for particular queries.
  8132. 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.
  8133. */
  8134. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  8135. DROP TABLE #tblDRI;
  8136. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  8137. 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)
  8138. CONSTRAINT PK_DRI PRIMARY KEY CLUSTERED(databaseID, [schema_id], [object_id], [constraint_name]))
  8139. UPDATE #tmpdbs1
  8140. SET isdone = 0
  8141. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  8142. BEGIN
  8143. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  8144. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8145. USE ' + QUOTENAME(@dbname) + '
  8146. 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]
  8147. FROM sys.foreign_keys FKC (NOLOCK)
  8148. INNER JOIN sys.objects o (NOLOCK) ON FKC.parent_object_id = o.[object_id]
  8149. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8150. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8151. WHERE o.type = ''U'' AND FKC.is_not_trusted = 1 AND FKC.is_not_for_replication = 0
  8152. GROUP BY o.[schema_id], mst.[object_id], FKC.name, t.name, mst.name
  8153. UNION ALL
  8154. 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]
  8155. FROM sys.check_constraints CC (NOLOCK)
  8156. INNER JOIN sys.objects o (NOLOCK) ON CC.parent_object_id = o.[object_id]
  8157. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8158. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8159. WHERE o.type = ''U'' AND CC.is_not_trusted = 1 AND CC.is_not_for_replication = 0 AND CC.is_disabled = 0
  8160. GROUP BY t.[schema_id], mst.[object_id], CC.name, t.name, mst.name
  8161. ORDER BY mst.name, [constraint_name];'
  8162. BEGIN TRY
  8163. INSERT INTO #tblDRI
  8164. EXECUTE sp_executesql @sqlcmd
  8165. END TRY
  8166. BEGIN CATCH
  8167. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8168. SELECT @ErrorMessage = 'Declarative Referential Integrity subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8169. RAISERROR (@ErrorMessage, 16, 1);
  8170. END CATCH
  8171. UPDATE #tmpdbs1
  8172. SET isdone = 1
  8173. WHERE [dbid] = @dbid
  8174. END;
  8175. IF (SELECT COUNT(*) FROM #tblDRI) > 0
  8176. BEGIN
  8177. 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]
  8178. SELECT 'Performance_checks' AS [Category], 'DRI_UntrustedConstraints' AS [Information], [database_name] AS [Database_Name], constraint_name AS [Constraint_Name],
  8179. [schema_name] AS [Schema_Name], table_name AS [Table_Name], [constraint_type] AS [Constraint_Type]
  8180. FROM #tblDRI
  8181. ORDER BY [database_name], [schema_name], table_name, [constraint_type];
  8182. IF @gen_scripts = 1
  8183. BEGIN
  8184. DECLARE @strSQL1 NVARCHAR(4000)
  8185. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8186. PRINT CHAR(10) + '--############# Trust untrusted Contraints statements #############' + CHAR(10)
  8187. DECLARE cDRI CURSOR FAST_FORWARD FOR SELECT 'USE ' + [database_name] + CHAR(10) + 'GO' + CHAR(10) +
  8188. 'ALTER TABLE ' + QUOTENAME([schema_name]) + '.' + QUOTENAME(table_name) + CHAR(10) +
  8189. 'WITH CHECK CHECK CONSTRAINT ' + QUOTENAME(constraint_name) + CHAR(10) + 'GO'
  8190. FROM #tblDRI
  8191. ORDER BY [database_name], [schema_name], table_name, [constraint_type]
  8192. OPEN cDRI
  8193. FETCH NEXT FROM cDRI INTO @strSQL1
  8194. WHILE (@@FETCH_STATUS = 0)
  8195. BEGIN
  8196. PRINT @strSQL1
  8197. FETCH NEXT FROM cDRI INTO @strSQL1
  8198. END
  8199. CLOSE cDRI
  8200. DEALLOCATE cDRI
  8201. PRINT CHAR(10) + '--############# Ended Trust untrusted Contraints statements #############' + CHAR(10)
  8202. END;
  8203. END
  8204. ELSE
  8205. BEGIN
  8206. SELECT 'Performance_checks' AS [Category], 'DRI_UntrustedConstraints' AS [Check], '[OK]' AS [Deviation]
  8207. END;
  8208. END;
  8209. IF @ptochecks = 1
  8210. RAISERROR (N'|-Starting Indexes and Statistics Checks', 10, 1) WITH NOWAIT
  8211. --------------------------------------------------------------------------------------------------------------------------------
  8212. -- Statistics update subsection
  8213. --------------------------------------------------------------------------------------------------------------------------------
  8214. IF @ptochecks = 1
  8215. BEGIN
  8216. RAISERROR (N' |-Starting Statistics update', 10, 1) WITH NOWAIT
  8217. UPDATE #tmpdbs0
  8218. SET isdone = 0;
  8219. UPDATE #tmpdbs0
  8220. SET isdone = 1
  8221. WHERE [state] <> 0 OR [dbid] < 5;
  8222. UPDATE #tmpdbs0
  8223. SET isdone = 1
  8224. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8225. DECLARE @dbcmptlevel int
  8226. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  8227. DROP TABLE #tblStatsUpd;
  8228. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  8229. 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)
  8230. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8231. BEGIN
  8232. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8233. BEGIN
  8234. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid], @dbcmptlevel = [compatibility_level] FROM #tmpdbs0 WHERE isdone = 0
  8235. IF ((@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4000) OR (@sqlmajorver = 11 AND @sqlbuild >= 3000) OR @sqlmajorver > 11) AND @dbcmptlevel > 80
  8236. BEGIN
  8237. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8238. 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,
  8239. 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
  8240. FROM sys.objects AS o
  8241. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8242. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8243. INNER JOIN sys.stats AS ss ON ss.[object_id] = mst.[object_id]
  8244. CROSS APPLY sys.dm_db_stats_properties(ss.[object_id], ss.[stats_id]) AS sp
  8245. WHERE sp.[rows] > 0
  8246. AND ((sp.[rows] <= 500 AND sp.modification_counter >= 500)
  8247. OR (sp.[rows] > 500 AND sp.modification_counter >= (500 + sp.[rows] * 0.20)))'
  8248. END
  8249. ELSE
  8250. BEGIN
  8251. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8252. 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,
  8253. 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
  8254. FROM sys.sysindexes AS si
  8255. INNER JOIN sys.objects AS o ON si.id = o.[object_id]
  8256. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8257. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8258. INNER JOIN sys.stats AS ss ON ss.[object_id] = o.[object_id]
  8259. INNER JOIN sys.partitions AS p ON p.[object_id] = ss.[object_id]
  8260. LEFT JOIN sys.indexes i ON si.id = i.[object_id] AND si.indid = i.index_id
  8261. WHERE o.type <> ''S'' AND i.name IS NOT NULL
  8262. GROUP BY mst.[object_id], t.name, rowmodctr, ss.stats_id, ss.name, ss.auto_created, ss.user_created
  8263. HAVING SUM(p.[rows]) > 0
  8264. AND ((SUM(p.[rows]) <= 500 AND rowmodctr >= 500)
  8265. OR (SUM(p.[rows]) > 500 AND rowmodctr >= (500 + SUM(p.[rows]) * 0.20)))'
  8266. END
  8267. BEGIN TRY
  8268. INSERT INTO #tblStatsUpd
  8269. EXECUTE sp_executesql @sqlcmd
  8270. END TRY
  8271. BEGIN CATCH
  8272. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8273. SELECT @ErrorMessage = 'Statistics update subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8274. RAISERROR (@ErrorMessage, 16, 1);
  8275. END CATCH
  8276. UPDATE #tmpdbs0
  8277. SET isdone = 1
  8278. WHERE [dbid] = @dbid
  8279. END
  8280. END;
  8281. CREATE INDEX IX_Stats ON #tblStatsUpd([databaseID]);
  8282. IF (SELECT COUNT(*) FROM #tblStatsUpd) > 0
  8283. BEGIN
  8284. 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
  8285. BEGIN
  8286. 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]
  8287. 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],
  8288. last_updated, [rows], modification_counter, CAST((su.modification_counter*1.00/(su.[rows]*1.00))*100.0 AS DECIMAL(18,2)) AS [RowMod_Pct],
  8289. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8290. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8291. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8292. ELSE NULL
  8293. END AS [Statistic_Type],
  8294. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition], su.unfiltered_rows AS [Unfiltered_Rows]
  8295. FROM #tblStatsUpd AS su INNER JOIN master.sys.databases AS sd (NOLOCK) ON su.[databaseID] = sd.[database_id]
  8296. WHERE sd.is_auto_update_stats_on = 0
  8297. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8298. END;
  8299. 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
  8300. BEGIN
  8301. 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]
  8302. 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],
  8303. last_updated, [rows], modification_counter, CAST((su.modification_counter*1.00/(su.[rows]*1.00))*100.0 AS DECIMAL(18,2)) AS [RowMod_Pct],
  8304. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8305. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8306. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8307. ELSE NULL
  8308. END AS [Statistic_Type],
  8309. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition]
  8310. FROM #tblStatsUpd AS su INNER JOIN master.sys.databases AS sd (NOLOCK) ON su.[databaseID] = sd.[database_id]
  8311. WHERE sd.is_auto_update_stats_on = 1
  8312. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8313. END;
  8314. END
  8315. ELSE
  8316. BEGIN
  8317. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_to_update' AS [Check], '[OK]' AS [Deviation]
  8318. END;
  8319. END;
  8320. --------------------------------------------------------------------------------------------------------------------------------
  8321. -- Statistics sampling subsection
  8322. --------------------------------------------------------------------------------------------------------------------------------
  8323. IF @ptochecks = 1
  8324. BEGIN
  8325. IF (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4000) OR (@sqlmajorver = 11 AND @sqlbuild >= 3000) OR @sqlmajorver > 11
  8326. BEGIN
  8327. RAISERROR (N' |-Starting Statistics sampling', 10, 1) WITH NOWAIT
  8328. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  8329. DROP TABLE #tblStatsSamp;
  8330. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  8331. 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)
  8332. UPDATE #tmpdbs0
  8333. SET isdone = 0;
  8334. UPDATE #tmpdbs0
  8335. SET isdone = 1
  8336. WHERE [state] <> 0 OR [dbid] < 5;
  8337. UPDATE #tmpdbs0
  8338. SET isdone = 1
  8339. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8340. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8341. BEGIN
  8342. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8343. BEGIN
  8344. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid], @dbcmptlevel = [compatibility_level] FROM #tmpdbs0 WHERE isdone = 0
  8345. IF @dbcmptlevel > 80
  8346. BEGIN
  8347. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8348. 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,
  8349. 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
  8350. FROM sys.objects AS o
  8351. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8352. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8353. INNER JOIN sys.stats AS ss ON ss.[object_id] = mst.[object_id]
  8354. CROSS APPLY sys.dm_db_stats_properties(ss.[object_id], ss.[stats_id]) AS sp
  8355. WHERE sp.[rows] > 0
  8356. AND CAST((sp.rows_sampled/(sp.[rows]*1.00))*100.0 AS DECIMAL(5,2)) < 25'
  8357. BEGIN TRY
  8358. INSERT INTO #tblStatsSamp
  8359. EXECUTE sp_executesql @sqlcmd
  8360. END TRY
  8361. BEGIN CATCH
  8362. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8363. SELECT @ErrorMessage = 'Statistics sampling subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8364. RAISERROR (@ErrorMessage, 16, 1);
  8365. END CATCH
  8366. END
  8367. UPDATE #tmpdbs0
  8368. SET isdone = 1
  8369. WHERE [dbid] = @dbid
  8370. END
  8371. END;
  8372. CREATE INDEX IX_Stats ON #tblStatsSamp([databaseID]);
  8373. IF (SELECT COUNT(*) FROM #tblStatsSamp) > 0
  8374. BEGIN
  8375. 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]
  8376. 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],
  8377. last_updated, [rows], rows_sampled, CAST((rows_sampled/([rows]*1.00))*100.0 AS DECIMAL(5,2)) AS [Sample_Pct],
  8378. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8379. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8380. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8381. ELSE NULL
  8382. END AS [Statistic_Type],
  8383. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition]
  8384. FROM #tblStatsSamp AS su
  8385. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8386. END
  8387. ELSE
  8388. BEGIN
  8389. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_sampling_lt_25pct' AS [Check], '[OK]' AS [Deviation]
  8390. END;
  8391. END;
  8392. END;
  8393. --------------------------------------------------------------------------------------------------------------------------------
  8394. -- Hypothetical objects subsection
  8395. --------------------------------------------------------------------------------------------------------------------------------
  8396. IF @ptochecks = 1
  8397. BEGIN
  8398. RAISERROR (N' |-Starting Hypothetical objects', 10, 1) WITH NOWAIT
  8399. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  8400. DROP TABLE #tblHypObj;
  8401. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  8402. CREATE TABLE #tblHypObj ([DBName] sysname, [Schema] VARCHAR(100), [Table] VARCHAR(255), [Object] VARCHAR(255), [Type] VARCHAR(10));
  8403. UPDATE #tmpdbs0
  8404. SET isdone = 0;
  8405. UPDATE #tmpdbs0
  8406. SET isdone = 1
  8407. WHERE [state] <> 0 OR [dbid] = 2;
  8408. UPDATE #tmpdbs0
  8409. SET isdone = 1
  8410. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8411. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8412. BEGIN
  8413. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8414. BEGIN
  8415. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  8416. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8417. SELECT ''' + @dbname + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), i.name, ''INDEX''
  8418. FROM sys.indexes i
  8419. INNER JOIN sys.objects o ON o.[object_id] = i.[object_id]
  8420. INNER JOIN sys.tables AS mst ON mst.[object_id] = i.[object_id]
  8421. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8422. WHERE i.is_hypothetical = 1
  8423. UNION ALL
  8424. SELECT ''' + @dbname + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), s.name, ''STATISTICS''
  8425. FROM sys.stats s
  8426. INNER JOIN sys.objects o (NOLOCK) ON o.[object_id] = s.[object_id]
  8427. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = s.[object_id]
  8428. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8429. WHERE (s.name LIKE ''hind_%'' OR s.name LIKE ''_dta_stat%'') AND auto_created = 0
  8430. AND s.name NOT IN (SELECT name FROM ' + QUOTENAME(@dbname) + '.sys.indexes)'
  8431. BEGIN TRY
  8432. INSERT INTO #tblHypObj
  8433. EXECUTE sp_executesql @sqlcmd
  8434. END TRY
  8435. BEGIN CATCH
  8436. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8437. SELECT @ErrorMessage = 'Hypothetical objects subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8438. RAISERROR (@ErrorMessage, 16, 1);
  8439. END CATCH
  8440. UPDATE #tmpdbs0
  8441. SET isdone = 1
  8442. WHERE [dbid] = @dbid
  8443. END
  8444. END;
  8445. UPDATE #tmpdbs0
  8446. SET isdone = 0;
  8447. IF (SELECT COUNT([Object]) FROM #tblHypObj) > 0
  8448. BEGIN
  8449. 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]
  8450. 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]
  8451. FROM #tblHypObj
  8452. ORDER BY 2, 3, 5
  8453. IF @gen_scripts = 1
  8454. BEGIN
  8455. DECLARE @strSQL NVARCHAR(4000)
  8456. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8457. PRINT CHAR(10) + '--############# Existing Hypothetical objects drop statements #############' + CHAR(10)
  8458. 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) +
  8459. CASE WHEN [Type] = 'STATISTICS' THEN 'DROP STATISTICS ' + [Schema] + '.' + [Table] + '.' + QUOTENAME([Object]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  8460. ELSE 'DROP INDEX ' + QUOTENAME([Object]) + ' ON ' + [Schema] + '.' + [Table] + ';' + CHAR(10) + 'GO' + CHAR(10)
  8461. END
  8462. FROM #tblHypObj
  8463. ORDER BY DBName, [Table]
  8464. OPEN ITW_Stats
  8465. FETCH NEXT FROM ITW_Stats INTO @strSQL
  8466. WHILE (@@FETCH_STATUS = 0)
  8467. BEGIN
  8468. PRINT @strSQL
  8469. FETCH NEXT FROM ITW_Stats INTO @strSQL
  8470. END
  8471. CLOSE ITW_Stats
  8472. DEALLOCATE ITW_Stats
  8473. PRINT CHAR(10) + '--############# Ended Hypothetical objects drop statements #############' + CHAR(10)
  8474. END;
  8475. END
  8476. ELSE
  8477. BEGIN
  8478. SELECT 'Index_and_Stats_checks' AS [Category], 'Hypothetical_objects' AS [Check], '[OK]' AS [Deviation]
  8479. END;
  8480. END;
  8481. --------------------------------------------------------------------------------------------------------------------------------
  8482. -- Index Health Analysis subsection
  8483. --------------------------------------------------------------------------------------------------------------------------------
  8484. IF @ixfrag = 1 AND @ptochecks = 1
  8485. BEGIN
  8486. RAISERROR (N' |-Starting Index Health Analysis check', 10, 1) WITH NOWAIT
  8487. DECLARE /*@dbid int, */@objectid int, @indexid int, @partition_nr int, @type_desc NVARCHAR(60)
  8488. DECLARE @ColumnStoreGetIXSQL NVARCHAR(2000), @ColumnStoreGetIXSQL_Param NVARCHAR(1000), @HasInMem bit
  8489. DECLARE /*@sqlcmd NVARCHAR(4000), @params NVARCHAR(500),*/ @schema_name VARCHAR(100), @table_name VARCHAR(300), @KeyCols VARCHAR(4000), @distinctCnt bigint, @OptimBucketCnt bigint
  8490. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  8491. DROP TABLE #tmpIPS;
  8492. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  8493. 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,
  8494. CONSTRAINT PK_IPS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id], [partition_number]));
  8495. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  8496. DROP TABLE #tmpIPS_CI;
  8497. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  8498. 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),
  8499. CONSTRAINT PK_IPS_CI PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id], [partition_number], row_group_id));
  8500. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  8501. DROP TABLE #tmpXIS;
  8502. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  8503. 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,
  8504. CONSTRAINT PK_tmpXIS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id]));
  8505. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  8506. DROP TABLE #tmpXNCIS;
  8507. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  8508. 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,
  8509. CONSTRAINT PK_tmpXNCIS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id]));
  8510. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  8511. DROP TABLE #tblWorking;
  8512. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  8513. 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)
  8514. -- type 0 = Heap; 1 = Clustered; 2 = Nonclustered; 3 = XML; 4 = Spatial; 5 = Clustered columnstore; 6 = Nonclustered columnstore; 7 = Nonclustered hash
  8515. RAISERROR (N' |-Populating support table...', 10, 1) WITH NOWAIT
  8516. UPDATE #tmpdbs0
  8517. SET isdone = 0;
  8518. UPDATE #tmpdbs0
  8519. SET isdone = 1
  8520. WHERE [state] <> 0 OR [dbid] < 5;
  8521. UPDATE #tmpdbs0
  8522. SET isdone = 1
  8523. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8524. IF EXISTS (SELECT TOP 1 id FROM #tmpdbs0 WHERE isdone = 0)
  8525. BEGIN
  8526. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8527. BEGIN
  8528. SELECT TOP 1 @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  8529. 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
  8530. FROM [' + DB_NAME(@dbid) + '].sys.indexes si
  8531. INNER JOIN [' + DB_NAME(@dbid) + '].sys.partitions sp ON si.[object_id] = sp.[object_id] AND si.index_id = sp.index_id
  8532. INNER JOIN [' + DB_NAME(@dbid) + '].sys.tables AS mst ON mst.[object_id] = si.[object_id]
  8533. INNER JOIN [' + DB_NAME(@dbid) + '].sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8534. 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
  8535. INSERT INTO #tblWorking
  8536. EXEC sp_executesql @sqlcmd;
  8537. IF @sqlmajorver >= 12
  8538. BEGIN
  8539. SELECT @sqlcmd = 'SELECT @HasInMemOUT = ISNULL((SELECT TOP 1 1 FROM [' + DB_NAME(@dbid) + '].sys.filegroups FG where FG.[type] = ''FX''), 0)'
  8540. SET @params = N'@HasInMemOUT bit OUTPUT';
  8541. EXECUTE sp_executesql @sqlcmd, @params, @HasInMemOUT=@HasInMem OUTPUT
  8542. IF @HasInMem = 1
  8543. BEGIN
  8544. 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)
  8545. EXECUTE sp_executesql @ColumnStoreGetIXSQL, @ColumnStoreGetIXSQL_Param, @dbid_In = @dbid, @objectid_In = @objectid, @indexid_In = @indexid, @partition_nr_In = @partition_nr;
  8546. SELECT @ErrorMessage = ' |-Gathering sys.dm_db_xtp_hash_index_stats and sys.dm_db_xtp_nonclustered_index_stats data in ' + DB_NAME(@dbid) + '...'
  8547. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT;
  8548. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8549. USE [' + DB_NAME(@dbid) + '];
  8550. 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,
  8551. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8552. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8553. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8554. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8555. WHERE si.[object_id] = i.[object_id] AND si.index_id = i.index_id AND ic.is_included_column = 0
  8556. ORDER BY ic.key_ordinal
  8557. FOR XML PATH('''')), 2, 8000) AS KeyCols, NULL, NULL, 0
  8558. FROM sys.dm_db_xtp_hash_index_stats AS xhis
  8559. INNER JOIN sys.dm_db_xtp_index_stats AS xis ON xis.[object_id] = xhis.[object_id] AND xis.[index_id] = xhis.[index_id]
  8560. INNER JOIN sys.indexes AS si (NOLOCK) ON xis.[object_id] = si.[object_id] AND xis.[index_id] = si.[index_id]
  8561. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  8562. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8563. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8564. WHERE o.[type] = ''U'''
  8565. BEGIN TRY
  8566. INSERT INTO #tmpXIS
  8567. EXECUTE sp_executesql @sqlcmd
  8568. END TRY
  8569. BEGIN CATCH
  8570. 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)) + ')'
  8571. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8572. END CATCH
  8573. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8574. USE [' + DB_NAME(@dbid) + '];
  8575. SELECT ' + CONVERT(NVARCHAR(20), @dbid) + ' AS [database_id],
  8576. xis.[object_id], t.name, o.name, xis.index_id, si.name, si.type_desc,
  8577. xnis.delta_pages, xnis.internal_pages, xnis.leaf_pages, xnis.page_update_count,
  8578. xnis.page_update_retry_count, xnis.page_consolidation_count,
  8579. xnis.page_consolidation_retry_count, xnis.page_split_count, xnis.page_split_retry_count,
  8580. xnis.key_split_count, xnis.key_split_retry_count, xnis.page_merge_count, xnis.page_merge_retry_count,
  8581. xnis.key_merge_count, xnis.key_merge_retry_count,
  8582. xis.scans_started, xis.scans_retries
  8583. FROM sys.dm_db_xtp_nonclustered_index_stats AS xnis (NOLOCK)
  8584. 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]
  8585. INNER JOIN sys.indexes AS si (NOLOCK) ON xis.[object_id] = si.[object_id] AND xis.[index_id] = si.[index_id]
  8586. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  8587. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8588. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8589. WHERE o.[type] = ''U'''
  8590. BEGIN TRY
  8591. INSERT INTO #tmpXNCIS
  8592. EXECUTE sp_executesql @sqlcmd
  8593. END TRY
  8594. BEGIN CATCH
  8595. 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)) + ')'
  8596. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8597. END CATCH
  8598. END;
  8599. /*ELSE
  8600. BEGIN
  8601. SELECT @ErrorMessage = ' |-Skipping ' + DB_NAME(@dbid) + '. No memory optimized filegroup was found...'
  8602. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT;
  8603. END;*/
  8604. END;
  8605. UPDATE #tmpdbs0
  8606. SET isdone = 1
  8607. WHERE [dbid] = @dbid;
  8608. END
  8609. END;
  8610. IF EXISTS (SELECT TOP 1 database_id FROM #tmpXIS WHERE isdone = 0)
  8611. BEGIN
  8612. RAISERROR (' |-Gathering additional data on xtp hash indexes...', 10, 1) WITH NOWAIT;
  8613. WHILE (SELECT COUNT(database_id) FROM #tmpXIS WHERE isdone = 0) > 0
  8614. BEGIN
  8615. 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
  8616. 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;'
  8617. SET @params = N'@distinctCntOUT bigint OUTPUT, @OptimBucketCntOUT bigint OUTPUT';
  8618. EXECUTE sp_executesql @sqlcmd, @params, @distinctCntOUT=@distinctCnt OUTPUT, @OptimBucketCntOUT=@OptimBucketCnt OUTPUT;
  8619. UPDATE #tmpXIS
  8620. SET distinctCnt = @distinctCnt, OptimBucketCnt = @OptimBucketCnt, isdone = 1
  8621. WHERE database_id = @dbid AND [object_id] = @objectid AND [index_id] = @indexid;
  8622. END;
  8623. END;
  8624. IF (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND [type] <= 2) > 0
  8625. BEGIN
  8626. RAISERROR (' |-Gathering sys.dm_db_index_physical_stats data...', 10, 1) WITH NOWAIT;
  8627. WHILE (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND [type] <= 2) > 0
  8628. BEGIN
  8629. SELECT TOP 1 @dbid = database_id, @objectid = [object_id], @indexid = index_id, @partition_nr = partition_number
  8630. FROM #tblWorking WHERE is_done = 0 AND [type] <= 2
  8631. INSERT INTO #tmpIPS
  8632. SELECT ps.database_id, ps.[object_id], ps.index_id, ps.partition_number, SUM(ps.avg_fragmentation_in_percent), SUM(ps.page_count),
  8633. CAST((SUM(ps.page_count)*8)/1024 AS DECIMAL(26,3)) AS [size_MB], ps.record_count, ps.forwarded_record_count -- for heaps
  8634. FROM sys.dm_db_index_physical_stats(@dbid, @objectid, @indexid , @partition_nr, @ixfragscanmode) AS ps
  8635. WHERE /*ps.index_id > 0 -- ignore heaps
  8636. AND */ps.index_level = 0 -- leaf-level nodes only
  8637. AND ps.alloc_unit_type_desc = 'IN_ROW_DATA'
  8638. GROUP BY ps.database_id, ps.[object_id], ps.index_id, ps.partition_number, ps.record_count, ps.forwarded_record_count
  8639. OPTION (MAXDOP 2);
  8640. UPDATE #tblWorking
  8641. SET is_done = 1
  8642. WHERE database_id = @dbid AND [object_id] = @objectid AND index_id = @indexid AND partition_number = @partition_nr
  8643. END
  8644. END;
  8645. IF (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND type = 5) > 0
  8646. BEGIN
  8647. RAISERROR (' |-Gathering sys.column_store_row_groups data...', 10, 1) WITH NOWAIT;
  8648. WHILE (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND type IN (5,6)) > 0
  8649. BEGIN
  8650. SELECT TOP 1 @dbid = database_id, @objectid = [object_id], @indexid = index_id, @partition_nr = partition_number
  8651. FROM #tblWorking WHERE is_done = 0 AND type IN (5,6)
  8652. BEGIN TRY
  8653. 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
  8654. FROM [' + DB_NAME(@dbid) + '].sys.column_store_row_groups rg
  8655. WHERE rg.object_id = @objectid_In
  8656. AND rg.index_id = @indexid_In
  8657. AND rg.partition_number = @partition_nr_In
  8658. --AND rg.state = 3 -- Only COMPRESSED row groups
  8659. 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
  8660. OPTION (MAXDOP 2)'
  8661. SET @ColumnStoreGetIXSQL_Param = N'@dbid_In int, @objectid_In int, @indexid_In int, @partition_nr_In int';
  8662. 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)
  8663. EXECUTE sp_executesql @ColumnStoreGetIXSQL, @ColumnStoreGetIXSQL_Param, @dbid_In = @dbid, @objectid_In = @objectid, @indexid_In = @indexid, @partition_nr_In = @partition_nr;
  8664. END TRY
  8665. BEGIN CATCH
  8666. 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)) + ')'
  8667. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8668. END CATCH
  8669. UPDATE #tblWorking
  8670. SET is_done = 1
  8671. WHERE database_id = @dbid AND [object_id] = @objectid AND index_id = @indexid AND partition_number = @partition_nr
  8672. END
  8673. END;
  8674. -- Check for index fragmentation over 5 pct when index has more than 1 extent allocated, or in CCI, all compressed row groups
  8675. IF (SELECT COUNT(*) FROM #tmpIPS WHERE fragmentation > 5 AND [page_count] > 8) > 0
  8676. OR (SELECT COUNT(*) FROM #tmpIPS_CI WHERE fragmentation > 5 AND [state] = 3) > 0
  8677. BEGIN
  8678. 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]
  8679. 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,
  8680. ips.page_count, ips.[size_MB], ips.record_count, ips.forwarded_record_count, -- for heaps
  8681. NULL AS row_group_id, NULL AS [Comment]
  8682. FROM #tmpIPS ips
  8683. 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
  8684. WHERE ips.fragmentation > 5 AND ips.[page_count] > 8
  8685. UNION ALL
  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, ipsci.partition_number, ipsci.fragmentation,
  8687. ipsci.page_count, ipsci.[size_MB], ipsci.record_count, NULL AS forwarded_record_count, ipsci.row_group_id,
  8688. '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]
  8689. FROM #tmpIPS_CI ipsci
  8690. 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
  8691. WHERE ipsci.fragmentation > 5 AND ipsci.[state] = 3
  8692. ORDER BY fragmentation DESC, [page_count] ASC
  8693. END
  8694. ELSE
  8695. BEGIN
  8696. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Fragmentation' AS [Check], '[OK]' AS [Deviation]
  8697. END;
  8698. IF @sqlmajorver >= 12
  8699. BEGIN
  8700. -- For the below values, your mileage may vary. Assuming more than 50 percent empty buckets and an average chain length over 5 requires investigation
  8701. -- http://blogs.technet.com/b/dataplatforminsider/archive/2014/01/30/in-memory-oltp-index-troubleshooting-part-ii.aspx
  8702. IF (SELECT COUNT(*) FROM #tmpXIS WHERE FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) > 50 AND [avg_chain_length] > 5) > 0
  8703. BEGIN
  8704. 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]
  8705. 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,
  8706. distinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8707. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8708. FROM #tmpXIS
  8709. WHERE FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) > 50 AND [avg_chain_length] > 5
  8710. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8711. END
  8712. ELSE
  8713. BEGIN
  8714. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_AvgChain_EmptyBuckets' AS [Check], '[OK]' AS [Deviation]
  8715. END;
  8716. IF (SELECT COUNT(*) FROM #tmpXIS WHERE total_bucket_count > distinctCnt) > 0
  8717. BEGIN
  8718. 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]
  8719. 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,
  8720. distinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8721. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8722. FROM #tmpXIS
  8723. WHERE total_bucket_count > distinctCnt
  8724. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8725. END
  8726. ELSE
  8727. BEGIN
  8728. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooManyBuckets' AS [Check], '[OK]' AS [Deviation]
  8729. END;
  8730. IF (SELECT COUNT(*) FROM #tmpXIS WHERE total_bucket_count < distinctCnt) > 0
  8731. BEGIN
  8732. 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]
  8733. 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,
  8734. distinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8735. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8736. FROM #tmpXIS
  8737. WHERE total_bucket_count < distinctCnt
  8738. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8739. END
  8740. ELSE
  8741. BEGIN
  8742. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooFewBuckets' AS [Check], '[OK]' AS [Deviation]
  8743. END;
  8744. -- For the below values, your mileage may vary. Assuming more than 5 percent retries requires investigation .
  8745. -- https://msdn.microsoft.com/en-us/library/dn645468.aspx
  8746. 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
  8747. OR FLOOR((CAST(page_consolidation_retry_count AS FLOAT)/CASE WHEN page_consolidation_count = 0 THEN 1 ELSE page_consolidation_count END) * 100) > 5
  8748. OR FLOOR((CAST(page_split_retry_count AS FLOAT)/CASE WHEN page_split_count = 0 THEN 1 ELSE page_split_count END) * 100) > 5
  8749. OR FLOOR((CAST(key_split_retry_count AS FLOAT)/CASE WHEN key_split_count = 0 THEN 1 ELSE key_split_count END) * 100) > 5
  8750. OR FLOOR((CAST(page_merge_retry_count AS FLOAT)/CASE WHEN page_merge_count = 0 THEN 1 ELSE page_merge_count END) * 100) > 5
  8751. OR FLOOR((CAST(key_merge_retry_count AS FLOAT)/CASE WHEN key_merge_count = 0 THEN 1 ELSE key_merge_count END) * 100) > 5
  8752. ) > 0
  8753. BEGIN
  8754. 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]
  8755. 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,
  8756. delta_pages, internal_pages, leaf_pages,
  8757. 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],
  8758. 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],
  8759. 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],
  8760. 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],
  8761. 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],
  8762. 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]
  8763. FROM #tmpXNCIS
  8764. WHERE FLOOR((CAST(page_update_retry_count AS FLOAT)/CASE WHEN page_update_count = 0 THEN 1 ELSE page_update_count END) * 100) > 5
  8765. OR FLOOR((CAST(page_consolidation_retry_count AS FLOAT)/CASE WHEN page_consolidation_count = 0 THEN 1 ELSE page_consolidation_count END) * 100) > 5
  8766. OR FLOOR((CAST(page_split_retry_count AS FLOAT)/CASE WHEN page_split_count = 0 THEN 1 ELSE page_split_count END) * 100) > 5
  8767. OR FLOOR((CAST(key_split_retry_count AS FLOAT)/CASE WHEN key_split_count = 0 THEN 1 ELSE key_split_count END) * 100) > 5
  8768. OR FLOOR((CAST(page_merge_retry_count AS FLOAT)/CASE WHEN page_merge_count = 0 THEN 1 ELSE page_merge_count END) * 100) > 5
  8769. OR FLOOR((CAST(key_merge_retry_count AS FLOAT)/CASE WHEN key_merge_count = 0 THEN 1 ELSE key_merge_count END) * 100) > 5
  8770. ORDER BY [database_name], [schema_name], table_name, [leaf_pages] DESC;
  8771. END;
  8772. END;
  8773. END
  8774. ELSE
  8775. BEGIN
  8776. RAISERROR(' |- [INFORMATION: "Index Health Analysis" check is disabled]', 10, 1, N'disallow_ixfrag')
  8777. --RETURN
  8778. END;
  8779. --------------------------------------------------------------------------------------------------------------------------------
  8780. -- Duplicate or Redundant indexes subsection (clustered, non-clustered, clustered and non-clustered columnstore indexes only)
  8781. --------------------------------------------------------------------------------------------------------------------------------
  8782. IF @ptochecks = 1
  8783. BEGIN
  8784. RAISERROR (N' |-Starting Duplicate or Redundant indexes', 10, 1) WITH NOWAIT
  8785. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  8786. DROP TABLE #tblIxs1;
  8787. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  8788. CREATE TABLE #tblIxs1 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  8789. [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),
  8790. KeyCols VARCHAR(4000), KeyColsOrdered VARCHAR(4000), IncludedCols VARCHAR(4000) NULL, IncludedColsOrdered VARCHAR(4000) NULL, AllColsOrdered VARCHAR(4000) NULL, [KeyCols_data_length_bytes] int,
  8791. CONSTRAINT PK_Ixs PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]));
  8792. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  8793. DROP TABLE #tblCode;
  8794. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  8795. CREATE TABLE #tblCode ([DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [indexName] VARCHAR(200), type_desc NVARCHAR(60));
  8796. UPDATE #tmpdbs1
  8797. SET isdone = 0;
  8798. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  8799. BEGIN
  8800. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  8801. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8802. USE ' + QUOTENAME(@dbname) + ';
  8803. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  8804. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, mi.index_id AS indexID,
  8805. mi.[name] AS Index_Name, mi.[type] AS [indexType], mi.is_primary_key, mi.[is_unique_constraint], mi.is_unique, mi.is_disabled,
  8806. mi.fill_factor, mi.is_padded, ' + CASE WHEN @sqlmajorver > 9 THEN 'mi.has_filter, mi.filter_definition,' ELSE 'NULL, NULL,' END + '
  8807. SUBSTRING(( SELECT '','' + ac.name FROM sys.tables AS st
  8808. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8809. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8810. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8811. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  8812. ORDER BY ic.key_ordinal
  8813. FOR XML PATH('''')), 2, 8000) AS KeyCols,
  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 ac.name
  8820. FOR XML PATH('''')), 2, 8000) AS KeyColsOrdered,
  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 = 1
  8826. ORDER BY ic.key_ordinal
  8827. FOR XML PATH('''')), 2, 8000) AS IncludedCols,
  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 ac.name
  8834. FOR XML PATH('''')), 2, 8000) AS IncludedColsOrdered,
  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
  8840. ORDER BY ac.name
  8841. FOR XML PATH('''')), 2, 8000) AS AllColsOrdered,
  8842. (SELECT SUM(CASE sty.name WHEN ''nvarchar'' THEN sc.max_length/2 ELSE sc.max_length END) FROM sys.indexes AS i
  8843. INNER JOIN sys.tables AS t ON t.[object_id] = i.[object_id]
  8844. INNER JOIN sys.schemas ss ON ss.[schema_id] = t.[schema_id]
  8845. INNER JOIN sys.index_columns AS sic ON sic.object_id = mst.object_id AND sic.index_id = mi.index_id
  8846. INNER JOIN sys.columns AS sc ON sc.object_id = t.object_id AND sc.column_id = sic.column_id
  8847. INNER JOIN sys.types AS sty ON sc.user_type_id = sty.user_type_id
  8848. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND sic.key_ordinal > 0) AS [KeyCols_data_length_bytes]
  8849. FROM sys.indexes AS mi
  8850. INNER JOIN sys.tables AS mst ON mst.[object_id] = mi.[object_id]
  8851. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8852. WHERE mi.type IN (1,2,5,6) AND mst.is_ms_shipped = 0
  8853. ORDER BY objectName
  8854. OPTION (MAXDOP 2);'
  8855. BEGIN TRY
  8856. INSERT INTO #tblIxs1
  8857. EXECUTE sp_executesql @sqlcmd
  8858. END TRY
  8859. BEGIN CATCH
  8860. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8861. SELECT @ErrorMessage = 'Duplicate or Redundant indexes subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8862. RAISERROR (@ErrorMessage, 16, 1);
  8863. END CATCH
  8864. UPDATE #tmpdbs1
  8865. SET isdone = 1
  8866. WHERE [dbid] = @dbid;
  8867. END
  8868. 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]
  8869. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8870. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))) > 0
  8871. BEGIN
  8872. 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]
  8873. 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],
  8874. 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,
  8875. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  8876. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8877. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8878. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8879. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8880. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8881. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8882. 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
  8883. ORDER BY I.DatabaseName, I.[objectName], I.[indexID]
  8884. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes_toDrop' AS [Check], I.[DatabaseName], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name],
  8885. 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,
  8886. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  8887. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8888. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8889. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8890. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8891. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8892. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8893. AND I.[indexID] NOT IN (
  8894. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8895. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8896. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8897. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8898. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8899. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8900. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8901. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8902. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8903. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8904. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8905. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8906. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8907. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8908. ))
  8909. 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
  8910. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8911. DECLARE @strSQL2 NVARCHAR(4000), @DatabaseName sysname, @indexName sysname
  8912. IF @gen_scripts = 1
  8913. BEGIN
  8914. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8915. PRINT CHAR(10) + '/*
  8916. 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.
  8917. 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.
  8918. */'
  8919. PRINT CHAR(10) + '--############# Existing Duplicate indexes drop statements #############' + CHAR(10)
  8920. 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) +
  8921. 'DROP INDEX ' + QUOTENAME(I.[indexName]) + ' ON ' + QUOTENAME(I.[schemaName]) + '.' + QUOTENAME(I.[objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  8922. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8923. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8924. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8925. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8926. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8927. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8928. AND I.[indexID] NOT IN (
  8929. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8930. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8931. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8932. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8933. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8934. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8935. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8936. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8937. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8938. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8939. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8940. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8941. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8942. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8943. ))
  8944. GROUP BY I.[databaseID], I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered
  8945. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8946. OPEN Dup_Stats
  8947. FETCH NEXT FROM Dup_Stats INTO @strSQL2
  8948. WHILE (@@FETCH_STATUS = 0)
  8949. BEGIN
  8950. PRINT @strSQL2
  8951. FETCH NEXT FROM Dup_Stats INTO @strSQL2
  8952. END
  8953. CLOSE Dup_Stats
  8954. DEALLOCATE Dup_Stats
  8955. PRINT '--############# Ended Duplicate indexes drop statements #############' + CHAR(10)
  8956. END;
  8957. RAISERROR (N' |-Starting index search in sql modules...', 10, 1) WITH NOWAIT
  8958. DECLARE Dup_HardCoded CURSOR FAST_FORWARD FOR SELECT I.[DatabaseName],I.[indexName]
  8959. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8960. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8961. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8962. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8963. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8964. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8965. AND I.[indexID] NOT IN (
  8966. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8967. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8968. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8969. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8970. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8971. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8972. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8973. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8974. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8975. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8976. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8977. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8978. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8979. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8980. ))
  8981. GROUP BY I.[databaseID], I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered
  8982. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8983. OPEN Dup_HardCoded
  8984. FETCH NEXT FROM Dup_HardCoded INTO @DatabaseName,@indexName
  8985. WHILE (@@FETCH_STATUS = 0)
  8986. BEGIN
  8987. SET @sqlcmd = 'USE [' + @DatabaseName + '];
  8988. SELECT ''' + @DatabaseName + ''' AS [database], ss.name AS [schemaName], so.name AS [objectName], ''' + @indexName + ''' AS indexName, so.type_desc
  8989. FROM sys.sql_modules sm
  8990. INNER JOIN sys.objects so ON sm.[object_id] = so.[object_id]
  8991. INNER JOIN sys.schemas ss ON ss.[schema_id] = so.[schema_id]
  8992. WHERE sm.[definition] LIKE ''%' + @indexName + '%'''
  8993. INSERT INTO #tblCode
  8994. EXECUTE sp_executesql @sqlcmd
  8995. FETCH NEXT FROM Dup_HardCoded INTO @DatabaseName,@indexName
  8996. END
  8997. CLOSE Dup_HardCoded
  8998. DEALLOCATE Dup_HardCoded
  8999. RAISERROR (N' |-Ended index search in sql modules', 10, 1) WITH NOWAIT
  9000. IF (SELECT COUNT(*) FROM #tblCode) > 0
  9001. BEGIN
  9002. 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]
  9003. SELECT [DatabaseName],[schemaName],[objectName] AS [referedIn_objectName], indexName AS [referenced_indexName], type_desc AS [refered_objectType]
  9004. FROM #tblCode
  9005. ORDER BY [DatabaseName], [objectName]
  9006. END
  9007. ELSE
  9008. BEGIN
  9009. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes_HardCoded' AS [Check], '[OK]' AS [Deviation]
  9010. END
  9011. END
  9012. ELSE
  9013. BEGIN
  9014. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes' AS [Check], '[OK]' AS [Deviation]
  9015. END;
  9016. 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]
  9017. AND (I.[KeyCols] <> I2.[KeyCols] OR I.IncludedCols <> I2.IncludedCols)
  9018. AND (((I.[KeyColsOrdered] <> I2.[KeyColsOrdered] OR I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9019. 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)
  9020. OR I.[AllColsOrdered] = I2.[AllColsOrdered]))
  9021. OR (I.[KeyColsOrdered] <> I2.[KeyColsOrdered] AND I.IncludedColsOrdered = I2.IncludedColsOrdered)
  9022. OR (I.[KeyColsOrdered] = I2.[KeyColsOrdered] AND I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9023. 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)))
  9024. AND I.indexID NOT IN (SELECT I3.[indexID]
  9025. FROM #tblIxs1 I3 INNER JOIN #tblIxs1 I4
  9026. ON I3.[databaseID] = I4.[databaseID] AND I3.[objectID] = I4.[objectID] AND I3.[indexID] <> I4.[indexID]
  9027. AND I3.[KeyCols] = I4.[KeyCols] AND (I3.IncludedCols = I4.IncludedCols OR (I3.IncludedCols IS NULL AND I4.IncludedCols IS NULL))
  9028. WHERE I3.[databaseID] = I.[databaseID] AND I3.[objectID] = I.[objectID]
  9029. GROUP BY I3.[indexID])
  9030. WHERE I.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9031. AND I2.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9032. AND I.is_unique_constraint = 0 -- no unique constraints
  9033. AND I2.is_unique_constraint = 0 -- no unique constraints
  9034. ) > 0
  9035. BEGIN
  9036. 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]
  9037. 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],
  9038. I.[indexID], I.[indexName] AS [Index_Name], I.is_unique, I.fill_factor, I.is_padded, I.has_filter, I.filter_definition,
  9039. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedColsOrdered IS NULL THEN I.[KeyColsOrdered] ELSE I.[KeyColsOrdered] + ',' + I.IncludedColsOrdered END AS [KeyInclColsOrdered]
  9040. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  9041. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  9042. AND (((I.[KeyColsOrdered] <> I2.[KeyColsOrdered] OR I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9043. 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)
  9044. OR I.[AllColsOrdered] = I2.[AllColsOrdered]))
  9045. OR (I.[KeyColsOrdered] <> I2.[KeyColsOrdered] AND I.IncludedColsOrdered = I2.IncludedColsOrdered)
  9046. OR (I.[KeyColsOrdered] = I2.[KeyColsOrdered] AND I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9047. 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)))
  9048. AND I.indexID NOT IN (SELECT I3.[indexID]
  9049. FROM #tblIxs1 I3 INNER JOIN #tblIxs1 I4
  9050. ON I3.[databaseID] = I4.[databaseID] AND I3.[objectID] = I4.[objectID] AND I3.[indexID] <> I4.[indexID]
  9051. AND I3.[KeyCols] = I4.[KeyCols] AND (I3.IncludedCols = I4.IncludedCols OR (I3.IncludedCols IS NULL AND I4.IncludedCols IS NULL))
  9052. WHERE I3.[databaseID] = I.[databaseID] AND I3.[objectID] = I.[objectID]
  9053. GROUP BY I3.[indexID])
  9054. WHERE I.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9055. AND I2.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9056. AND I.is_unique_constraint = 0 -- no unique constraints
  9057. AND I2.is_unique_constraint = 0 -- no unique constraints
  9058. 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
  9059. ORDER BY I.DatabaseName, I.[objectName], I.[KeyColsOrdered], I.IncludedColsOrdered, I.[indexID]
  9060. END
  9061. ELSE
  9062. BEGIN
  9063. SELECT 'Index_and_Stats_checks' AS [Category], 'Redundant_Indexes' AS [Check], '[OK]' AS [Deviation]
  9064. END;
  9065. END;
  9066. --------------------------------------------------------------------------------------------------------------------------------
  9067. -- Unused and rarely used indexes subsection
  9068. --------------------------------------------------------------------------------------------------------------------------------
  9069. IF @ptochecks = 1
  9070. BEGIN
  9071. RAISERROR (N' |-Starting Unused and rarely used indexes', 10, 1) WITH NOWAIT
  9072. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  9073. DROP TABLE #tblIxs2;
  9074. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  9075. CREATE TABLE #tblIxs2 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  9076. [indexID] int, [indexName] VARCHAR(200), [Hits] bigint NULL, [Reads_Ratio] DECIMAL(5,2), [Writes_Ratio] DECIMAL(5,2),
  9077. user_updates bigint, last_user_seek DATETIME NULL, last_user_scan DATETIME NULL, last_user_lookup DATETIME NULL,
  9078. last_user_update DATETIME NULL, is_unique bit, [type] tinyint, is_primary_key bit, is_unique_constraint bit, is_disabled bit,
  9079. CONSTRAINT PK_Ixs2 PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]))
  9080. UPDATE #tmpdbs1
  9081. SET isdone = 0;
  9082. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9083. BEGIN
  9084. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9085. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9086. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9087. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, si.index_id AS indexID, si.[name] AS Index_Name,
  9088. (s.user_seeks + s.user_scans + s.user_lookups) AS [Hits],
  9089. 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 /
  9090. 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],
  9091. RTRIM(CONVERT(NVARCHAR(10),CAST(CASE WHEN s.user_updates = 0 THEN 0 ELSE CONVERT(REAL, s.user_updates) * 100 /
  9092. 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],
  9093. s.user_updates,
  9094. MAX(s.last_user_seek) AS last_user_seek,
  9095. MAX(s.last_user_scan) AS last_user_scan,
  9096. MAX(s.last_user_lookup) AS last_user_lookup,
  9097. MAX(s.last_user_update) AS last_user_update,
  9098. si.is_unique, si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9099. FROM sys.indexes AS si (NOLOCK)
  9100. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  9101. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = si.[object_id]
  9102. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9103. INNER JOIN sys.dm_db_index_usage_stats AS s (NOLOCK) ON s.database_id = ' + CONVERT(VARCHAR(8), @dbid) + '
  9104. AND s.object_id = si.object_id AND s.index_id = si.index_id
  9105. WHERE mst.is_ms_shipped = 0
  9106. --AND OBJECTPROPERTY(o.object_id,''IsUserTable'') = 1 -- sys.tables only returns type U
  9107. AND si.type IN (2,6) -- non-clustered and non-clustered columnstore indexes only
  9108. AND si.is_primary_key = 0 -- no primary keys
  9109. AND si.is_unique_constraint = 0 -- no unique constraints
  9110. --AND si.is_unique = 0 -- no alternate keys
  9111. 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,
  9112. si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9113. ORDER BY objectName
  9114. OPTION (MAXDOP 2);'
  9115. BEGIN TRY
  9116. INSERT INTO #tblIxs2
  9117. EXECUTE sp_executesql @sqlcmd
  9118. END TRY
  9119. BEGIN CATCH
  9120. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9121. SELECT @ErrorMessage = 'Unused and rarely used indexes subsection - Error raised in TRY block 1 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9122. RAISERROR (@ErrorMessage, 16, 1);
  9123. END CATCH
  9124. UPDATE #tmpdbs1
  9125. SET isdone = 1
  9126. WHERE [dbid] = @dbid
  9127. END
  9128. UPDATE #tmpdbs1
  9129. SET isdone = 0;
  9130. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9131. BEGIN
  9132. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9133. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9134. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9135. 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,
  9136. si.[name] AS Index_Name, 0, 0, 0, 0, NULL, NULL, NULL, NULL,
  9137. si.is_unique, si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9138. FROM sys.indexes AS si (NOLOCK)
  9139. INNER JOIN sys.objects AS so (NOLOCK) ON si.object_id = so.object_id
  9140. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = si.[object_id]
  9141. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9142. WHERE OBJECTPROPERTY(so.object_id,''IsUserTable'') = 1
  9143. AND mst.is_ms_shipped = 0
  9144. AND si.index_id NOT IN (SELECT s.index_id
  9145. FROM sys.dm_db_index_usage_stats s
  9146. WHERE s.object_id = si.object_id
  9147. AND si.index_id = s.index_id
  9148. AND database_id = ' + CONVERT(VARCHAR(8), @dbid) + ')
  9149. AND si.name IS NOT NULL
  9150. AND si.type IN (2,6) -- non-clustered and non-clustered columnstore indexes only
  9151. AND si.is_primary_key = 0 -- no primary keys
  9152. AND si.is_unique_constraint = 0 -- no unique constraints
  9153. --AND si.is_unique = 0 -- no alternate keys
  9154. '
  9155. BEGIN TRY
  9156. INSERT INTO #tblIxs2
  9157. EXECUTE sp_executesql @sqlcmd
  9158. END TRY
  9159. BEGIN CATCH
  9160. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9161. SELECT @ErrorMessage = 'Unused and rarely used indexes subsection - Error raised in TRY block 2 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9162. RAISERROR (@ErrorMessage, 16, 1);
  9163. END CATCH
  9164. UPDATE #tmpdbs1
  9165. SET isdone = 1
  9166. WHERE [dbid] = @dbid
  9167. END;
  9168. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 /*AND is_disabled = 0*/) > 0
  9169. BEGIN
  9170. 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]
  9171. 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,
  9172. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9173. user_updates, last_user_update
  9174. FROM #tblIxs2
  9175. WHERE [Hits] = 0 AND last_user_update > 0
  9176. UNION ALL
  9177. 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,
  9178. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9179. user_updates, last_user_update
  9180. FROM #tblIxs2
  9181. WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)
  9182. ORDER BY [Information], [Database_Name], [Table_Name], [R/W_Ratio] DESC;
  9183. IF @gen_scripts = 1
  9184. BEGIN
  9185. DECLARE @strSQL3 NVARCHAR(4000)
  9186. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9187. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 AND last_user_update > 0) > 0
  9188. BEGIN
  9189. PRINT CHAR(10) + '--############# Existing unused indexes with updates drop statements #############' + CHAR(10)
  9190. 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) +
  9191. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9192. FROM #tblIxs2
  9193. WHERE [Hits] = 0 AND last_user_update > 0
  9194. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC;
  9195. OPEN Un_Stats
  9196. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9197. WHILE (@@FETCH_STATUS = 0)
  9198. BEGIN
  9199. PRINT @strSQL3
  9200. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9201. END
  9202. CLOSE Un_Stats
  9203. DEALLOCATE Un_Stats
  9204. PRINT CHAR(10) + '--############# Ended unused indexes with updates drop statements #############' + CHAR(10)
  9205. END;
  9206. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)) > 0
  9207. BEGIN
  9208. PRINT CHAR(10) + '--############# Existing unused indexes with no updates drop statements #############' + CHAR(10)
  9209. 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) +
  9210. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9211. FROM #tblIxs2
  9212. WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)
  9213. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC;
  9214. OPEN Un_Stats
  9215. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9216. WHILE (@@FETCH_STATUS = 0)
  9217. BEGIN
  9218. PRINT @strSQL3
  9219. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9220. END
  9221. CLOSE Un_Stats
  9222. DEALLOCATE Un_Stats
  9223. PRINT CHAR(10) + '--############# Ended unused indexes with no updates drop statements #############' + CHAR(10)
  9224. END
  9225. END;
  9226. END
  9227. ELSE
  9228. BEGIN
  9229. SELECT 'Index_and_Stats_checks' AS [Category], 'Unused_Indexes' AS [Check], '[OK]' AS [Deviation]
  9230. END;
  9231. 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
  9232. BEGIN
  9233. 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]
  9234. 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,
  9235. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9236. user_updates, last_user_seek, last_user_scan, last_user_lookup, last_user_update
  9237. FROM #tblIxs2
  9238. WHERE [Hits] > 0 AND [Reads_Ratio] < 5
  9239. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC
  9240. IF @gen_scripts = 1
  9241. BEGIN
  9242. DECLARE @strSQL4 NVARCHAR(4000)
  9243. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9244. PRINT CHAR(10) + '--############# Existing rarely used indexes drop statements #############' + CHAR(10)
  9245. 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) +
  9246. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9247. FROM #tblIxs2
  9248. WHERE [Hits] > 0 AND [Reads_Ratio] < 5
  9249. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC
  9250. OPEN curRarUsed
  9251. FETCH NEXT FROM curRarUsed INTO @strSQL4
  9252. WHILE (@@FETCH_STATUS = 0)
  9253. BEGIN
  9254. PRINT @strSQL4
  9255. FETCH NEXT FROM curRarUsed INTO @strSQL4
  9256. END
  9257. CLOSE curRarUsed
  9258. DEALLOCATE curRarUsed
  9259. PRINT '--############# Ended rarely used indexes drop statements #############' + CHAR(10)
  9260. END;
  9261. END
  9262. ELSE
  9263. BEGIN
  9264. SELECT 'Index_and_Stats_checks' AS [Category], 'Rarely_Used_Indexes' AS [Check], '[OK]' AS [Deviation]
  9265. END;
  9266. END;
  9267. --------------------------------------------------------------------------------------------------------------------------------
  9268. -- Indexes with large keys (> 900 bytes) subsection
  9269. --------------------------------------------------------------------------------------------------------------------------------
  9270. IF @ptochecks = 1
  9271. BEGIN
  9272. RAISERROR (N' |-Starting Indexes with large keys (> 900 bytes)', 10, 1) WITH NOWAIT
  9273. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [KeyCols_data_length_bytes] > 900) > 0
  9274. BEGIN
  9275. 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]
  9276. 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],
  9277. I.KeyCols, [KeyCols_data_length_bytes]
  9278. FROM #tblIxs1 I
  9279. WHERE [KeyCols_data_length_bytes] > 900
  9280. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9281. END
  9282. ELSE
  9283. BEGIN
  9284. SELECT 'Index_and_Stats_checks' AS [Category], 'Large_Index_Key' AS [Check], '[OK]' AS [Deviation]
  9285. END;
  9286. END;
  9287. --------------------------------------------------------------------------------------------------------------------------------
  9288. -- Indexes with fill factor < 80 pct subsection
  9289. --------------------------------------------------------------------------------------------------------------------------------
  9290. IF @ptochecks = 1
  9291. BEGIN
  9292. RAISERROR (N' |-Starting Indexes with fill factor < 80 pct', 10, 1) WITH NOWAIT
  9293. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [fill_factor] BETWEEN 1 AND 79) > 0
  9294. BEGIN
  9295. 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]
  9296. 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],
  9297. [fill_factor], I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  9298. FROM #tblIxs1 I
  9299. WHERE [fill_factor] BETWEEN 1 AND 79
  9300. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9301. END
  9302. ELSE
  9303. BEGIN
  9304. SELECT 'Index_and_Stats_checks' AS [Category], 'Low_Fill_Factor' AS [Check], '[OK]' AS [Deviation]
  9305. END;
  9306. END;
  9307. --------------------------------------------------------------------------------------------------------------------------------
  9308. -- Disabled indexes subsection
  9309. --------------------------------------------------------------------------------------------------------------------------------
  9310. IF @ptochecks = 1
  9311. BEGIN
  9312. RAISERROR (N' |-Starting Disabled indexes', 10, 1) WITH NOWAIT
  9313. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [is_disabled] = 1) > 0
  9314. BEGIN
  9315. SELECT 'Index_and_Stats_checks' AS [Category], 'Disabled_IXs' AS [Check], '[WARNING: Some indexes are disabled. Revise the need to maintain these]' AS [Deviation]
  9316. 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],
  9317. CASE WHEN [indexType] = 1 THEN 'Clustered'
  9318. WHEN [indexType] = 2 THEN 'Non-clustered'
  9319. WHEN [indexType] = 3 THEN 'Clustered columnstore'
  9320. ELSE 'Non-clustered columnstore' END AS [Index_Type],
  9321. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  9322. FROM #tblIxs1 I
  9323. WHERE [is_disabled] = 1
  9324. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9325. END
  9326. ELSE
  9327. BEGIN
  9328. SELECT 'Index_and_Stats_checks' AS [Category], 'Disabled_IXs' AS [Check], '[OK]' AS [Deviation]
  9329. END;
  9330. END;
  9331. --------------------------------------------------------------------------------------------------------------------------------
  9332. -- Non-unique clustered indexes subsection
  9333. --------------------------------------------------------------------------------------------------------------------------------
  9334. IF @ptochecks = 1
  9335. BEGIN
  9336. RAISERROR (N' |-Starting Non-unique clustered indexes', 10, 1) WITH NOWAIT
  9337. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [is_unique] = 0 AND indexID = 1) > 0
  9338. BEGIN
  9339. 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]
  9340. 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]
  9341. FROM #tblIxs1 I
  9342. WHERE [is_unique] = 0 AND indexID = 1
  9343. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName]
  9344. END
  9345. ELSE
  9346. BEGIN
  9347. SELECT 'Index_and_Stats_checks' AS [Category], 'NonUnique_CIXs' AS [Check], '[OK]' AS [Deviation]
  9348. END;
  9349. END;
  9350. --------------------------------------------------------------------------------------------------------------------------------
  9351. -- Clustered Indexes with GUIDs in key subsection
  9352. --------------------------------------------------------------------------------------------------------------------------------
  9353. IF @ptochecks = 1
  9354. BEGIN
  9355. RAISERROR (N' |-Starting Clustered Indexes with GUIDs in key', 10, 1) WITH NOWAIT
  9356. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  9357. DROP TABLE #tblIxs6;
  9358. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  9359. CREATE TABLE #tblIxs6 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  9360. [indexID] int, [indexName] VARCHAR(200), [indexType] tinyint, [is_unique_constraint] bit, is_unique bit, is_disabled bit, fill_factor tinyint, is_padded bit,
  9361. KeyCols VARCHAR(4000), KeyColsOrdered VARCHAR(4000), Key_has_GUID int,
  9362. CONSTRAINT PK_Ixs3 PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]));
  9363. UPDATE #tmpdbs1
  9364. SET isdone = 0;
  9365. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9366. BEGIN
  9367. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9368. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  9369. USE ' + QUOTENAME(@dbname) + ';
  9370. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9371. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, mi.index_id AS indexID,
  9372. mi.[name] AS Index_Name, mi.[type] AS [indexType], mi.[is_unique_constraint], mi.is_unique, mi.is_disabled,
  9373. mi.fill_factor, mi.is_padded,
  9374. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  9375. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  9376. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  9377. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9378. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  9379. ORDER BY ic.key_ordinal
  9380. FOR XML PATH('''')), 2, 8000) AS KeyCols,
  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 ac.name
  9387. FOR XML PATH('''')), 2, 8000) AS KeyColsOrdered,
  9388. (SELECT COUNT(sty.name) FROM sys.indexes AS i
  9389. INNER JOIN sys.tables AS t ON t.[object_id] = i.[object_id]
  9390. INNER JOIN sys.schemas ss ON ss.[schema_id] = t.[schema_id]
  9391. INNER JOIN sys.index_columns AS sic ON sic.object_id = mst.object_id AND sic.index_id = mi.index_id
  9392. INNER JOIN sys.columns AS sc ON sc.object_id = t.object_id AND sc.column_id = sic.column_id
  9393. INNER JOIN sys.types AS sty ON sc.user_type_id = sty.user_type_id
  9394. 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]
  9395. FROM sys.indexes AS mi
  9396. INNER JOIN sys.tables AS mst ON mst.[object_id] = mi.[object_id]
  9397. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  9398. WHERE mi.type = 1 AND mi.is_unique_constraint = 0
  9399. AND mst.is_ms_shipped = 0
  9400. --AND OBJECTPROPERTY(o.object_id,''IsUserTable'') = 1 -- sys.tables only returns type U
  9401. ORDER BY objectName
  9402. OPTION (MAXDOP 2);'
  9403. BEGIN TRY
  9404. INSERT INTO #tblIxs6
  9405. EXECUTE sp_executesql @sqlcmd
  9406. END TRY
  9407. BEGIN CATCH
  9408. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9409. SELECT @ErrorMessage = 'Clustered Indexes with GUIDs in key subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9410. RAISERROR (@ErrorMessage, 16, 1);
  9411. END CATCH
  9412. UPDATE #tmpdbs1
  9413. SET isdone = 1
  9414. WHERE [dbid] = @dbid
  9415. END;
  9416. IF (SELECT COUNT(*) FROM #tblIxs6 WHERE [Key_has_GUID] > 0) > 0
  9417. BEGIN
  9418. 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]
  9419. 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
  9420. FROM #tblIxs6 I
  9421. WHERE [Key_has_GUID] > 0
  9422. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9423. END
  9424. ELSE
  9425. BEGIN
  9426. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Key_GUID' AS [Check], '[OK]' AS [Deviation]
  9427. END
  9428. END;
  9429. --------------------------------------------------------------------------------------------------------------------------------
  9430. -- Foreign Keys with no Index subsection
  9431. --------------------------------------------------------------------------------------------------------------------------------
  9432. IF @ptochecks = 1
  9433. BEGIN
  9434. RAISERROR (N' |-Starting Foreign Keys with no Index', 10, 1) WITH NOWAIT
  9435. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  9436. DROP TABLE #tblFK;
  9437. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  9438. CREATE TABLE #tblFK ([databaseID] int, [DatabaseName] sysname, [constraint_name] VARCHAR(200), [parent_schema_name] VARCHAR(100),
  9439. [parent_table_name] VARCHAR(200), parent_columns VARCHAR(4000), [referenced_schema] VARCHAR(100), [referenced_table_name] VARCHAR(200), referenced_columns VARCHAR(4000),
  9440. CONSTRAINT PK_FK PRIMARY KEY CLUSTERED(databaseID, [constraint_name]))
  9441. UPDATE #tmpdbs1
  9442. SET isdone = 0
  9443. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9444. BEGIN
  9445. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9446. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  9447. USE ' + QUOTENAME(@dbname) + '
  9448. ;WITH cteFK AS (
  9449. SELECT t.name AS [parent_schema_name],
  9450. OBJECT_NAME(FKC.parent_object_id) [parent_table_name],
  9451. OBJECT_NAME(constraint_object_id) AS [constraint_name],
  9452. t2.name AS [referenced_schema],
  9453. OBJECT_NAME(referenced_object_id) AS [referenced_table_name],
  9454. SUBSTRING((SELECT '','' + RTRIM(COL_NAME(k.parent_object_id,parent_column_id)) AS [data()]
  9455. FROM sys.foreign_key_columns k (NOLOCK)
  9456. INNER JOIN sys.foreign_keys (NOLOCK) ON k.constraint_object_id = [object_id]
  9457. AND k.constraint_object_id = FKC.constraint_object_id
  9458. ORDER BY constraint_column_id
  9459. FOR XML PATH('''')), 2, 8000) AS [parent_columns],
  9460. SUBSTRING((SELECT '','' + RTRIM(COL_NAME(k.referenced_object_id,referenced_column_id)) AS [data()]
  9461. FROM sys.foreign_key_columns k (NOLOCK)
  9462. INNER JOIN sys.foreign_keys (NOLOCK) ON k.constraint_object_id = [object_id]
  9463. AND k.constraint_object_id = FKC.constraint_object_id
  9464. ORDER BY constraint_column_id
  9465. FOR XML PATH('''')), 2, 8000) AS [referenced_columns]
  9466. FROM sys.foreign_key_columns FKC (NOLOCK)
  9467. INNER JOIN sys.objects o (NOLOCK) ON FKC.parent_object_id = o.[object_id]
  9468. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  9469. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9470. INNER JOIN sys.objects so (NOLOCK) ON FKC.referenced_object_id = so.[object_id]
  9471. INNER JOIN sys.tables AS mst2 (NOLOCK) ON mst2.[object_id] = so.[object_id]
  9472. INNER JOIN sys.schemas AS t2 (NOLOCK) ON t2.[schema_id] = mst2.[schema_id]
  9473. WHERE o.type = ''U'' AND so.type = ''U''
  9474. GROUP BY o.[schema_id],so.[schema_id],FKC.parent_object_id,constraint_object_id,referenced_object_id,t.name,t2.name
  9475. ),
  9476. cteIndexCols AS (
  9477. SELECT t.name AS schemaName,
  9478. OBJECT_NAME(mst.[object_id]) AS objectName,
  9479. SUBSTRING(( SELECT '','' + RTRIM(ac.name) FROM sys.tables AS st
  9480. INNER JOIN sys.indexes AS mi ON st.[object_id] = mi.[object_id]
  9481. INNER JOIN sys.index_columns AS ic ON mi.[object_id] = ic.[object_id] AND mi.[index_id] = ic.[index_id]
  9482. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9483. WHERE i.[object_id] = mi.[object_id] AND i.index_id = mi.index_id AND ic.is_included_column = 0
  9484. ORDER BY ac.column_id
  9485. FOR XML PATH('''')), 2, 8000) AS KeyCols
  9486. FROM sys.indexes AS i
  9487. INNER JOIN sys.tables AS mst ON mst.[object_id] = i.[object_id]
  9488. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  9489. WHERE i.[type] IN (1,2,5,6) AND i.is_unique_constraint = 0
  9490. AND mst.is_ms_shipped = 0
  9491. )
  9492. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name, fk.constraint_name AS constraintName,
  9493. fk.parent_schema_name AS schemaName, fk.parent_table_name AS tableName,
  9494. REPLACE(fk.parent_columns,'' ,'','','') AS parentColumns, fk.referenced_schema AS referencedSchemaName,
  9495. fk.referenced_table_name AS referencedTableName, REPLACE(fk.referenced_columns,'' ,'','','') AS referencedColumns
  9496. FROM cteFK fk
  9497. WHERE NOT EXISTS (SELECT 1 FROM cteIndexCols ict
  9498. WHERE fk.parent_schema_name = ict.schemaName
  9499. AND fk.parent_table_name = ict.objectName
  9500. AND REPLACE(fk.parent_columns,'' ,'','','') = ict.KeyCols);'
  9501. BEGIN TRY
  9502. INSERT INTO #tblFK
  9503. EXECUTE sp_executesql @sqlcmd
  9504. END TRY
  9505. BEGIN CATCH
  9506. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9507. SELECT @ErrorMessage = 'Foreign Keys with no Index subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9508. RAISERROR (@ErrorMessage, 16, 1);
  9509. END CATCH
  9510. UPDATE #tmpdbs1
  9511. SET isdone = 1
  9512. WHERE [dbid] = @dbid
  9513. END;
  9514. IF (SELECT COUNT(*) FROM #tblFK) > 0
  9515. BEGIN
  9516. 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]
  9517. SELECT 'Index_and_Stats_checks' AS [Category], 'FK_no_Index' AS [Information], FK.[DatabaseName] AS [Database_Name], constraint_name AS [Constraint_Name],
  9518. FK.parent_schema_name AS [Schema_Name], FK.parent_table_name AS [Table_Name],
  9519. FK.parent_columns AS parentColumns, FK.referenced_schema AS Referenced_Schema_Name,
  9520. FK.referenced_table_name AS Referenced_Table_Name, FK.referenced_columns AS referencedColumns
  9521. FROM #tblFK FK
  9522. ORDER BY [DatabaseName], parent_schema_name, parent_table_name, referenced_schema, referenced_table_name
  9523. IF @gen_scripts = 1
  9524. BEGIN
  9525. DECLARE @strSQL5 NVARCHAR(4000)
  9526. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9527. PRINT CHAR(10) + '--############# FK index creation statements #############' + CHAR(10)
  9528. DECLARE curFKs CURSOR FAST_FORWARD FOR SELECT 'USE ' + [DatabaseName] + CHAR(10) + 'GO' + CHAR(10) +
  9529. 'CREATE INDEX IX_' + REPLACE(constraint_name,' ','_') + ' ON ' + QUOTENAME(parent_schema_name) + '.' + QUOTENAME(parent_table_name) + ' ([' + REPLACE(REPLACE(parent_columns,',','],['),']]',']') + ']);' + CHAR(10) + 'GO' + CHAR(10)
  9530. FROM #tblFK
  9531. ORDER BY [DatabaseName], parent_schema_name, parent_table_name, referenced_schema, referenced_table_name
  9532. OPEN curFKs
  9533. FETCH NEXT FROM curFKs INTO @strSQL5
  9534. WHILE (@@FETCH_STATUS = 0)
  9535. BEGIN
  9536. PRINT @strSQL5
  9537. FETCH NEXT FROM curFKs INTO @strSQL5
  9538. END
  9539. CLOSE curFKs
  9540. DEALLOCATE curFKs
  9541. PRINT '--############# Ended FK index creation statements #############' + CHAR(10)
  9542. END;
  9543. END
  9544. ELSE
  9545. BEGIN
  9546. SELECT 'Index_and_Stats_checks' AS [Category], 'FK_no_Index' AS [Check], '[OK]' AS [Deviation]
  9547. END;
  9548. END;
  9549. --------------------------------------------------------------------------------------------------------------------------------
  9550. -- Indexing per Table subsection
  9551. --------------------------------------------------------------------------------------------------------------------------------
  9552. IF @ptochecks = 1
  9553. BEGIN
  9554. RAISERROR (N' |-Starting Indexing per Table', 10, 1) WITH NOWAIT
  9555. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  9556. DROP TABLE #tblIxs3;
  9557. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  9558. CREATE TABLE #tblIxs3 ([Operation] tinyint, [databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200))
  9559. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  9560. DROP TABLE #tblIxs4;
  9561. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  9562. CREATE TABLE #tblIxs4 ([databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [CntCols] int, [CntIxs] int)
  9563. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  9564. DROP TABLE #tblIxs5;
  9565. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  9566. CREATE TABLE #tblIxs5 ([databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [indexName] VARCHAR(200), [indexLocation] VARCHAR(200))
  9567. UPDATE #tmpdbs1
  9568. SET isdone = 0
  9569. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9570. BEGIN
  9571. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9572. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9573. SELECT 1 AS [Check], ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name
  9574. FROM sys.indexes AS si (NOLOCK)
  9575. INNER JOIN sys.tables AS t (NOLOCK) ON si.[object_id] = t.[object_id]
  9576. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9577. WHERE si.is_hypothetical = 0
  9578. GROUP BY si.[object_id], t.name, s.name
  9579. HAVING COUNT(index_id) = 1 AND MAX(index_id) = 0
  9580. UNION ALL
  9581. SELECT 2 AS [Check], ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name
  9582. FROM sys.indexes AS si (NOLOCK)
  9583. INNER JOIN sys.tables AS t (NOLOCK) ON si.[object_id] = t.[object_id]
  9584. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9585. WHERE si.is_hypothetical = 0
  9586. GROUP BY t.name, s.name
  9587. HAVING COUNT(index_id) > 1 AND MIN(index_id) = 0;'
  9588. BEGIN TRY
  9589. INSERT INTO #tblIxs3
  9590. EXECUTE sp_executesql @sqlcmd
  9591. END TRY
  9592. BEGIN CATCH
  9593. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9594. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 1 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9595. RAISERROR (@ErrorMessage, 16, 1);
  9596. END CATCH
  9597. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9598. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name, COUNT(c.column_id),
  9599. (SELECT COUNT(si.index_id) FROM sys.tables AS t2 INNER JOIN sys.indexes AS si ON si.[object_id] = t2.[object_id]
  9600. WHERE si.index_id > 0 AND si.[object_id] = t.[object_id] AND si.is_hypothetical = 0
  9601. GROUP BY si.[object_id])
  9602. FROM sys.tables AS t (NOLOCK)
  9603. INNER JOIN sys.columns AS c (NOLOCK) ON t.[object_id] = c.[object_id]
  9604. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9605. GROUP BY s.name, t.name, t.[object_id];'
  9606. BEGIN TRY
  9607. INSERT INTO #tblIxs4
  9608. EXECUTE sp_executesql @sqlcmd
  9609. END TRY
  9610. BEGIN CATCH
  9611. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9612. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 2 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9613. RAISERROR (@ErrorMessage, 16, 1);
  9614. END CATCH
  9615. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9616. SELECT DISTINCT ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name, i.name, ds.name
  9617. FROM sys.tables AS t (NOLOCK)
  9618. INNER JOIN sys.indexes AS i (NOLOCK) ON t.[object_id] = i.[object_id]
  9619. INNER JOIN sys.data_spaces AS ds (NOLOCK) ON ds.data_space_id = i.data_space_id
  9620. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9621. WHERE t.[type] = ''U''
  9622. AND i.[type] IN (1,2)
  9623. AND i.is_hypothetical = 0
  9624. -- Get partitioned tables
  9625. AND t.name IN (SELECT ob.name
  9626. FROM sys.tables AS ob (NOLOCK)
  9627. INNER JOIN sys.indexes AS ind (NOLOCK) ON ind.[object_id] = ob.[object_id]
  9628. INNER JOIN sys.data_spaces AS sds (NOLOCK) ON sds.data_space_id = ind.data_space_id
  9629. WHERE sds.[type] = ''PS''
  9630. GROUP BY ob.name)
  9631. AND ds.[type] <> ''PS'';'
  9632. BEGIN TRY
  9633. INSERT INTO #tblIxs5
  9634. EXECUTE sp_executesql @sqlcmd
  9635. END TRY
  9636. BEGIN CATCH
  9637. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9638. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 3 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9639. RAISERROR (@ErrorMessage, 16, 1);
  9640. END CATCH
  9641. UPDATE #tmpdbs1
  9642. SET isdone = 1
  9643. WHERE [dbid] = @dbid
  9644. END;
  9645. IF (SELECT COUNT(*) FROM #tblIxs3 WHERE [Operation] = 1) > 0
  9646. BEGIN
  9647. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_Indexes' AS [Check], '[WARNING: Some tables do not have indexes]' AS [Deviation]
  9648. 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
  9649. END
  9650. ELSE
  9651. BEGIN
  9652. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_Indexes' AS [Check], '[OK]' AS [Deviation]
  9653. END;
  9654. IF (SELECT COUNT(*) FROM #tblIxs3 WHERE [Operation] = 2) > 0
  9655. BEGIN
  9656. 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]
  9657. 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
  9658. END
  9659. ELSE
  9660. BEGIN
  9661. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_CL_Index' AS [Check], '[OK]' AS [Deviation]
  9662. END;
  9663. IF (SELECT COUNT(*) FROM #tblIxs4 WHERE [CntCols] < [CntIxs]) > 0
  9664. BEGIN
  9665. 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]
  9666. 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]
  9667. END
  9668. ELSE
  9669. BEGIN
  9670. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_more_Indexes_than_Cols' AS [Check], '[OK]' AS [Deviation]
  9671. END;
  9672. IF (SELECT COUNT(*) FROM #tblIxs5) > 0
  9673. BEGIN
  9674. 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]
  9675. 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
  9676. END
  9677. ELSE
  9678. BEGIN
  9679. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_partition_misaligned_Indexes' AS [Check], '[OK]' AS [Deviation]
  9680. END;
  9681. END;
  9682. --------------------------------------------------------------------------------------------------------------------------------
  9683. -- Missing Indexes subsection
  9684. -- Outputs only potentially most relevant, based in scoring method - use at you own discretion)
  9685. --------------------------------------------------------------------------------------------------------------------------------
  9686. IF @ptochecks = 1
  9687. BEGIN
  9688. RAISERROR (N' |-Starting Missing Indexes', 10, 1) WITH NOWAIT
  9689. DECLARE @IC VARCHAR(4000), @ICWI VARCHAR(4000), @editionCheck bit
  9690. /* Refer to http://msdn.microsoft.com/en-us/library/ms174396.aspx */
  9691. IF (SELECT SERVERPROPERTY('EditionID')) IN (1804890536, 1872460670, 610778273, -2117995310)
  9692. SET @editionCheck = 1 -- supports enterprise only features
  9693. ELSE
  9694. SET @editionCheck = 0; -- does not support enterprise only features
  9695. -- Create the helper functions
  9696. 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')
  9697. EXEC ('USE tempdb; EXEC(''
  9698. CREATE FUNCTION dbo.fn_createindex_allcols (@ix_handle int)
  9699. RETURNS NVARCHAR(max)
  9700. AS
  9701. BEGIN
  9702. DECLARE @ReturnCols NVARCHAR(max)
  9703. ;WITH ColumnToPivot ([data()]) AS (
  9704. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9705. FROM sys.dm_db_missing_index_details id
  9706. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9707. WHERE id.index_handle = @ix_handle
  9708. ORDER BY ic.column_id ASC
  9709. FOR XML PATH(''''''''), TYPE
  9710. ),
  9711. XmlRawData (CSVString) AS (
  9712. SELECT (SELECT [data()] AS InputData
  9713. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9714. )
  9715. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9716. FROM XmlRawData
  9717. RETURN (@ReturnCols)
  9718. END'')
  9719. ')
  9720. 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')
  9721. EXEC ('USE tempdb; EXEC(''
  9722. CREATE FUNCTION dbo.fn_createindex_keycols (@ix_handle int)
  9723. RETURNS NVARCHAR(max)
  9724. AS
  9725. BEGIN
  9726. DECLARE @ReturnCols NVARCHAR(max)
  9727. ;WITH ColumnToPivot ([data()]) AS (
  9728. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9729. FROM sys.dm_db_missing_index_details id
  9730. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9731. WHERE id.index_handle = @ix_handle
  9732. AND (ic.column_usage = ''''EQUALITY'''' OR ic.column_usage = ''''INEQUALITY'''')
  9733. ORDER BY ic.column_id ASC
  9734. FOR XML PATH(''''''''), TYPE
  9735. ),
  9736. XmlRawData (CSVString) AS (
  9737. SELECT (SELECT [data()] AS InputData
  9738. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9739. )
  9740. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9741. FROM XmlRawData
  9742. RETURN (@ReturnCols)
  9743. END'')
  9744. ')
  9745. 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')
  9746. EXEC ('USE tempdb; EXEC(''
  9747. CREATE FUNCTION dbo.fn_createindex_includecols (@ix_handle int)
  9748. RETURNS NVARCHAR(max)
  9749. AS
  9750. BEGIN
  9751. DECLARE @ReturnCols NVARCHAR(max)
  9752. ;WITH ColumnToPivot ([data()]) AS (
  9753. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9754. FROM sys.dm_db_missing_index_details id
  9755. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9756. WHERE id.index_handle = @ix_handle
  9757. AND ic.column_usage = ''''INCLUDE''''
  9758. ORDER BY ic.column_id ASC
  9759. FOR XML PATH(''''''''), TYPE
  9760. ),
  9761. XmlRawData (CSVString) AS (
  9762. SELECT (SELECT [data()] AS InputData
  9763. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9764. )
  9765. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9766. FROM XmlRawData
  9767. RETURN (@ReturnCols)
  9768. END'')
  9769. ')
  9770. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  9771. DROP TABLE #IndexCreation;
  9772. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  9773. CREATE TABLE #IndexCreation (
  9774. [database_id] int,
  9775. DBName VARCHAR(255),
  9776. [Table] VARCHAR(255),
  9777. [ix_handle] int,
  9778. [User_Hits_on_Missing_Index] int,
  9779. [Estimated_Improvement_Percent] DECIMAL(5,2),
  9780. [Avg_Total_User_Cost] int,
  9781. [Unique_Compiles] int,
  9782. [Score] NUMERIC(19,3),
  9783. [KeyCols] VARCHAR(1000),
  9784. [IncludedCols] VARCHAR(4000),
  9785. [Ix_Name] VARCHAR(255),
  9786. [AllCols] NVARCHAR(max),
  9787. [KeyColsOrdered] NVARCHAR(max),
  9788. [IncludedColsOrdered] NVARCHAR(max)
  9789. )
  9790. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  9791. DROP TABLE #IndexRedundant;
  9792. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  9793. CREATE TABLE #IndexRedundant (
  9794. DBName VARCHAR(255),
  9795. [Table] VARCHAR(255),
  9796. [Ix_Name] VARCHAR(255),
  9797. [ix_handle] int,
  9798. [KeyCols] VARCHAR(1000),
  9799. [IncludedCols] VARCHAR(4000),
  9800. [Redundant_With] VARCHAR(255)
  9801. )
  9802. INSERT INTO #IndexCreation
  9803. SELECT i.database_id,
  9804. m.[name],
  9805. RIGHT(i.[statement], LEN(i.[statement]) - (LEN(m.[name]) + 3)) AS [Table],
  9806. i.index_handle AS [ix_handle],
  9807. [User_Hits_on_Missing_Index] = (s.user_seeks + s.user_scans),
  9808. s.avg_user_impact, -- Query cost would reduce by this amount in percentage, on average.
  9809. s.avg_total_user_cost, -- Average cost of the user queries that could be reduced by the index in the group.
  9810. s.unique_compiles, -- Number of compilations and recompilations that would benefit from this missing index group.
  9811. (CONVERT(NUMERIC(19,3), s.user_seeks) + CONVERT(NUMERIC(19,3), s.user_scans))
  9812. * CONVERT(NUMERIC(19,3), s.avg_total_user_cost)
  9813. * CONVERT(NUMERIC(19,3), s.avg_user_impact) AS Score, -- The higher the score, higher is the anticipated improvement for user queries.
  9814. CASE WHEN (i.equality_columns IS NOT NULL AND i.inequality_columns IS NULL) THEN i.equality_columns
  9815. WHEN (i.equality_columns IS NULL AND i.inequality_columns IS NOT NULL) THEN i.inequality_columns
  9816. ELSE i.equality_columns + ',' + i.inequality_columns END AS [KeyCols],
  9817. i.included_columns AS [IncludedCols],
  9818. '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),
  9819. 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],
  9820. tempdb.dbo.fn_createindex_allcols(i.index_handle),
  9821. tempdb.dbo.fn_createindex_keycols(i.index_handle),
  9822. tempdb.dbo.fn_createindex_includecols(i.index_handle)
  9823. FROM sys.dm_db_missing_index_details i
  9824. INNER JOIN master.sys.databases m ON i.database_id = m.database_id
  9825. INNER JOIN sys.dm_db_missing_index_groups g ON i.index_handle = g.index_handle
  9826. INNER JOIN sys.dm_db_missing_index_group_stats s ON s.group_handle = g.index_group_handle
  9827. WHERE i.database_id > 4
  9828. INSERT INTO #IndexRedundant
  9829. SELECT I.DBName, I.[Table], I.[Ix_Name], I.[ix_handle], I.[KeyCols], I.[IncludedCols], I2.[Ix_Name]
  9830. FROM #IndexCreation I
  9831. INNER JOIN #IndexCreation I2 ON I.[database_id] = I2.[database_id] AND I.[Table] = I2.[Table] AND I.[Ix_Name] <> I2.[Ix_Name]
  9832. AND (((I.KeyColsOrdered <> I2.KeyColsOrdered OR I.[IncludedColsOrdered] <> I2.[IncludedColsOrdered])
  9833. 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)
  9834. OR I.[AllCols] = I2.[AllCols]))
  9835. OR (I.KeyColsOrdered <> I2.KeyColsOrdered AND I.[IncludedColsOrdered] = I2.[IncludedColsOrdered])
  9836. OR (I.KeyColsOrdered = I2.KeyColsOrdered AND I.[IncludedColsOrdered] <> I2.[IncludedColsOrdered]))
  9837. WHERE I.[Score] >= 100000
  9838. AND I2.[Score] >= 100000
  9839. GROUP BY I.DBName, I.[Table], I.[Ix_Name], I.[ix_handle], I.[KeyCols], I.[IncludedCols], I2.[Ix_Name]
  9840. ORDER BY I.DBName, I.[Table], I.[Ix_Name]
  9841. IF (SELECT COUNT(*) FROM #IndexCreation WHERE [Score] >= 100000) > 0
  9842. BEGIN
  9843. 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]
  9844. 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],
  9845. [Estimated_Improvement_Percent], [Avg_Total_User_Cost], [Unique_Compiles], IC.[KeyCols], IC.[IncludedCols], IC.[Ix_Name] AS [Index_Name],
  9846. SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9847. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9848. ORDER BY IR.[Redundant_With]
  9849. FOR XML PATH('')), 2, 8000) AS [Possibly_Redundant_With],
  9850. CASE WHEN IC.[Score] >= 100000 THEN 'Y' ELSE 'N' END AS [Generate_Script]
  9851. FROM #IndexCreation IC
  9852. --WHERE [Score] >= 100000
  9853. ORDER BY IC.DBName, IC.[Score] DESC, IC.[User_Hits_on_Missing_Index], IC.[Estimated_Improvement_Percent];
  9854. 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],
  9855. I.[Ix_Name] AS [Index_Name], I.[KeyCols], I.[IncludedCols]
  9856. FROM #IndexRedundant I
  9857. ORDER BY I.DBName, I.[Table], I.[Ix_Name]
  9858. IF @gen_scripts = 1
  9859. BEGIN
  9860. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */' + CHAR(10)
  9861. IF (SELECT COUNT(*) FROM #IndexCreation IC
  9862. WHERE IC.[IncludedCols] IS NULL AND IC.[Score] >= 100000
  9863. ) > 0
  9864. BEGIN
  9865. PRINT '--############# Indexes creation statements #############' + CHAR(10)
  9866. DECLARE cIC CURSOR FAST_FORWARD FOR
  9867. SELECT '-- User Hits on Missing Index ' + IC.[Ix_Name] + ': ' + CONVERT(VARCHAR(20),IC.[User_Hits_on_Missing_Index]) + CHAR(10) +
  9868. '-- Estimated Improvement Percent: ' + CONVERT(VARCHAR(6),IC.[Estimated_Improvement_Percent]) + CHAR(10) +
  9869. '-- Average Total User Cost: ' + CONVERT(VARCHAR(50),IC.[Avg_Total_User_Cost]) + CHAR(10) +
  9870. '-- Unique Compiles: ' + CONVERT(VARCHAR(50),IC.[Unique_Compiles]) + CHAR(10) +
  9871. '-- Score: ' + CONVERT(VARCHAR(20),CONVERT(bigint,IC.[Score])) +
  9872. CASE WHEN (SELECT COUNT(IR.[Redundant_With]) FROM #IndexRedundant IR
  9873. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]) > 0
  9874. THEN CHAR(10) + '-- Possibly Redundant with Missing Index(es): ' + SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9875. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9876. FOR XML PATH('')), 2, 8000)
  9877. ELSE '' END +
  9878. CHAR(10) + 'USE ' + QUOTENAME(IC.DBName) + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sysindexes WHERE name = N''' +
  9879. IC.[Ix_Name] + ''') DROP INDEX ' + IC.[Table] + '.' +
  9880. IC.[Ix_Name] + ';' + CHAR(10) + 'GO' + CHAR(10) + 'CREATE INDEX ' +
  9881. IC.[Ix_Name] + ' ON ' + IC.[Table] + ' (' + IC.[KeyCols] + CASE WHEN @editionCheck = 1 THEN ') WITH (ONLINE = ON);' ELSE ');' END + CHAR(10) + 'GO' + CHAR(10)
  9882. FROM #IndexCreation IC
  9883. WHERE IC.[IncludedCols] IS NULL AND IC.[Score] >= 100000
  9884. ORDER BY IC.DBName, IC.[Table], IC.[Ix_Name]
  9885. OPEN cIC
  9886. FETCH NEXT FROM cIC INTO @IC
  9887. WHILE @@FETCH_STATUS = 0
  9888. BEGIN
  9889. PRINT @IC
  9890. FETCH NEXT FROM cIC INTO @IC
  9891. END
  9892. CLOSE cIC
  9893. DEALLOCATE cIC
  9894. END;
  9895. IF (SELECT COUNT(*) FROM #IndexCreation IC
  9896. WHERE IC.[IncludedCols] IS NOT NULL AND IC.[Score] >= 100000
  9897. ) > 0
  9898. BEGIN
  9899. PRINT '--############# Covering indexes creation statements #############' + CHAR(10)
  9900. DECLARE cICWI CURSOR FAST_FORWARD FOR
  9901. SELECT '-- User Hits on Missing Index ' + IC.[Ix_Name] + ': ' + CONVERT(VARCHAR(20),IC.[User_Hits_on_Missing_Index]) + CHAR(10) +
  9902. '-- Estimated Improvement Percent: ' + CONVERT(VARCHAR(6),IC.[Estimated_Improvement_Percent]) + CHAR(10) +
  9903. '-- Average Total User Cost: ' + CONVERT(VARCHAR(50),IC.[Avg_Total_User_Cost]) + CHAR(10) +
  9904. '-- Unique Compiles: ' + CONVERT(VARCHAR(50),IC.[Unique_Compiles]) + CHAR(10) +
  9905. '-- Score: ' + CONVERT(VARCHAR(20),CONVERT(bigint,IC.[Score])) +
  9906. CASE WHEN (SELECT COUNT(IR.[Redundant_With]) FROM #IndexRedundant IR
  9907. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]) > 0
  9908. THEN CHAR(10) + '-- Possibly Redundant with Missing Index(es): ' + SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9909. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9910. FOR XML PATH('')), 2, 8000)
  9911. ELSE '' END +
  9912. CHAR(10) + 'USE ' + QUOTENAME(IC.DBName) + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sysindexes WHERE name = N''' +
  9913. IC.[Ix_Name] + ''') DROP INDEX ' + IC.[Table] + '.' +
  9914. IC.[Ix_Name] + ';' + CHAR(10) + 'GO' + CHAR(10) + 'CREATE INDEX ' +
  9915. 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)
  9916. FROM #IndexCreation IC
  9917. WHERE IC.[IncludedCols] IS NOT NULL AND IC.[Score] >= 100000
  9918. ORDER BY IC.DBName, IC.[Table], IC.[Ix_Name]
  9919. OPEN cICWI
  9920. FETCH NEXT FROM cICWI INTO @ICWI
  9921. WHILE @@FETCH_STATUS = 0
  9922. BEGIN
  9923. PRINT @ICWI
  9924. FETCH NEXT FROM cICWI INTO @ICWI
  9925. END
  9926. CLOSE cICWI
  9927. DEALLOCATE cICWI
  9928. END;
  9929. PRINT '--############# Ended missing indexes creation statements #############' + CHAR(10)
  9930. END;
  9931. END
  9932. ELSE IF (SELECT COUNT(*) FROM #IndexCreation WHERE [Score] < 100000) > 0
  9933. BEGIN
  9934. 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]
  9935. 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],
  9936. [Estimated_Improvement_Percent], [Avg_Total_User_Cost], [Unique_Compiles], IC.[KeyCols], IC.[IncludedCols], IC.[Ix_Name] AS [Index_Name],
  9937. SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9938. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9939. ORDER BY IR.[Redundant_With]
  9940. FOR XML PATH('')), 2, 8000) AS [Possibly_Redundant_With],
  9941. CASE WHEN IC.[Score] >= 100000 THEN 'Y' ELSE 'N' END AS [Generate_Script]
  9942. FROM #IndexCreation IC
  9943. --WHERE [Score] < 100000
  9944. ORDER BY IC.DBName, IC.[Score] DESC, IC.[User_Hits_on_Missing_Index], IC.[Estimated_Improvement_Percent];
  9945. END
  9946. ELSE
  9947. BEGIN
  9948. SELECT 'Index_and_Stats_checks' AS [Category], 'Missing_Indexes' AS [Check], '[OK]' AS [Deviation]
  9949. END
  9950. END;
  9951. --------------------------------------------------------------------------------------------------------------------------------
  9952. -- Objects naming conventions subsection
  9953. -- Refer to BOL for more information
  9954. -- (http://msdn.microsoft.com/en-us/library/dd172115(v=vs.100).aspx)
  9955. -- (http://msdn.microsoft.com/en-us/library/dd172134.aspx)
  9956. -- (http://msdn.microsoft.com/en-us/library/ms189822.aspx)
  9957. --------------------------------------------------------------------------------------------------------------------------------
  9958. RAISERROR (N'|-Starting Objects naming conventions Checks', 10, 1) WITH NOWAIT
  9959. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  9960. DROP TABLE #tmpobjectnames;
  9961. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  9962. CREATE TABLE #tmpobjectnames ([DBName] sysname, [schemaName] VARCHAR(100), [Object] VARCHAR(255), [Col] VARCHAR(255), [type] CHAR(2), type_desc VARCHAR(60));
  9963. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  9964. DROP TABLE #tmpfinalobjectnames;
  9965. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  9966. CREATE TABLE #tmpfinalobjectnames ([Deviation] tinyint, [DBName] sysname, [schemaName] VARCHAR(100), [Object] VARCHAR(255), [Col] VARCHAR(255), type_desc VARCHAR(60), [Comment] VARCHAR(500) NULL);
  9967. UPDATE #tmpdbs1
  9968. SET isdone = 0
  9969. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9970. BEGIN
  9971. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9972. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9973. SELECT ''' + @dbname + ''' AS [DBName], s.name, so.name, NULL, type, type_desc
  9974. FROM sys.objects so
  9975. INNER JOIN sys.schemas s ON so.schema_id = s.schema_id
  9976. WHERE so.is_ms_shipped = 0
  9977. UNION ALL
  9978. SELECT ''' + @dbname + ''' AS [DBName], s.name, so.name, sc.name, ''TC'' AS [type], ''TABLE_COLUMN'' AS [type_desc]
  9979. FROM sys.columns sc
  9980. INNER JOIN sys.objects so ON sc.object_id = so.object_id
  9981. INNER JOIN sys.schemas s ON so.schema_id = s.schema_id
  9982. WHERE so.is_ms_shipped = 0'
  9983. BEGIN TRY
  9984. INSERT INTO #tmpobjectnames
  9985. EXECUTE sp_executesql @sqlcmd
  9986. END TRY
  9987. BEGIN CATCH
  9988. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9989. SELECT @ErrorMessage = 'Object naming conventions subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9990. RAISERROR (@ErrorMessage, 16, 1);
  9991. END CATCH
  9992. UPDATE #tmpdbs1
  9993. SET isdone = 1
  9994. WHERE [dbid] = @dbid
  9995. END;
  9996. UPDATE #tmpdbs1
  9997. SET isdone = 0
  9998. CREATE INDEX IX1 ON #tmpobjectnames([type],[Object]);
  9999. /* http://msdn.microsoft.com/en-us/library/dd172115(v=vs.100).aspx */
  10000. INSERT INTO #tmpfinalobjectnames
  10001. SELECT 1, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10002. FROM #tmpobjectnames
  10003. WHERE [type] = 'P' AND [Object] LIKE 'sp[_]%'
  10004. AND [Object] NOT IN ('sp_alterdiagram','sp_creatediagram','sp_dropdiagram','sp_helpdiagramdefinition','sp_helpdiagrams','sp_renamediagram','sp_upgraddiagrams');
  10005. /* http://msdn.microsoft.com/en-us/library/dd172134.aspx */
  10006. INSERT INTO #tmpfinalobjectnames
  10007. SELECT 2, [DBName], [schemaName], [Object], [Col], type_desc, CASE WHEN [Object] LIKE '% %' THEN 'Space - ' + QUOTENAME([Object]) ELSE NULL END COLLATE database_default AS [Comment]
  10008. FROM #tmpobjectnames
  10009. WHERE [type] <> 'S' AND [type] <> 'TC'
  10010. AND ([Object] LIKE '% %' --space
  10011. OR [Object] LIKE '%[[]%'
  10012. OR [Object] LIKE '%]%'
  10013. OR [Object] LIKE '%-%'
  10014. OR [Object] LIKE '%.%'
  10015. OR [Object] LIKE '%,%'
  10016. OR [Object] LIKE '%;%'
  10017. OR [Object] LIKE '%' + CHAR(34) + '%' --double quote
  10018. OR [Object] LIKE '%' + CHAR(39) + '%'); --single quote
  10019. INSERT INTO #tmpfinalobjectnames
  10020. SELECT 3, [DBName], [schemaName], [Object], [Col], type_desc, CASE WHEN [Col] LIKE '% %' THEN 'Space - ' + QUOTENAME([Col]) ELSE NULL END COLLATE database_default AS [Comment]
  10021. FROM #tmpobjectnames
  10022. WHERE [type] = 'TC'
  10023. AND ([Col] LIKE '% %' --space
  10024. OR [Col] LIKE '%[[]%'
  10025. OR [Col] LIKE '%]%'
  10026. OR [Col] LIKE '%-%'
  10027. OR [Col] LIKE '%.%'
  10028. OR [Col] LIKE '%,%'
  10029. OR [Col] LIKE '%;%'
  10030. OR [Col] LIKE '%' + CHAR(34) + '%' --double quote
  10031. OR [Col] LIKE '%' + CHAR(39) + '%'); --single quote
  10032. /* http://msdn.microsoft.com/en-us/library/ms189822.aspx */
  10033. INSERT INTO #tmpfinalobjectnames
  10034. SELECT 4, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10035. FROM #tmpobjectnames
  10036. WHERE [type] <> 'S'
  10037. AND ([Object] LIKE '% ABSOLUTE %' OR [Object] LIKE '% ABSOLUTE' OR [Object] = 'ABSOLUTE'
  10038. OR [Object] LIKE '% ACTION %' OR [Object] LIKE '% ACTION' OR [Object] = 'ACTION'
  10039. OR [Object] LIKE '% ADA %' OR [Object] LIKE '% ADA' OR [Object] = 'ADA'
  10040. OR [Object] LIKE '% ADD %' OR [Object] LIKE '% ADD' OR [Object] = 'ADD'
  10041. OR [Object] LIKE '% ADMIN %' OR [Object] LIKE '% ADMIN' OR [Object] = 'ADMIN'
  10042. OR [Object] LIKE '% AFTER %' OR [Object] LIKE '% AFTER' OR [Object] = 'AFTER'
  10043. OR [Object] LIKE '% AGGREGATE %' OR [Object] LIKE '% AGGREGATE' OR [Object] = 'AGGREGATE'
  10044. OR [Object] LIKE '% ALIAS %' OR [Object] LIKE '% ALIAS' OR [Object] = 'ALIAS'
  10045. OR [Object] LIKE '% ALL %' OR [Object] LIKE '% ALL' OR [Object] = 'ALL'
  10046. OR [Object] LIKE '% ALLOCATE %' OR [Object] LIKE '% ALLOCATE' OR [Object] = 'ALLOCATE'
  10047. OR [Object] LIKE '% ALTER %' OR [Object] LIKE '% ALTER' OR [Object] = 'ALTER'
  10048. OR [Object] LIKE '% AND %' OR [Object] LIKE '% AND' OR [Object] = 'AND'
  10049. OR [Object] LIKE '% ANY %' OR [Object] LIKE '% ANY' OR [Object] = 'ANY'
  10050. OR [Object] LIKE '% ARE %' OR [Object] LIKE '% ARE' OR [Object] = 'ARE'
  10051. OR [Object] LIKE '% ARRAY %' OR [Object] LIKE '% ARRAY' OR [Object] = 'ARRAY'
  10052. OR [Object] LIKE '% AS %' OR [Object] LIKE '% AS' OR [Object] = 'AS'
  10053. OR [Object] LIKE '% ASC %' OR [Object] LIKE '% ASC' OR [Object] = 'ASC'
  10054. OR [Object] LIKE '% ASSERTION %' OR [Object] LIKE '% ASSERTION' OR [Object] = 'ASSERTION'
  10055. OR [Object] LIKE '% AT %' OR [Object] LIKE '% AT' OR [Object] = 'AT'
  10056. OR [Object] LIKE '% AUTHORIZATION %' OR [Object] LIKE '% AUTHORIZATION' OR [Object] = 'AUTHORIZATION'
  10057. OR [Object] LIKE '% AVG %' OR [Object] LIKE '% AVG' OR [Object] = 'AVG'
  10058. OR [Object] LIKE '% BACKUP %' OR [Object] LIKE '% BACKUP' OR [Object] = 'BACKUP'
  10059. OR [Object] LIKE '% BEFORE %' OR [Object] LIKE '% BEFORE' OR [Object] = 'BEFORE'
  10060. OR [Object] LIKE '% BEGIN %' OR [Object] LIKE '% BEGIN' OR [Object] = 'BEGIN'
  10061. OR [Object] LIKE '% BETWEEN %' OR [Object] LIKE '% BETWEEN' OR [Object] = 'BETWEEN'
  10062. OR [Object] LIKE '% BINARY %' OR [Object] LIKE '% BINARY' OR [Object] = 'BINARY'
  10063. OR [Object] LIKE '% BIT %' OR [Object] LIKE '% BIT' OR [Object] = 'BIT'
  10064. OR [Object] LIKE '% BIT_LENGTH %' OR [Object] LIKE '% BIT_LENGTH' OR [Object] = 'BIT_LENGTH'
  10065. OR [Object] LIKE '% BLOB %' OR [Object] LIKE '% BLOB' OR [Object] = 'BLOB'
  10066. OR [Object] LIKE '% BOOLEAN %' OR [Object] LIKE '% BOOLEAN' OR [Object] = 'BOOLEAN'
  10067. OR [Object] LIKE '% BOTH %' OR [Object] LIKE '% BOTH' OR [Object] = 'BOTH'
  10068. OR [Object] LIKE '% BREADTH %' OR [Object] LIKE '% BREADTH' OR [Object] = 'BREADTH'
  10069. OR [Object] LIKE '% BREAK %' OR [Object] LIKE '% BREAK' OR [Object] = 'BREAK'
  10070. OR [Object] LIKE '% BROWSE %' OR [Object] LIKE '% BROWSE' OR [Object] = 'BROWSE'
  10071. OR [Object] LIKE '% BULK %' OR [Object] LIKE '% BULK' OR [Object] = 'BULK'
  10072. OR [Object] LIKE '% BY %' OR [Object] LIKE '% BY' OR [Object] = 'BY'
  10073. OR [Object] LIKE '% CALL %' OR [Object] LIKE '% CALL' OR [Object] = 'CALL'
  10074. OR [Object] LIKE '% CASCADE %' OR [Object] LIKE '% CASCADE' OR [Object] = 'CASCADE'
  10075. OR [Object] LIKE '% CASCADED %' OR [Object] LIKE '% CASCADED' OR [Object] = 'CASCADED'
  10076. OR [Object] LIKE '% CASE %' OR [Object] LIKE '% CASE' OR [Object] = 'CASE'
  10077. OR [Object] LIKE '% CAST %' OR [Object] LIKE '% CAST' OR [Object] = 'CAST'
  10078. OR [Object] LIKE '% CATALOG %' OR [Object] LIKE '% CATALOG' OR [Object] = 'CATALOG'
  10079. OR [Object] LIKE '% CHAR %' OR [Object] LIKE '% CHAR' OR [Object] = 'CHAR'
  10080. OR [Object] LIKE '% CHAR_LENGTH %' OR [Object] LIKE '% CHAR_LENGTH' OR [Object] = 'CHAR_LENGTH'
  10081. OR [Object] LIKE '% CHARACTER %' OR [Object] LIKE '% CHARACTER' OR [Object] = 'CHARACTER'
  10082. OR [Object] LIKE '% CHARACTER_LENGTH %' OR [Object] LIKE '% CHARACTER_LENGTH' OR [Object] = 'CHARACTER_LENGTH'
  10083. OR [Object] LIKE '% CHECK %' OR [Object] LIKE '% CHECK' OR [Object] = 'CHECK'
  10084. OR [Object] LIKE '% CHECKPOINT %' OR [Object] LIKE '% CHECKPOINT' OR [Object] = 'CHECKPOINT'
  10085. OR [Object] LIKE '% CLASS %' OR [Object] LIKE '% CLASS' OR [Object] = 'CLASS'
  10086. OR [Object] LIKE '% CLOB %' OR [Object] LIKE '% CLOB' OR [Object] = 'CLOB'
  10087. OR [Object] LIKE '% CLOSE %' OR [Object] LIKE '% CLOSE' OR [Object] = 'CLOSE'
  10088. OR [Object] LIKE '% CLUSTERED %' OR [Object] LIKE '% CLUSTERED' OR [Object] = 'CLUSTERED'
  10089. OR [Object] LIKE '% COALESCE %' OR [Object] LIKE '% COALESCE' OR [Object] = 'COALESCE'
  10090. OR [Object] LIKE '% COLLATE %' OR [Object] LIKE '% COLLATE' OR [Object] = 'COLLATE'
  10091. OR [Object] LIKE '% COLLATION %' OR [Object] LIKE '% COLLATION' OR [Object] = 'COLLATION'
  10092. OR [Object] LIKE '% COLUMN %' OR [Object] LIKE '% COLUMN' OR [Object] = 'COLUMN'
  10093. OR [Object] LIKE '% COMMIT %' OR [Object] LIKE '% COMMIT' OR [Object] = 'COMMIT'
  10094. OR [Object] LIKE '% COMPLETION %' OR [Object] LIKE '% COMPLETION' OR [Object] = 'COMPLETION'
  10095. OR [Object] LIKE '% COMPUTE %' OR [Object] LIKE '% COMPUTE' OR [Object] = 'COMPUTE'
  10096. OR [Object] LIKE '% CONNECT %' OR [Object] LIKE '% CONNECT' OR [Object] = 'CONNECT'
  10097. OR [Object] LIKE '% CONNECTION %' OR [Object] LIKE '% CONNECTION' OR [Object] = 'CONNECTION'
  10098. OR [Object] LIKE '% CONSTRAINT %' OR [Object] LIKE '% CONSTRAINT' OR [Object] = 'CONSTRAINT'
  10099. OR [Object] LIKE '% CONSTRAINTS %' OR [Object] LIKE '% CONSTRAINTS' OR [Object] = 'CONSTRAINTS'
  10100. OR [Object] LIKE '% CONSTRUCTOR %' OR [Object] LIKE '% CONSTRUCTOR' OR [Object] = 'CONSTRUCTOR'
  10101. OR [Object] LIKE '% CONTAINS %' OR [Object] LIKE '% CONTAINS' OR [Object] = 'CONTAINS'
  10102. OR [Object] LIKE '% CONTAINSTABLE %' OR [Object] LIKE '% CONTAINSTABLE' OR [Object] = 'CONTAINSTABLE'
  10103. OR [Object] LIKE '% CONTINUE %' OR [Object] LIKE '% CONTINUE' OR [Object] = 'CONTINUE'
  10104. OR [Object] LIKE '% CONVERT %' OR [Object] LIKE '% CONVERT' OR [Object] = 'CONVERT'
  10105. OR [Object] LIKE '% CORRESPONDING %' OR [Object] LIKE '% CORRESPONDING' OR [Object] = 'CORRESPONDING'
  10106. OR [Object] LIKE '% COUNT %' OR [Object] LIKE '% COUNT' OR [Object] = 'COUNT'
  10107. OR [Object] LIKE '% CREATE %' OR [Object] LIKE '% CREATE' OR [Object] = 'CREATE'
  10108. OR [Object] LIKE '% CROSS %' OR [Object] LIKE '% CROSS' OR [Object] = 'CROSS'
  10109. OR [Object] LIKE '% CUBE %' OR [Object] LIKE '% CUBE' OR [Object] = 'CUBE'
  10110. OR [Object] LIKE '% CURRENT %' OR [Object] LIKE '% CURRENT' OR [Object] = 'CURRENT'
  10111. OR [Object] LIKE '% CURRENT_DATE %' OR [Object] LIKE '% CURRENT_DATE' OR [Object] = 'CURRENT_DATE'
  10112. OR [Object] LIKE '% CURRENT_PATH %' OR [Object] LIKE '% CURRENT_PATH' OR [Object] = 'CURRENT_PATH'
  10113. OR [Object] LIKE '% CURRENT_ROLE %' OR [Object] LIKE '% CURRENT_ROLE' OR [Object] = 'CURRENT_ROLE'
  10114. OR [Object] LIKE '% CURRENT_TIME %' OR [Object] LIKE '% CURRENT_TIME' OR [Object] = 'CURRENT_TIME'
  10115. OR [Object] LIKE '% CURRENT_TIMESTAMP %' OR [Object] LIKE '% CURRENT_TIMESTAMP' OR [Object] = 'CURRENT_TIMESTAMP'
  10116. OR [Object] LIKE '% CURRENT_USER %' OR [Object] LIKE '% CURRENT_USER' OR [Object] = 'CURRENT_USER'
  10117. OR [Object] LIKE '% CURSOR %' OR [Object] LIKE '% CURSOR' OR [Object] = 'CURSOR'
  10118. OR [Object] LIKE '% CYCLE %' OR [Object] LIKE '% CYCLE' OR [Object] = 'CYCLE'
  10119. OR [Object] LIKE '% DATA %' OR [Object] LIKE '% DATA' OR [Object] = 'DATA'
  10120. OR [Object] LIKE '% DATABASE %' OR [Object] LIKE '% DATABASE' OR [Object] = 'DATABASE'
  10121. OR [Object] LIKE '% DATE %' OR [Object] LIKE '% DATE' OR [Object] = 'DATE'
  10122. OR [Object] LIKE '% DAY %' OR [Object] LIKE '% DAY' OR [Object] = 'DAY'
  10123. OR [Object] LIKE '% DBCC %' OR [Object] LIKE '% DBCC' OR [Object] = 'DBCC'
  10124. OR [Object] LIKE '% DEALLOCATE %' OR [Object] LIKE '% DEALLOCATE' OR [Object] = 'DEALLOCATE'
  10125. OR [Object] LIKE '% DEC %' OR [Object] LIKE '% DEC' OR [Object] = 'DEC'
  10126. OR [Object] LIKE '% DECIMAL %' OR [Object] LIKE '% DECIMAL' OR [Object] = 'DECIMAL'
  10127. OR [Object] LIKE '% DECLARE %' OR [Object] LIKE '% DECLARE' OR [Object] = 'DECLARE'
  10128. OR [Object] LIKE '% DEFAULT %' OR [Object] LIKE '% DEFAULT' OR [Object] = 'DEFAULT'
  10129. OR [Object] LIKE '% DEFERRABLE %' OR [Object] LIKE '% DEFERRABLE' OR [Object] = 'DEFERRABLE'
  10130. OR [Object] LIKE '% DEFERRED %' OR [Object] LIKE '% DEFERRED' OR [Object] = 'DEFERRED'
  10131. OR [Object] LIKE '% DELETE %' OR [Object] LIKE '% DELETE' OR [Object] = 'DELETE'
  10132. OR [Object] LIKE '% DENY %' OR [Object] LIKE '% DENY' OR [Object] = 'DENY'
  10133. OR [Object] LIKE '% DEPTH %' OR [Object] LIKE '% DEPTH' OR [Object] = 'DEPTH'
  10134. OR [Object] LIKE '% DEREF %' OR [Object] LIKE '% DEREF' OR [Object] = 'DEREF'
  10135. OR [Object] LIKE '% DESC %' OR [Object] LIKE '% DESC' OR [Object] = 'DESC'
  10136. OR [Object] LIKE '% DESCRIBE %' OR [Object] LIKE '% DESCRIBE' OR [Object] = 'DESCRIBE'
  10137. OR [Object] LIKE '% DESCRIPTOR %' OR [Object] LIKE '% DESCRIPTOR' OR [Object] = 'DESCRIPTOR'
  10138. OR [Object] LIKE '% DESTROY %' OR [Object] LIKE '% DESTROY' OR [Object] = 'DESTROY'
  10139. OR [Object] LIKE '% DESTRUCTOR %' OR [Object] LIKE '% DESTRUCTOR' OR [Object] = 'DESTRUCTOR'
  10140. OR [Object] LIKE '% DETERMINISTIC %' OR [Object] LIKE '% DETERMINISTIC' OR [Object] = 'DETERMINISTIC'
  10141. OR [Object] LIKE '% DIAGNOSTICS %' OR [Object] LIKE '% DIAGNOSTICS' OR [Object] = 'DIAGNOSTICS'
  10142. OR [Object] LIKE '% DICTIONARY %' OR [Object] LIKE '% DICTIONARY' OR [Object] = 'DICTIONARY'
  10143. OR [Object] LIKE '% DISCONNECT %' OR [Object] LIKE '% DISCONNECT' OR [Object] = 'DISCONNECT'
  10144. OR [Object] LIKE '% DISK %' OR [Object] LIKE '% DISK' OR [Object] = 'DISK'
  10145. OR [Object] LIKE '% DISTINCT %' OR [Object] LIKE '% DISTINCT' OR [Object] = 'DISTINCT'
  10146. OR [Object] LIKE '% DISTRIBUTED %' OR [Object] LIKE '% DISTRIBUTED' OR [Object] = 'DISTRIBUTED'
  10147. OR [Object] LIKE '% DOMAIN %' OR [Object] LIKE '% DOMAIN' OR [Object] = 'DOMAIN'
  10148. OR [Object] LIKE '% DOUBLE %' OR [Object] LIKE '% DOUBLE' OR [Object] = 'DOUBLE'
  10149. OR [Object] LIKE '% DROP %' OR [Object] LIKE '% DROP' OR [Object] = 'DROP'
  10150. OR [Object] LIKE '% DUMMY %' OR [Object] LIKE '% DUMMY' OR [Object] = 'DUMMY'
  10151. OR [Object] LIKE '% DUMP %' OR [Object] LIKE '% DUMP' OR [Object] = 'DUMP'
  10152. OR [Object] LIKE '% DYNAMIC %' OR [Object] LIKE '% DYNAMIC' OR [Object] = 'DYNAMIC'
  10153. OR [Object] LIKE '% EACH %' OR [Object] LIKE '% EACH' OR [Object] = 'EACH'
  10154. OR [Object] LIKE '% ELSE %' OR [Object] LIKE '% ELSE' OR [Object] = 'ELSE'
  10155. OR [Object] LIKE '% END %' OR [Object] LIKE '% END' OR [Object] = 'END'
  10156. OR [Object] LIKE '% END-EXEC %' OR [Object] LIKE '% END-EXEC' OR [Object] = 'END-EXEC'
  10157. OR [Object] LIKE '% EQUALS %' OR [Object] LIKE '% EQUALS' OR [Object] = 'EQUALS'
  10158. OR [Object] LIKE '% ERRLVL %' OR [Object] LIKE '% ERRLVL' OR [Object] = 'ERRLVL'
  10159. OR [Object] LIKE '% ESCAPE %' OR [Object] LIKE '% ESCAPE' OR [Object] = 'ESCAPE'
  10160. OR [Object] LIKE '% EVERY %' OR [Object] LIKE '% EVERY' OR [Object] = 'EVERY'
  10161. OR [Object] LIKE '% EXCEPT %' OR [Object] LIKE '% EXCEPT' OR [Object] = 'EXCEPT'
  10162. OR [Object] LIKE '% EXCEPTION %' OR [Object] LIKE '% EXCEPTION' OR [Object] = 'EXCEPTION'
  10163. OR [Object] LIKE '% EXEC %' OR [Object] LIKE '% EXEC' OR [Object] = 'EXEC'
  10164. OR [Object] LIKE '% EXECUTE %' OR [Object] LIKE '% EXECUTE' OR [Object] = 'EXECUTE'
  10165. OR [Object] LIKE '% EXISTS %' OR [Object] LIKE '% EXISTS' OR [Object] = 'EXISTS'
  10166. OR [Object] LIKE '% EXIT %' OR [Object] LIKE '% EXIT' OR [Object] = 'EXIT'
  10167. OR [Object] LIKE '% EXTERNAL %' OR [Object] LIKE '% EXTERNAL' OR [Object] = 'EXTERNAL'
  10168. OR [Object] LIKE '% EXTRACT %' OR [Object] LIKE '% EXTRACT' OR [Object] = 'EXTRACT'
  10169. OR [Object] LIKE '% FALSE %' OR [Object] LIKE '% FALSE' OR [Object] = 'FALSE'
  10170. OR [Object] LIKE '% FETCH %' OR [Object] LIKE '% FETCH' OR [Object] = 'FETCH'
  10171. OR [Object] LIKE '% FILE %' OR [Object] LIKE '% FILE' OR [Object] = 'FILE'
  10172. OR [Object] LIKE '% FILLFACTOR %' OR [Object] LIKE '% FILLFACTOR' OR [Object] = 'FILLFACTOR'
  10173. OR [Object] LIKE '% FIRST %' OR [Object] LIKE '% FIRST' OR [Object] = 'FIRST'
  10174. OR [Object] LIKE '% FLOAT %' OR [Object] LIKE '% FLOAT' OR [Object] = 'FLOAT'
  10175. OR [Object] LIKE '% FOR %' OR [Object] LIKE '% FOR' OR [Object] = 'FOR'
  10176. OR [Object] LIKE '% FOREIGN %' OR [Object] LIKE '% FOREIGN' OR [Object] = 'FOREIGN'
  10177. OR [Object] LIKE '% FORTRAN %' OR [Object] LIKE '% FORTRAN' OR [Object] = 'FORTRAN'
  10178. OR [Object] LIKE '% FOUND %' OR [Object] LIKE '% FOUND' OR [Object] = 'FOUND'
  10179. OR [Object] LIKE '% FREE %' OR [Object] LIKE '% FREE' OR [Object] = 'FREE'
  10180. OR [Object] LIKE '% FREETEXT %' OR [Object] LIKE '% FREETEXT' OR [Object] = 'FREETEXT'
  10181. OR [Object] LIKE '% FREETEXTTABLE %' OR [Object] LIKE '% FREETEXTTABLE' OR [Object] = 'FREETEXTTABLE'
  10182. OR [Object] LIKE '% FROM %' OR [Object] LIKE '% FROM' OR [Object] = 'FROM'
  10183. OR [Object] LIKE '% FULL %' OR [Object] LIKE '% FULL' OR [Object] = 'FULL'
  10184. OR [Object] LIKE '% FULLTEXTTABLE %' OR [Object] LIKE '% FULLTEXTTABLE' OR [Object] = 'FULLTEXTTABLE'
  10185. OR [Object] LIKE '% FUNCTION %' OR [Object] LIKE '% FUNCTION' OR [Object] = 'FUNCTION'
  10186. OR [Object] LIKE '% GENERAL %' OR [Object] LIKE '% GENERAL' OR [Object] = 'GENERAL'
  10187. OR [Object] LIKE '% GET %' OR [Object] LIKE '% GET' OR [Object] = 'GET'
  10188. OR [Object] LIKE '% GLOBAL %' OR [Object] LIKE '% GLOBAL' OR [Object] = 'GLOBAL'
  10189. OR [Object] LIKE '% GO %' OR [Object] LIKE '% GO' OR [Object] = 'GO'
  10190. OR [Object] LIKE '% GOTO %' OR [Object] LIKE '% GOTO' OR [Object] = 'GOTO'
  10191. OR [Object] LIKE '% GRANT %' OR [Object] LIKE '% GRANT' OR [Object] = 'GRANT'
  10192. OR [Object] LIKE '% GROUP %' OR [Object] LIKE '% GROUP' OR [Object] = 'GROUP'
  10193. OR [Object] LIKE '% GROUPING %' OR [Object] LIKE '% GROUPING' OR [Object] = 'GROUPING'
  10194. OR [Object] LIKE '% HAVING %' OR [Object] LIKE '% HAVING' OR [Object] = 'HAVING'
  10195. OR [Object] LIKE '% HOLDLOCK %' OR [Object] LIKE '% HOLDLOCK' OR [Object] = 'HOLDLOCK'
  10196. OR [Object] LIKE '% HOST %' OR [Object] LIKE '% HOST' OR [Object] = 'HOST'
  10197. OR [Object] LIKE '% HOUR %' OR [Object] LIKE '% HOUR' OR [Object] = 'HOUR'
  10198. OR [Object] LIKE '% IDENTITY %' OR [Object] LIKE '% IDENTITY' OR [Object] = 'IDENTITY'
  10199. OR [Object] LIKE '% IDENTITY_INSERT %' OR [Object] LIKE '% IDENTITY_INSERT' OR [Object] = 'IDENTITY_INSERT'
  10200. OR [Object] LIKE '% IDENTITYCOL %' OR [Object] LIKE '% IDENTITYCOL' OR [Object] = 'IDENTITYCOL'
  10201. OR [Object] LIKE '% IF %' OR [Object] LIKE '% IF' OR [Object] = 'IF'
  10202. OR [Object] LIKE '% IGNORE %' OR [Object] LIKE '% IGNORE' OR [Object] = 'IGNORE'
  10203. OR [Object] LIKE '% IMMEDIATE %' OR [Object] LIKE '% IMMEDIATE' OR [Object] = 'IMMEDIATE'
  10204. OR [Object] LIKE '% IN %' OR [Object] LIKE '% IN' OR [Object] = 'IN'
  10205. OR [Object] LIKE '% INCLUDE %' OR [Object] LIKE '% INCLUDE' OR [Object] = 'INCLUDE'
  10206. OR [Object] LIKE '% INDEX %' OR [Object] LIKE '% INDEX' OR [Object] = 'INDEX'
  10207. OR [Object] LIKE '% INDICATOR %' OR [Object] LIKE '% INDICATOR' OR [Object] = 'INDICATOR'
  10208. OR [Object] LIKE '% INITIALIZE %' OR [Object] LIKE '% INITIALIZE' OR [Object] = 'INITIALIZE'
  10209. OR [Object] LIKE '% INITIALLY %' OR [Object] LIKE '% INITIALLY' OR [Object] = 'INITIALLY'
  10210. OR [Object] LIKE '% INNER %' OR [Object] LIKE '% INNER' OR [Object] = 'INNER'
  10211. OR [Object] LIKE '% INOUT %' OR [Object] LIKE '% INOUT' OR [Object] = 'INOUT'
  10212. OR [Object] LIKE '% INPUT %' OR [Object] LIKE '% INPUT' OR [Object] = 'INPUT'
  10213. OR [Object] LIKE '% INSENSITIVE %' OR [Object] LIKE '% INSENSITIVE' OR [Object] = 'INSENSITIVE'
  10214. OR [Object] LIKE '% INSERT %' OR [Object] LIKE '% INSERT' OR [Object] = 'INSERT'
  10215. OR [Object] LIKE '% INT %' OR [Object] LIKE '% INT' OR [Object] = 'INT'
  10216. OR [Object] LIKE '% INTEGER %' OR [Object] LIKE '% INTEGER' OR [Object] = 'INTEGER'
  10217. OR [Object] LIKE '% INTERSECT %' OR [Object] LIKE '% INTERSECT' OR [Object] = 'INTERSECT'
  10218. OR [Object] LIKE '% INTERVAL %' OR [Object] LIKE '% INTERVAL' OR [Object] = 'INTERVAL'
  10219. OR [Object] LIKE '% INTO %' OR [Object] LIKE '% INTO' OR [Object] = 'INTO'
  10220. OR [Object] LIKE '% IS %' OR [Object] LIKE '% IS' OR [Object] = 'IS'
  10221. OR [Object] LIKE '% ISOLATION %' OR [Object] LIKE '% ISOLATION' OR [Object] = 'ISOLATION'
  10222. OR [Object] LIKE '% ITERATE %' OR [Object] LIKE '% ITERATE' OR [Object] = 'ITERATE'
  10223. OR [Object] LIKE '% JOIN %' OR [Object] LIKE '% JOIN' OR [Object] = 'JOIN'
  10224. OR [Object] LIKE '% KEY %' OR [Object] LIKE '% KEY' OR [Object] = 'KEY'
  10225. OR [Object] LIKE '% KILL %' OR [Object] LIKE '% KILL' OR [Object] = 'KILL'
  10226. OR [Object] LIKE '% LANGUAGE %' OR [Object] LIKE '% LANGUAGE' OR [Object] = 'LANGUAGE'
  10227. OR [Object] LIKE '% LARGE %' OR [Object] LIKE '% LARGE' OR [Object] = 'LARGE'
  10228. OR [Object] LIKE '% LAST %' OR [Object] LIKE '% LAST' OR [Object] = 'LAST'
  10229. OR [Object] LIKE '% LATERAL %' OR [Object] LIKE '% LATERAL' OR [Object] = 'LATERAL'
  10230. OR [Object] LIKE '% LEADING %' OR [Object] LIKE '% LEADING' OR [Object] = 'LEADING'
  10231. OR [Object] LIKE '% LEFT %' OR [Object] LIKE '% LEFT' OR [Object] = 'LEFT'
  10232. OR [Object] LIKE '% LESS %' OR [Object] LIKE '% LESS' OR [Object] = 'LESS'
  10233. OR [Object] LIKE '% LEVEL %' OR [Object] LIKE '% LEVEL' OR [Object] = 'LEVEL'
  10234. OR [Object] LIKE '% LIKE %' OR [Object] LIKE '% LIKE' OR [Object] = 'LIKE'
  10235. OR [Object] LIKE '% LIMIT %' OR [Object] LIKE '% LIMIT' OR [Object] = 'LIMIT'
  10236. OR [Object] LIKE '% LINENO %' OR [Object] LIKE '% LINENO' OR [Object] = 'LINENO'
  10237. OR [Object] LIKE '% LOAD %' OR [Object] LIKE '% LOAD' OR [Object] = 'LOAD'
  10238. OR [Object] LIKE '% LOCAL %' OR [Object] LIKE '% LOCAL' OR [Object] = 'LOCAL'
  10239. OR [Object] LIKE '% LOCALTIME %' OR [Object] LIKE '% LOCALTIME' OR [Object] = 'LOCALTIME'
  10240. OR [Object] LIKE '% LOCALTIMESTAMP %' OR [Object] LIKE '% LOCALTIMESTAMP' OR [Object] = 'LOCALTIMESTAMP'
  10241. OR [Object] LIKE '% LOCATOR %' OR [Object] LIKE '% LOCATOR' OR [Object] = 'LOCATOR'
  10242. OR [Object] LIKE '% LOWER %' OR [Object] LIKE '% LOWER' OR [Object] = 'LOWER'
  10243. OR [Object] LIKE '% MAP %' OR [Object] LIKE '% MAP' OR [Object] = 'MAP'
  10244. OR [Object] LIKE '% MATCH %' OR [Object] LIKE '% MATCH' OR [Object] = 'MATCH'
  10245. OR [Object] LIKE '% MAX %' OR [Object] LIKE '% MAX' OR [Object] = 'MAX'
  10246. OR [Object] LIKE '% MIN %' OR [Object] LIKE '% MIN' OR [Object] = 'MIN'
  10247. OR [Object] LIKE '% MINUTE %' OR [Object] LIKE '% MINUTE' OR [Object] = 'MINUTE'
  10248. OR [Object] LIKE '% MODIFIES %' OR [Object] LIKE '% MODIFIES' OR [Object] = 'MODIFIES'
  10249. OR [Object] LIKE '% MODIFY %' OR [Object] LIKE '% MODIFY' OR [Object] = 'MODIFY'
  10250. OR [Object] LIKE '% MODULE %' OR [Object] LIKE '% MODULE' OR [Object] = 'MODULE'
  10251. OR [Object] LIKE '% MONTH %' OR [Object] LIKE '% MONTH' OR [Object] = 'MONTH'
  10252. OR [Object] LIKE '% NAMES %' OR [Object] LIKE '% NAMES' OR [Object] = 'NAMES'
  10253. OR [Object] LIKE '% NATIONAL %' OR [Object] LIKE '% NATIONAL' OR [Object] = 'NATIONAL'
  10254. OR [Object] LIKE '% NATURAL %' OR [Object] LIKE '% NATURAL' OR [Object] = 'NATURAL'
  10255. OR [Object] LIKE '% NCHAR %' OR [Object] LIKE '% NCHAR' OR [Object] = 'NCHAR'
  10256. OR [Object] LIKE '% NCLOB %' OR [Object] LIKE '% NCLOB' OR [Object] = 'NCLOB'
  10257. OR [Object] LIKE '% NEW %' OR [Object] LIKE '% NEW' OR [Object] = 'NEW'
  10258. OR [Object] LIKE '% NEXT %' OR [Object] LIKE '% NEXT' OR [Object] = 'NEXT'
  10259. OR [Object] LIKE '% NO %' OR [Object] LIKE '% NO' OR [Object] = 'NO'
  10260. OR [Object] LIKE '% NOCHECK %' OR [Object] LIKE '% NOCHECK' OR [Object] = 'NOCHECK'
  10261. OR [Object] LIKE '% NONCLUSTERED %' OR [Object] LIKE '% NONCLUSTERED' OR [Object] = 'NONCLUSTERED'
  10262. OR [Object] LIKE '% NONE %' OR [Object] LIKE '% NONE' OR [Object] = 'NONE'
  10263. OR [Object] LIKE '% NOT %' OR [Object] LIKE '% NOT' OR [Object] = 'NOT'
  10264. OR [Object] LIKE '% NULL %' OR [Object] LIKE '% NULL' OR [Object] = 'NULL'
  10265. OR [Object] LIKE '% NULLIF %' OR [Object] LIKE '% NULLIF' OR [Object] = 'NULLIF'
  10266. OR [Object] LIKE '% NUMERIC %' OR [Object] LIKE '% NUMERIC' OR [Object] = 'NUMERIC'
  10267. OR [Object] LIKE '% OBJECT %' OR [Object] LIKE '% OBJECT' OR [Object] = 'OBJECT'
  10268. OR [Object] LIKE '% OCTET_LENGTH %' OR [Object] LIKE '% OCTET_LENGTH' OR [Object] = 'OCTET_LENGTH'
  10269. OR [Object] LIKE '% OF %' OR [Object] LIKE '% OF' OR [Object] = 'OF'
  10270. OR [Object] LIKE '% OFF %' OR [Object] LIKE '% OFF' OR [Object] = 'OFF'
  10271. OR [Object] LIKE '% OFFSETS %' OR [Object] LIKE '% OFFSETS' OR [Object] = 'OFFSETS'
  10272. OR [Object] LIKE '% OLD %' OR [Object] LIKE '% OLD' OR [Object] = 'OLD'
  10273. OR [Object] LIKE '% ON %' OR [Object] LIKE '% ON' OR [Object] = 'ON'
  10274. OR [Object] LIKE '% ONLY %' OR [Object] LIKE '% ONLY' OR [Object] = 'ONLY'
  10275. OR [Object] LIKE '% OPEN %' OR [Object] LIKE '% OPEN' OR [Object] = 'OPEN'
  10276. OR [Object] LIKE '% OPENDATASOURCE %' OR [Object] LIKE '% OPENDATASOURCE' OR [Object] = 'OPENDATASOURCE'
  10277. OR [Object] LIKE '% OPENQUERY %' OR [Object] LIKE '% OPENQUERY' OR [Object] = 'OPENQUERY'
  10278. OR [Object] LIKE '% OPENROWSET %' OR [Object] LIKE '% OPENROWSET' OR [Object] = 'OPENROWSET'
  10279. OR [Object] LIKE '% OPENXML %' OR [Object] LIKE '% OPENXML' OR [Object] = 'OPENXML'
  10280. OR [Object] LIKE '% OPERATION %' OR [Object] LIKE '% OPERATION' OR [Object] = 'OPERATION'
  10281. OR [Object] LIKE '% OPTION %' OR [Object] LIKE '% OPTION' OR [Object] = 'OPTION'
  10282. OR [Object] LIKE '% OR %' OR [Object] LIKE '% OR' OR [Object] = 'OR'
  10283. OR [Object] LIKE '% ORDER %' OR [Object] LIKE '% ORDER' OR [Object] = 'ORDER'
  10284. OR [Object] LIKE '% ORDINALITY %' OR [Object] LIKE '% ORDINALITY' OR [Object] = 'ORDINALITY'
  10285. OR [Object] LIKE '% OUT %' OR [Object] LIKE '% OUT' OR [Object] = 'OUT'
  10286. OR [Object] LIKE '% OUTER %' OR [Object] LIKE '% OUTER' OR [Object] = 'OUTER'
  10287. OR [Object] LIKE '% OUTPUT %' OR [Object] LIKE '% OUTPUT' OR [Object] = 'OUTPUT'
  10288. OR [Object] LIKE '% OVER %' OR [Object] LIKE '% OVER' OR [Object] = 'OVER'
  10289. OR [Object] LIKE '% OVERLAPS %' OR [Object] LIKE '% OVERLAPS' OR [Object] = 'OVERLAPS'
  10290. OR [Object] LIKE '% PAD %' OR [Object] LIKE '% PAD' OR [Object] = 'PAD'
  10291. OR [Object] LIKE '% PARAMETER %' OR [Object] LIKE '% PARAMETER' OR [Object] = 'PARAMETER'
  10292. OR [Object] LIKE '% PARAMETERS %' OR [Object] LIKE '% PARAMETERS' OR [Object] = 'PARAMETERS'
  10293. OR [Object] LIKE '% PARTIAL %' OR [Object] LIKE '% PARTIAL' OR [Object] = 'PARTIAL'
  10294. OR [Object] LIKE '% PASCAL %' OR [Object] LIKE '% PASCAL' OR [Object] = 'PASCAL'
  10295. OR [Object] LIKE '% PATH %' OR [Object] LIKE '% PATH' OR [Object] = 'PATH'
  10296. OR [Object] LIKE '% PERCENT %' OR [Object] LIKE '% PERCENT' OR [Object] = 'PERCENT'
  10297. OR [Object] LIKE '% PLAN %' OR [Object] LIKE '% PLAN' OR [Object] = 'PLAN'
  10298. OR [Object] LIKE '% POSITION %' OR [Object] LIKE '% POSITION' OR [Object] = 'POSITION'
  10299. OR [Object] LIKE '% POSTFIX %' OR [Object] LIKE '% POSTFIX' OR [Object] = 'POSTFIX'
  10300. OR [Object] LIKE '% PRECISION %' OR [Object] LIKE '% PRECISION' OR [Object] = 'PRECISION'
  10301. OR [Object] LIKE '% PREFIX %' OR [Object] LIKE '% PREFIX' OR [Object] = 'PREFIX'
  10302. OR [Object] LIKE '% PREORDER %' OR [Object] LIKE '% PREORDER' OR [Object] = 'PREORDER'
  10303. OR [Object] LIKE '% PREPARE %' OR [Object] LIKE '% PREPARE' OR [Object] = 'PREPARE'
  10304. OR [Object] LIKE '% PRESERVE %' OR [Object] LIKE '% PRESERVE' OR [Object] = 'PRESERVE'
  10305. OR [Object] LIKE '% PRIMARY %' OR [Object] LIKE '% PRIMARY' OR [Object] = 'PRIMARY'
  10306. OR [Object] LIKE '% PRINT %' OR [Object] LIKE '% PRINT' OR [Object] = 'PRINT'
  10307. OR [Object] LIKE '% PRIOR %' OR [Object] LIKE '% PRIOR' OR [Object] = 'PRIOR'
  10308. OR [Object] LIKE '% PRIVILEGES %' OR [Object] LIKE '% PRIVILEGES' OR [Object] = 'PRIVILEGES'
  10309. OR [Object] LIKE '% PROC %' OR [Object] LIKE '% PROC' OR [Object] = 'PROC'
  10310. OR [Object] LIKE '% PROCEDURE %' OR [Object] LIKE '% PROCEDURE' OR [Object] = 'PROCEDURE'
  10311. OR [Object] LIKE '% PUBLIC %' OR [Object] LIKE '% PUBLIC' OR [Object] = 'PUBLIC'
  10312. OR [Object] LIKE '% RAISERROR %' OR [Object] LIKE '% RAISERROR' OR [Object] = 'RAISERROR'
  10313. OR [Object] LIKE '% READ %' OR [Object] LIKE '% READ' OR [Object] = 'READ'
  10314. OR [Object] LIKE '% READS %' OR [Object] LIKE '% READS' OR [Object] = 'READS'
  10315. OR [Object] LIKE '% READTEXT %' OR [Object] LIKE '% READTEXT' OR [Object] = 'READTEXT'
  10316. OR [Object] LIKE '% REAL %' OR [Object] LIKE '% REAL' OR [Object] = 'REAL'
  10317. OR [Object] LIKE '% RECONFIGURE %' OR [Object] LIKE '% RECONFIGURE' OR [Object] = 'RECONFIGURE'
  10318. OR [Object] LIKE '% RECURSIVE %' OR [Object] LIKE '% RECURSIVE' OR [Object] = 'RECURSIVE'
  10319. OR [Object] LIKE '% REF %' OR [Object] LIKE '% REF' OR [Object] = 'REF'
  10320. OR [Object] LIKE '% REFERENCES %' OR [Object] LIKE '% REFERENCES' OR [Object] = 'REFERENCES'
  10321. OR [Object] LIKE '% REFERENCING %' OR [Object] LIKE '% REFERENCING' OR [Object] = 'REFERENCING'
  10322. OR [Object] LIKE '% RELATIVE %' OR [Object] LIKE '% RELATIVE' OR [Object] = 'RELATIVE'
  10323. OR [Object] LIKE '% REPLICATION %' OR [Object] LIKE '% REPLICATION' OR [Object] = 'REPLICATION'
  10324. OR [Object] LIKE '% RESTORE %' OR [Object] LIKE '% RESTORE' OR [Object] = 'RESTORE'
  10325. OR [Object] LIKE '% RESTRICT %' OR [Object] LIKE '% RESTRICT' OR [Object] = 'RESTRICT'
  10326. OR [Object] LIKE '% RESULT %' OR [Object] LIKE '% RESULT' OR [Object] = 'RESULT'
  10327. OR [Object] LIKE '% RETURN %' OR [Object] LIKE '% RETURN' OR [Object] = 'RETURN'
  10328. OR [Object] LIKE '% RETURNS %' OR [Object] LIKE '% RETURNS' OR [Object] = 'RETURNS'
  10329. OR [Object] LIKE '% REVOKE %' OR [Object] LIKE '% REVOKE' OR [Object] = 'REVOKE'
  10330. OR [Object] LIKE '% RIGHT %' OR [Object] LIKE '% RIGHT' OR [Object] = 'RIGHT'
  10331. OR [Object] LIKE '% ROLE %' OR [Object] LIKE '% ROLE' OR [Object] = 'ROLE'
  10332. OR [Object] LIKE '% ROLLBACK %' OR [Object] LIKE '% ROLLBACK' OR [Object] = 'ROLLBACK'
  10333. OR [Object] LIKE '% ROLLUP %' OR [Object] LIKE '% ROLLUP' OR [Object] = 'ROLLUP'
  10334. OR [Object] LIKE '% ROUTINE %' OR [Object] LIKE '% ROUTINE' OR [Object] = 'ROUTINE'
  10335. OR [Object] LIKE '% ROW %' OR [Object] LIKE '% ROW' OR [Object] = 'ROW'
  10336. OR [Object] LIKE '% ROWCOUNT %' OR [Object] LIKE '% ROWCOUNT' OR [Object] = 'ROWCOUNT'
  10337. OR [Object] LIKE '% ROWGUIDCOL %' OR [Object] LIKE '% ROWGUIDCOL' OR [Object] = 'ROWGUIDCOL'
  10338. OR [Object] LIKE '% ROWS %' OR [Object] LIKE '% ROWS' OR [Object] = 'ROWS'
  10339. OR [Object] LIKE '% RULE %' OR [Object] LIKE '% RULE' OR [Object] = 'RULE'
  10340. OR [Object] LIKE '% SAVE %' OR [Object] LIKE '% SAVE' OR [Object] = 'SAVE'
  10341. OR [Object] LIKE '% SAVEPOINT %' OR [Object] LIKE '% SAVEPOINT' OR [Object] = 'SAVEPOINT'
  10342. OR [Object] LIKE '% SCHEMA %' OR [Object] LIKE '% SCHEMA' OR [Object] = 'SCHEMA'
  10343. OR [Object] LIKE '% SCOPE %' OR [Object] LIKE '% SCOPE' OR [Object] = 'SCOPE'
  10344. OR [Object] LIKE '% SCROLL %' OR [Object] LIKE '% SCROLL' OR [Object] = 'SCROLL'
  10345. OR [Object] LIKE '% SEARCH %' OR [Object] LIKE '% SEARCH' OR [Object] = 'SEARCH'
  10346. OR [Object] LIKE '% SECOND %' OR [Object] LIKE '% SECOND' OR [Object] = 'SECOND'
  10347. OR [Object] LIKE '% SECTION %' OR [Object] LIKE '% SECTION' OR [Object] = 'SECTION'
  10348. OR [Object] LIKE '% SELECT %' OR [Object] LIKE '% SELECT' OR [Object] = 'SELECT'
  10349. OR [Object] LIKE '% SEQUENCE %' OR [Object] LIKE '% SEQUENCE' OR [Object] = 'SEQUENCE'
  10350. OR [Object] LIKE '% SESSION %' OR [Object] LIKE '% SESSION' OR [Object] = 'SESSION'
  10351. OR [Object] LIKE '% SESSION_USER %' OR [Object] LIKE '% SESSION_USER' OR [Object] = 'SESSION_USER'
  10352. OR [Object] LIKE '% SET %' OR [Object] LIKE '% SET' OR [Object] = 'SET'
  10353. OR [Object] LIKE '% SETS %' OR [Object] LIKE '% SETS' OR [Object] = 'SETS'
  10354. OR [Object] LIKE '% SETUSER %' OR [Object] LIKE '% SETUSER' OR [Object] = 'SETUSER'
  10355. OR [Object] LIKE '% SHUTDOWN %' OR [Object] LIKE '% SHUTDOWN' OR [Object] = 'SHUTDOWN'
  10356. OR [Object] LIKE '% SIZE %' OR [Object] LIKE '% SIZE' OR [Object] = 'SIZE'
  10357. OR [Object] LIKE '% SMALLINT %' OR [Object] LIKE '% SMALLINT' OR [Object] = 'SMALLINT'
  10358. OR [Object] LIKE '% SOME %' OR [Object] LIKE '% SOME' OR [Object] = 'SOME'
  10359. OR [Object] LIKE '% SPACE %' OR [Object] LIKE '% SPACE' OR [Object] = 'SPACE'
  10360. OR [Object] LIKE '% SPECIFIC %' OR [Object] LIKE '% SPECIFIC' OR [Object] = 'SPECIFIC'
  10361. OR [Object] LIKE '% SPECIFICTYPE %' OR [Object] LIKE '% SPECIFICTYPE' OR [Object] = 'SPECIFICTYPE'
  10362. OR [Object] LIKE '% SQL %' OR [Object] LIKE '% SQL' OR [Object] = 'SQL'
  10363. OR [Object] LIKE '% SQLCA %' OR [Object] LIKE '% SQLCA' OR [Object] = 'SQLCA'
  10364. OR [Object] LIKE '% SQLCODE %' OR [Object] LIKE '% SQLCODE' OR [Object] = 'SQLCODE'
  10365. OR [Object] LIKE '% SQLERROR %' OR [Object] LIKE '% SQLERROR' OR [Object] = 'SQLERROR'
  10366. OR [Object] LIKE '% SQLEXCEPTION %' OR [Object] LIKE '% SQLEXCEPTION' OR [Object] = 'SQLEXCEPTION'
  10367. OR [Object] LIKE '% SQLSTATE %' OR [Object] LIKE '% SQLSTATE' OR [Object] = 'SQLSTATE'
  10368. OR [Object] LIKE '% SQLWARNING %' OR [Object] LIKE '% SQLWARNING' OR [Object] = 'SQLWARNING'
  10369. OR [Object] LIKE '% START %' OR [Object] LIKE '% START' OR [Object] = 'START'
  10370. OR [Object] LIKE '% STATE %' OR [Object] LIKE '% STATE' OR [Object] = 'STATE'
  10371. OR [Object] LIKE '% STATEMENT %' OR [Object] LIKE '% STATEMENT' OR [Object] = 'STATEMENT'
  10372. OR [Object] LIKE '% STATIC %' OR [Object] LIKE '% STATIC' OR [Object] = 'STATIC'
  10373. OR [Object] LIKE '% STATISTICS %' OR [Object] LIKE '% STATISTICS' OR [Object] = 'STATISTICS'
  10374. OR [Object] LIKE '% STRUCTURE %' OR [Object] LIKE '% STRUCTURE' OR [Object] = 'STRUCTURE'
  10375. OR [Object] LIKE '% SUBSTRING %' OR [Object] LIKE '% SUBSTRING' OR [Object] = 'SUBSTRING'
  10376. OR [Object] LIKE '% SUM %' OR [Object] LIKE '% SUM' OR [Object] = 'SUM'
  10377. OR [Object] LIKE '% SYSTEM_USER %' OR [Object] LIKE '% SYSTEM_USER' OR [Object] = 'SYSTEM_USER'
  10378. OR [Object] LIKE '% TABLE %' OR [Object] LIKE '% TABLE' OR [Object] = 'TABLE'
  10379. OR [Object] LIKE '% TEMPORARY %' OR [Object] LIKE '% TEMPORARY' OR [Object] = 'TEMPORARY'
  10380. OR [Object] LIKE '% TERMINATE %' OR [Object] LIKE '% TERMINATE' OR [Object] = 'TERMINATE'
  10381. OR [Object] LIKE '% TEXTSIZE %' OR [Object] LIKE '% TEXTSIZE' OR [Object] = 'TEXTSIZE'
  10382. OR [Object] LIKE '% THAN %' OR [Object] LIKE '% THAN' OR [Object] = 'THAN'
  10383. OR [Object] LIKE '% THEN %' OR [Object] LIKE '% THEN' OR [Object] = 'THEN'
  10384. OR [Object] LIKE '% TIME %' OR [Object] LIKE '% TIME' OR [Object] = 'TIME'
  10385. OR [Object] LIKE '% TIMESTAMP %' OR [Object] LIKE '% TIMESTAMP' OR [Object] = 'TIMESTAMP'
  10386. OR [Object] LIKE '% TIMEZONE_HOUR %' OR [Object] LIKE '% TIMEZONE_HOUR' OR [Object] = 'TIMEZONE_HOUR'
  10387. OR [Object] LIKE '% TIMEZONE_MINUTE %' OR [Object] LIKE '% TIMEZONE_MINUTE' OR [Object] = 'TIMEZONE_MINUTE'
  10388. OR [Object] LIKE '% TO %' OR [Object] LIKE '% TO' OR [Object] = 'TO'
  10389. OR [Object] LIKE '% TOP %' OR [Object] LIKE '% TOP' OR [Object] = 'TOP'
  10390. OR [Object] LIKE '% TRAILING %' OR [Object] LIKE '% TRAILING' OR [Object] = 'TRAILING'
  10391. OR [Object] LIKE '% TRAN %' OR [Object] LIKE '% TRAN' OR [Object] = 'TRAN'
  10392. OR [Object] LIKE '% TRANSACTION %' OR [Object] LIKE '% TRANSACTION' OR [Object] = 'TRANSACTION'
  10393. OR [Object] LIKE '% TRANSLATE %' OR [Object] LIKE '% TRANSLATE' OR [Object] = 'TRANSLATE'
  10394. OR [Object] LIKE '% TRANSLATION %' OR [Object] LIKE '% TRANSLATION' OR [Object] = 'TRANSLATION'
  10395. OR [Object] LIKE '% TREAT %' OR [Object] LIKE '% TREAT' OR [Object] = 'TREAT'
  10396. OR [Object] LIKE '% TRIGGER %' OR [Object] LIKE '% TRIGGER' OR [Object] = 'TRIGGER'
  10397. OR [Object] LIKE '% TRIM %' OR [Object] LIKE '% TRIM' OR [Object] = 'TRIM'
  10398. OR [Object] LIKE '% TRUE %' OR [Object] LIKE '% TRUE' OR [Object] = 'TRUE'
  10399. OR [Object] LIKE '% TRUNCATE %' OR [Object] LIKE '% TRUNCATE' OR [Object] = 'TRUNCATE'
  10400. OR [Object] LIKE '% UNDER %' OR [Object] LIKE '% UNDER' OR [Object] = 'UNDER'
  10401. OR [Object] LIKE '% UNION %' OR [Object] LIKE '% UNION' OR [Object] = 'UNION'
  10402. OR [Object] LIKE '% UNIQUE %' OR [Object] LIKE '% UNIQUE' OR [Object] = 'UNIQUE'
  10403. OR [Object] LIKE '% UNKNOWN %' OR [Object] LIKE '% UNKNOWN' OR [Object] = 'UNKNOWN'
  10404. OR [Object] LIKE '% UNNEST %' OR [Object] LIKE '% UNNEST' OR [Object] = 'UNNEST'
  10405. OR [Object] LIKE '% UPDATE %' OR [Object] LIKE '% UPDATE' OR [Object] = 'UPDATE'
  10406. OR [Object] LIKE '% UPDATETEXT %' OR [Object] LIKE '% UPDATETEXT' OR [Object] = 'UPDATETEXT'
  10407. OR [Object] LIKE '% UPPER %' OR [Object] LIKE '% UPPER' OR [Object] = 'UPPER'
  10408. OR [Object] LIKE '% USAGE %' OR [Object] LIKE '% USAGE' OR [Object] = 'USAGE'
  10409. OR [Object] LIKE '% USE %' OR [Object] LIKE '% USE' OR [Object] = 'USE'
  10410. OR [Object] LIKE '% USER %' OR [Object] LIKE '% USER' OR [Object] = 'USER'
  10411. OR [Object] LIKE '% USING %' OR [Object] LIKE '% USING' OR [Object] = 'USING'
  10412. OR [Object] LIKE '% VALUE %' OR [Object] LIKE '% VALUE' OR [Object] = 'VALUE'
  10413. OR [Object] LIKE '% VALUES %' OR [Object] LIKE '% VALUES' OR [Object] = 'VALUES'
  10414. OR [Object] LIKE '% VARCHAR %' OR [Object] LIKE '% VARCHAR' OR [Object] = 'VARCHAR'
  10415. OR [Object] LIKE '% VARIABLE %' OR [Object] LIKE '% VARIABLE' OR [Object] = 'VARIABLE'
  10416. OR [Object] LIKE '% VARYING %' OR [Object] LIKE '% VARYING' OR [Object] = 'VARYING'
  10417. OR [Object] LIKE '% VIEW %' OR [Object] LIKE '% VIEW' OR [Object] = 'VIEW'
  10418. OR [Object] LIKE '% WAITFOR %' OR [Object] LIKE '% WAITFOR' OR [Object] = 'WAITFOR'
  10419. OR [Object] LIKE '% WHEN %' OR [Object] LIKE '% WHEN' OR [Object] = 'WHEN'
  10420. OR [Object] LIKE '% WHENEVER %' OR [Object] LIKE '% WHENEVER' OR [Object] = 'WHENEVER'
  10421. OR [Object] LIKE '% WHERE %' OR [Object] LIKE '% WHERE' OR [Object] = 'WHERE'
  10422. OR [Object] LIKE '% WHILE %' OR [Object] LIKE '% WHILE' OR [Object] = 'WHILE'
  10423. OR [Object] LIKE '% WITH %' OR [Object] LIKE '% WITH' OR [Object] = 'WITH'
  10424. OR [Object] LIKE '% WITHOUT %' OR [Object] LIKE '% WITHOUT' OR [Object] = 'WITHOUT'
  10425. OR [Object] LIKE '% WORK %' OR [Object] LIKE '% WORK' OR [Object] = 'WORK'
  10426. OR [Object] LIKE '% WRITE %' OR [Object] LIKE '% WRITE' OR [Object] = 'WRITE'
  10427. OR [Object] LIKE '% WRITETEXT %' OR [Object] LIKE '% WRITETEXT' OR [Object] = 'WRITETEXT'
  10428. OR [Object] LIKE '% YEAR %' OR [Object] LIKE '% YEAR' OR [Object] = 'YEAR'
  10429. OR [Object] LIKE '% ZONE %' OR [Object] LIKE '% ZONE' OR [Object] = 'ZONE');
  10430. /* http://msdn.microsoft.com/en-us/library/ms186755.aspx */
  10431. INSERT INTO #tmpfinalobjectnames
  10432. SELECT 5, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10433. FROM #tmpobjectnames
  10434. WHERE [type] IN ('FN','FS','TF','IF') AND [Object] LIKE 'fn[_]%'
  10435. AND [Object] NOT IN ('fn_diagram_objects');
  10436. IF (SELECT COUNT(*) FROM #tmpfinalobjectnames) > 0
  10437. BEGIN
  10438. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check], '[WARNING: Reserved words or special characters have been found in object names]' AS [Deviation]
  10439. END
  10440. ELSE
  10441. BEGIN
  10442. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check], '[OK]' AS [Deviation]
  10443. END;
  10444. IF (SELECT COUNT(*) FROM #tmpfinalobjectnames) > 0
  10445. BEGIN
  10446. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check],
  10447. CASE [Deviation] WHEN 1 THEN '[sp_ as prefix for stored procedures]'
  10448. WHEN 2 THEN '[Special character as part of object name]'
  10449. WHEN 3 THEN '[Special character as part of column name]'
  10450. WHEN 4 THEN '[Reserved words as part of object name]'
  10451. WHEN 5 THEN '[fn_ as prefix for user defined functions]'
  10452. END AS [Deviation],
  10453. [DBName] AS [Database_Name], [schemaName] AS [Schema_Name], [Object] AS [Object_Name], QUOTENAME([Col]) AS [Col], [type_desc] AS [Object_Type]
  10454. FROM #tmpfinalobjectnames
  10455. ORDER BY [Deviation], type_desc, [DBName], [schemaName], [Object];
  10456. END;
  10457. RAISERROR (N'|-Starting Security Checks', 10, 1) WITH NOWAIT
  10458. --------------------------------------------------------------------------------------------------------------------------------
  10459. -- Password check subsection
  10460. --------------------------------------------------------------------------------------------------------------------------------
  10461. RAISERROR (N' |-Starting Password check', 10, 1) WITH NOWAIT
  10462. DECLARE @passwords TABLE ([Deviation] VARCHAR(15), [Name] sysname, [CreateDate] DATETIME)
  10463. DECLARE @word TABLE (word NVARCHAR(50))
  10464. INSERT INTO @word values (0)
  10465. INSERT INTO @word values (1)
  10466. INSERT INTO @word values (12)
  10467. INSERT INTO @word values (123)
  10468. INSERT INTO @word values (1234)
  10469. INSERT INTO @word values (12345)
  10470. INSERT INTO @word values (123456)
  10471. INSERT INTO @word values (1234567)
  10472. INSERT INTO @word values (12345678)
  10473. INSERT INTO @word values (123456789)
  10474. INSERT INTO @word values (1234567890)
  10475. INSERT INTO @word values (11111)
  10476. INSERT INTO @word values (111111)
  10477. INSERT INTO @word values (1111111)
  10478. INSERT INTO @word values (11111111)
  10479. INSERT INTO @word values (21)
  10480. INSERT INTO @word values (321)
  10481. INSERT INTO @word values (4321)
  10482. INSERT INTO @word values (54321)
  10483. INSERT INTO @word values (654321)
  10484. INSERT INTO @word values (7654321)
  10485. INSERT INTO @word values (87654321)
  10486. INSERT INTO @word values (987654321)
  10487. INSERT INTO @word values (0987654321)
  10488. INSERT INTO @word values ('pwd')
  10489. INSERT INTO @word values ('Password')
  10490. INSERT INTO @word values ('password')
  10491. INSERT INTO @word values ('P@ssw0rd')
  10492. INSERT INTO @word values ('p@ssw0rd')
  10493. INSERT INTO @word values ('Teste')
  10494. INSERT INTO @word values ('teste')
  10495. INSERT INTO @word values ('Test')
  10496. INSERT INTO @word values ('test')
  10497. INSERT INTO @word values ('')
  10498. INSERT INTO @word values ('p@wd')
  10499. INSERT INTO @passwords
  10500. SELECT DISTINCT 'Weak_Password' AS Deviation, RTRIM(s.name) AS [Name], createdate AS [CreateDate]
  10501. FROM @word d
  10502. INNER JOIN master.sys.syslogins s ON PWDCOMPARE(RTRIM(RTRIM(d.word)), s.[password]) = 1
  10503. UNION ALL
  10504. SELECT 'NULL_Passwords' AS Deviation, RTRIM(name) AS [Name], createdate AS [CreateDate]
  10505. FROM master.sys.syslogins
  10506. WHERE [password] IS NULL
  10507. AND isntname = 0
  10508. AND name NOT IN ('MSCRMSqlClrLogin','##MS_SmoExtendedSigningCertificate##','##MS_PolicySigningCertificate##','##MS_SQLResourceSigningCertificate##','##MS_SQLReplicationSigningCertificate##','##MS_SQLAuthenticatorCertificate##','##MS_AgentSigningCertificate##','##MS_SQLEnableSystemAssemblyLoadingUser##')
  10509. UNION ALL
  10510. SELECT DISTINCT 'Name=Password' AS Deviation, RTRIM(s.name) AS [Name], createdate AS [CreateDate]
  10511. FROM master.sys.syslogins s
  10512. WHERE PWDCOMPARE(RTRIM(RTRIM(s.name)), s.[password]) = 1
  10513. ORDER BY [Deviation], [Name]
  10514. IF (SELECT COUNT([Deviation]) FROM @passwords) > 0
  10515. BEGIN
  10516. 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]
  10517. SELECT 'Security_checks' AS [Category], 'Password_checks' AS [Information], [Deviation], [Name], [CreateDate]
  10518. FROM @passwords
  10519. ORDER BY [Deviation], [Name]
  10520. END
  10521. ELSE
  10522. BEGIN
  10523. SELECT 'Security_checks' AS [Category], 'Password_checks' AS [Check], '[OK]' AS [Deviation]
  10524. END;
  10525. RAISERROR (N'|-Starting Maintenance and Monitoring Checks', 10, 1) WITH NOWAIT
  10526. --------------------------------------------------------------------------------------------------------------------------------
  10527. -- SQL Agent alerts for severe errors subsection
  10528. --------------------------------------------------------------------------------------------------------------------------------
  10529. RAISERROR (N' |-Starting SQL Agent alerts for severe errors', 10, 1) WITH NOWAIT
  10530. IF (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 1) = 0 AND (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 2) = 0
  10531. BEGIN
  10532. 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')
  10533. --RETURN
  10534. END
  10535. ELSE
  10536. BEGIN
  10537. 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]
  10538. FROM msdb.dbo.sysalerts
  10539. WHERE [message_id] IN (825,833,855,856,3452,3619,17179,17883,17884,17887,17888,17890,28036) OR severity = 10
  10540. UNION ALL
  10541. 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]
  10542. FROM msdb.dbo.sysalerts
  10543. WHERE [message_id] IN (610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300) OR severity = 16
  10544. UNION ALL
  10545. 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]
  10546. FROM msdb.dbo.sysalerts
  10547. WHERE [message_id] IN (802,845,1101,1105,1121,1214,8642,9002) OR severity = 17
  10548. UNION ALL
  10549. 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]
  10550. FROM msdb.dbo.sysalerts
  10551. WHERE [message_id] IN (701) OR severity = 19
  10552. UNION ALL
  10553. 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]
  10554. FROM msdb.dbo.sysalerts
  10555. WHERE [message_id] IN (3624) OR severity = 20
  10556. UNION ALL
  10557. 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]
  10558. FROM msdb.dbo.sysalerts
  10559. WHERE [message_id] IN (605) OR severity = 21
  10560. UNION ALL
  10561. 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]
  10562. FROM msdb.dbo.sysalerts
  10563. WHERE [message_id] IN (5180,8966) OR severity = 22
  10564. UNION ALL
  10565. 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]
  10566. FROM msdb.dbo.sysalerts
  10567. WHERE [message_id] IN (5572,9100) OR severity = 23
  10568. UNION ALL
  10569. 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]
  10570. FROM msdb.dbo.sysalerts
  10571. WHERE [message_id] IN (823,824,832) OR severity = 24
  10572. 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
  10573. 610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300, -- Sev 16
  10574. 802,845,1101,1105,1121,1214,8642,9002, -- Sev 17
  10575. 701, -- Sev 19
  10576. 3624, -- Sev 20
  10577. 605, -- Sev 21
  10578. 5180,8966, -- Sev 22
  10579. 5572,9100, -- Sev 23
  10580. 823,824,832 -- Sev 24
  10581. ) OR [severity] >= 17)) > 0
  10582. BEGIN
  10583. 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]
  10584. FROM msdb.dbo.sysalerts
  10585. WHERE ([message_id] IN (825,833,855,856,3452,3619,17179,17883,17884,17887,17888,17890,28036, -- Sev 10
  10586. 610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300, -- Sev 16
  10587. 802,845,1101,1105,1121,1214,8642,9002, -- Sev 17
  10588. 701, -- Sev 19
  10589. 3624, -- Sev 20
  10590. 605, -- Sev 21
  10591. 5180,8966, -- Sev 22
  10592. 5572,9100, -- Sev 23
  10593. 823,824,832 -- Sev 24
  10594. ) OR [severity] >= 17);
  10595. END
  10596. END;
  10597. --------------------------------------------------------------------------------------------------------------------------------
  10598. -- DBCC CHECKDB, Direct Catalog Updates and Data Purity subsection
  10599. --------------------------------------------------------------------------------------------------------------------------------
  10600. RAISERROR (N' |-Starting DBCC CHECKDB, Direct Catalog Updates and Data Purity', 10, 1) WITH NOWAIT
  10601. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  10602. DROP TABLE #output_dbinfo;
  10603. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  10604. CREATE TABLE #output_dbinfo (ParentObject VARCHAR(255), [Object] VARCHAR(255), Field VARCHAR(255), [value] VARCHAR(255))
  10605. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  10606. DROP TABLE #dbinfo;
  10607. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  10608. 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)
  10609. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1)
  10610. BEGIN
  10611. --DECLARE @dbname NVARCHAR(255);
  10612. DECLARE @dbcc bit, @catupd bit, @purity bit;
  10613. DECLARE curDBs CURSOR FAST_FORWARD FOR SELECT name FROM master.sys.databases (NOLOCK) WHERE is_read_only = 0 AND [state] = 0
  10614. OPEN curDBs
  10615. FETCH NEXT FROM curDBs INTO @dbname
  10616. WHILE (@@FETCH_STATUS = 0)
  10617. BEGIN
  10618. SET @dbname = RTRIM(LTRIM(@dbname))
  10619. INSERT INTO #output_dbinfo
  10620. EXEC('DBCC DBINFO(''' + @dbname + ''') WITH TABLERESULTS, NO_INFOMSGS')
  10621. INSERT INTO #dbinfo (dbname, lst_known_checkdb)
  10622. SELECT @dbname, [value] FROM #output_dbinfo WHERE Field LIKE 'dbi_dbccLastKnownGood%';
  10623. UPDATE #dbinfo
  10624. SET #dbinfo.updSysCatalog = #output_dbinfo.[value]
  10625. FROM #output_dbinfo
  10626. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_updSysCatalog%';
  10627. UPDATE #dbinfo
  10628. SET #dbinfo.dbi_createVersion = #output_dbinfo.[value]
  10629. FROM #output_dbinfo
  10630. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_createVersion%';
  10631. UPDATE #dbinfo
  10632. SET #dbinfo.dbi_dbccFlags = #output_dbinfo.[value]
  10633. FROM #output_dbinfo
  10634. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_dbccFlags%';
  10635. TRUNCATE TABLE #output_dbinfo;
  10636. FETCH NEXT FROM curDBs INTO @dbname
  10637. END
  10638. CLOSE curDBs
  10639. DEALLOCATE curDBs;
  10640. ;WITH cte_dbcc (name, lst_known_checkdb) AS (SELECT sd.name, tmpdbi.lst_known_checkdb
  10641. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10642. WHERE sd.database_id <> 2 AND is_read_only = 0 AND [state] = 0)
  10643. SELECT @dbcc = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10644. FROM cte_dbcc WHERE DATEDIFF(dd, lst_known_checkdb, GETDATE()) > 7 OR lst_known_checkdb IS NULL;
  10645. ;WITH cte_catupd (name, updSysCatalog) AS (SELECT sd.name, tmpdbi.updSysCatalog
  10646. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10647. WHERE sd.database_id <> 2 AND is_read_only = 0 AND [state] = 0)
  10648. SELECT @catupd = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10649. FROM cte_catupd WHERE updSysCatalog > '1900-01-01 00:00:00.000';
  10650. ;WITH cte_purity (name, dbi_createVersion, dbi_dbccFlags) AS (SELECT sd.name, tmpdbi.dbi_createVersion, tmpdbi.dbi_dbccFlags
  10651. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10652. WHERE sd.database_id > 4 AND is_read_only = 0 AND [state] = 0)
  10653. SELECT @purity = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10654. FROM cte_purity WHERE dbi_createVersion <= 611 AND dbi_dbccFlags = 0; -- <= SQL Server 2005
  10655. IF @dbcc = 1
  10656. BEGIN
  10657. 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]
  10658. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'DBCC_CHECKDB' AS [Information], [name] AS [Database_Name], MAX(lst_known_checkdb) AS Last_Known_CHECKDB
  10659. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10660. WHERE database_id <> 2 AND is_read_only = 0 AND [state] = 0
  10661. GROUP BY [name]
  10662. HAVING DATEDIFF(dd, MAX(lst_known_checkdb), GETDATE()) > 7 OR MAX(lst_known_checkdb) IS NULL
  10663. ORDER BY [name]
  10664. END
  10665. ELSE
  10666. BEGIN
  10667. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'DBCC_CHECKDB' AS [Check], '[OK]' AS [Deviation]
  10668. END;
  10669. IF @catupd = 1
  10670. BEGIN
  10671. SELECT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Check], '[WARNING: Microsoft does not support direct catalog updates to databases.]' AS [Deviation]
  10672. SELECT DISTINCT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Information], [name] AS [Database_Name], MAX(updSysCatalog) AS Last_Direct_Catalog_Update
  10673. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10674. WHERE database_id <> 2 AND is_read_only = 0 AND [state] = 0
  10675. GROUP BY [name]
  10676. HAVING (MAX(updSysCatalog) > '1900-01-01 00:00:00.000')
  10677. ORDER BY [name]
  10678. END
  10679. ELSE
  10680. BEGIN
  10681. SELECT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Check], '[OK]' AS [Deviation]
  10682. END;
  10683. -- http://support.microsoft.com/kb/923247/en-us
  10684. -- http://www.sqlskills.com/blogs/paul/checkdb-from-every-angle-how-to-tell-if-data-purity-checks-will-be-run
  10685. IF @purity = 1
  10686. BEGIN
  10687. 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]
  10688. 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
  10689. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10690. WHERE database_id > 4 AND dbi_createVersion <= 611 AND dbi_dbccFlags = 0 AND is_read_only = 0 AND [state] = 0
  10691. ORDER BY [name]
  10692. END
  10693. ELSE
  10694. BEGIN
  10695. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Databases_need_data_purity_check' AS [Check], '[OK]' AS [Deviation]
  10696. END;
  10697. END
  10698. ELSE
  10699. BEGIN
  10700. RAISERROR('[WARNING: Only a sysadmin can run the "DBCC CHECKDB, Direct Catalog Updates and Data Purity" checks. Bypassing check]', 16, 1, N'sysadmin')
  10701. --RETURN
  10702. END;
  10703. --------------------------------------------------------------------------------------------------------------------------------
  10704. -- AlwaysOn/Mirroring automatic page repair subsection
  10705. -- Refer to "Automatic Page Repair" BOL entry for more information (http://msdn.microsoft.com/en-us/library/bb677167.aspx)
  10706. --------------------------------------------------------------------------------------------------------------------------------
  10707. IF @sqlmajorver > 9
  10708. BEGIN
  10709. RAISERROR (N' |-Starting AlwaysOn/Mirroring automatic page repair', 10, 1) WITH NOWAIT
  10710. IF @sqlmajorver > 10
  10711. BEGIN
  10712. DECLARE @HadrRep int--, @sqlcmd NVARCHAR(4000), @params NVARCHAR(500)
  10713. SET @sqlcmd = N'SELECT @HadrRepOUT = COUNT(*) FROM sys.dm_hadr_auto_page_repair';
  10714. SET @params = N'@HadrRepOUT int OUTPUT';
  10715. EXECUTE sp_executesql @sqlcmd, @params, @HadrRepOUT=@HadrRep OUTPUT;
  10716. END
  10717. ELSE
  10718. BEGIN
  10719. SET @HadrRep = 0
  10720. END;
  10721. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  10722. DROP TABLE #pagerepair;
  10723. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  10724. 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)
  10725. IF (SELECT COUNT(*) FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)) > 0
  10726. BEGIN
  10727. INSERT INTO #pagerepair
  10728. SELECT DB_NAME(database_id) AS [Database_Name], [file_id], [page_id], [error_type], page_status, MAX(modification_time), 'Mirroring' AS [Repair_Source]
  10729. FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)
  10730. GROUP BY database_id, [file_id], [page_id], [error_type], page_status
  10731. END
  10732. IF @HadrRep > 0
  10733. BEGIN
  10734. INSERT INTO #pagerepair
  10735. 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]')
  10736. END;
  10737. IF (SELECT COUNT(*) FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)) > 0
  10738. OR @HadrRep > 0
  10739. BEGIN
  10740. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Check], '[WARNING: Page repairs have been found. Check for suspect pages]' AS [Deviation]
  10741. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Information], dbname AS [Database_Name],
  10742. [file_id] AS [File_ID],
  10743. [page_id] AS [Page_ID],
  10744. CASE [error_type]
  10745. WHEN -1 THEN 'Error 823'
  10746. WHEN 1 THEN 'Unspecified Error 824'
  10747. WHEN 2 THEN 'Bad Checksum'
  10748. WHEN 3 THEN 'Torn Page'
  10749. ELSE NULL
  10750. END AS [Error_Type],
  10751. CASE page_status
  10752. WHEN 2 THEN 'Queued for request from partner'
  10753. WHEN 3 THEN 'Request sent to partner'
  10754. WHEN 4 THEN 'Queued for automatic page repair'
  10755. WHEN 5 THEN 'Automatic page repair succeeded'
  10756. WHEN 6 THEN 'Irreparable'
  10757. END AS [Page_Status],
  10758. lst_modification_time AS [Last_Modification_Time], [Repair_Source]
  10759. FROM #pagerepair
  10760. END
  10761. ELSE
  10762. BEGIN
  10763. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Check], '[None]' AS [Deviation], '' AS [Source]
  10764. END
  10765. END;
  10766. --------------------------------------------------------------------------------------------------------------------------------
  10767. -- Suspect pages subsection
  10768. -- Refer to "Manage the suspect_pages Table" BOL entry for more information (http://msdn.microsoft.com/en-us/library/ms191301.aspx)
  10769. --------------------------------------------------------------------------------------------------------------------------------
  10770. RAISERROR (N' |-Starting Suspect pages', 10, 1) WITH NOWAIT
  10771. IF (SELECT COUNT(*) FROM msdb.dbo.suspect_pages WHERE (event_type = 1 OR event_type = 2 OR event_type = 3)) > 0
  10772. BEGIN
  10773. 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]
  10774. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Suspect_Pages' AS [Information], DB_NAME(database_id) AS [Database_Name],
  10775. [file_id] AS [File_ID],
  10776. [page_id] AS [Page_ID],
  10777. CASE event_type
  10778. WHEN 1 THEN 'Error 823 or unspecified Error 824'
  10779. WHEN 2 THEN 'Bad Checksum'
  10780. WHEN 3 THEN 'Torn Page'
  10781. ELSE NULL
  10782. END AS [Event_Type],
  10783. error_count AS [Error_Count],
  10784. last_update_date AS [Last_Update_Date]
  10785. FROM msdb.dbo.suspect_pages (NOLOCK)
  10786. WHERE (event_type = 1 OR event_type = 2 OR event_type = 3)
  10787. ORDER BY DB_NAME(database_id), last_update_date DESC, [file_id], [page_id]
  10788. END
  10789. ELSE
  10790. BEGIN
  10791. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Suspect_Pages' AS [Check], '[None]' AS [Deviation]
  10792. END;
  10793. --------------------------------------------------------------------------------------------------------------------------------
  10794. -- Replication Errors subsection
  10795. --------------------------------------------------------------------------------------------------------------------------------
  10796. IF @replication = 1 AND (SELECT COUNT(*) FROM master.sys.databases (NOLOCK) WHERE [name] = 'distribution') > 0
  10797. BEGIN
  10798. RAISERROR (N' |-Starting Replication Errors', 10, 1) WITH NOWAIT
  10799. IF (SELECT COUNT(*) FROM distribution.dbo.MSdistribution_history AS msh
  10800. INNER JOIN distribution.dbo.MSrepl_errors AS mse ON mse.id = msh.error_id
  10801. INNER JOIN distribution.dbo.MSdistribution_agents AS msa ON msh.agent_id = msa.id
  10802. WHERE mse.time >= DATEADD(hh, - 24, GETDATE())) > 0
  10803. BEGIN
  10804. 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]
  10805. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Lst_24H' AS [Information],
  10806. msa.[name] AS [Distribution_Agent], msa.publisher_db AS [Publisher_DB],
  10807. msa.publication AS [Publication], msa.subscriber_db AS [Subscriber_DB], mse.error_code
  10808. FROM distribution.dbo.MSdistribution_history AS msh
  10809. INNER JOIN distribution.dbo.MSrepl_errors AS mse ON mse.id = msh.error_id
  10810. INNER JOIN distribution.dbo.MSdistribution_agents AS msa ON msh.agent_id = msa.id
  10811. WHERE mse.time >= DATEADD(hh, - 24, GETDATE())
  10812. GROUP BY msa.[name], msa.publisher_db, msa.publication, msa.subscriber_db, mse.error_code
  10813. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Details' AS [Information], msh.time,
  10814. msa.[name] AS [Distribution_Agent], msa.publisher_db AS [Publisher_DB],
  10815. msa.publication AS [Publication], msa.subscriber_db AS [Subscriber_DB],
  10816. mse.error_code, mse.error_text
  10817. FROM distribution.dbo.MSdistribution_history AS msh (NOLOCK)
  10818. INNER JOIN distribution.dbo.MSrepl_errors AS mse (NOLOCK) ON mse.id = msh.error_id AND mse.time = msh.time
  10819. INNER JOIN distribution.dbo.MSdistribution_agents AS msa (NOLOCK) ON msh.agent_id = msa.id
  10820. WHERE (mse.time >= DATEADD(hh, - 24, GETDATE()))
  10821. ORDER BY msh.time
  10822. END
  10823. ELSE
  10824. BEGIN
  10825. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Lst_24H' AS [Check], '[None]' AS [Deviation]
  10826. END
  10827. END;
  10828. --------------------------------------------------------------------------------------------------------------------------------
  10829. -- Errorlog based checks subsection
  10830. -- Because it is a string based search, add other search conditions as deemed fit.
  10831. --------------------------------------------------------------------------------------------------------------------------------
  10832. RAISERROR (N' |-Starting Errorlog based checks', 10, 1) WITH NOWAIT
  10833. --DECLARE @lognumber int, @logcount int
  10834. DECLARE @langid smallint
  10835. SELECT @langid = lcid FROM sys.syslanguages WHERE name = @@LANGUAGE
  10836. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  10837. OR ISNULL(IS_SRVROLEMEMBER(N'securityadmin'), 0) = 1 -- Is securityadmin
  10838. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_readerrorlog') > 0
  10839. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_readerrorlog') > 0
  10840. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_enumerrorlogs') > 0)
  10841. BEGIN
  10842. SET @lognumber = 0
  10843. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10844. DROP TABLE #dbcc;
  10845. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10846. CREATE TABLE #dbcc (rowid int IDENTITY(1,1) PRIMARY KEY, logid int NULL, logdate DATETIME, spid VARCHAR(50), logmsg VARCHAR(4000))
  10847. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10848. CREATE INDEX [dbcc_logmsg] ON dbo.[#dbcc](logid)
  10849. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  10850. DROP TABLE #avail_logs;
  10851. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  10852. CREATE TABLE #avail_logs (lognum int, logdate DATETIME, logsize int)
  10853. -- Get the number of available logs
  10854. INSERT INTO #avail_logs
  10855. EXEC xp_enumerrorlogs
  10856. SELECT @logcount = MAX(lognum) FROM #avail_logs
  10857. WHILE @lognumber < @logcount
  10858. BEGIN
  10859. -- Cycle thru sql error logs
  10860. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''15 seconds'''
  10861. BEGIN TRY
  10862. INSERT INTO #dbcc (logdate, spid, logmsg)
  10863. EXECUTE (@sqlcmd);
  10864. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10865. END TRY
  10866. BEGIN CATCH
  10867. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10868. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  10869. RAISERROR (@ErrorMessage, 16, 1);
  10870. END CATCH
  10871. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''deadlock'''
  10872. BEGIN TRY
  10873. INSERT INTO #dbcc (logdate, spid, logmsg)
  10874. EXECUTE (@sqlcmd);
  10875. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10876. END TRY
  10877. BEGIN CATCH
  10878. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10879. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  10880. RAISERROR (@ErrorMessage, 16, 1);
  10881. END CATCH
  10882. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''stack dump'''
  10883. BEGIN TRY
  10884. INSERT INTO #dbcc (logdate, spid, logmsg)
  10885. EXECUTE (@sqlcmd);
  10886. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10887. END TRY
  10888. BEGIN CATCH
  10889. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10890. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  10891. RAISERROR (@ErrorMessage, 16, 1);
  10892. END CATCH
  10893. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''Error:'''
  10894. BEGIN TRY
  10895. INSERT INTO #dbcc (logdate, spid, logmsg)
  10896. EXECUTE (@sqlcmd);
  10897. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10898. END TRY
  10899. BEGIN CATCH
  10900. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10901. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 4. ' + ERROR_MESSAGE()
  10902. RAISERROR (@ErrorMessage, 16, 1);
  10903. END CATCH
  10904. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''A significant part of sql server process memory has been paged out'''
  10905. BEGIN TRY
  10906. INSERT INTO #dbcc (logdate, spid, logmsg)
  10907. EXECUTE (@sqlcmd);
  10908. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10909. END TRY
  10910. BEGIN CATCH
  10911. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10912. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 5. ' + ERROR_MESSAGE()
  10913. RAISERROR (@ErrorMessage, 16, 1);
  10914. END CATCH
  10915. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''cachestore flush'''
  10916. BEGIN TRY
  10917. INSERT INTO #dbcc (logdate, spid, logmsg)
  10918. EXECUTE (@sqlcmd);
  10919. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10920. END TRY
  10921. BEGIN CATCH
  10922. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10923. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 6. ' + ERROR_MESSAGE()
  10924. RAISERROR (@ErrorMessage, 16, 1);
  10925. END CATCH
  10926. -- Next log
  10927. --SET @lognumber = @lognumber + 1
  10928. SELECT @lognumber = MIN(lognum) FROM #avail_logs WHERE lognum > @lognumber
  10929. END
  10930. IF (SELECT COUNT([rowid]) FROM #dbcc) > 0
  10931. BEGIN
  10932. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog' AS [Check], '[WARNING: Errorlog contains important messages.]' AS [Deviation];
  10933. ;WITH cte_dbcc (err, errcnt, logdate, logmsg)
  10934. AS (SELECT CASE WHEN logmsg LIKE 'Error: %' THEN RIGHT(LEFT(#dbcc.logmsg, CHARINDEX(',', #dbcc.logmsg)-1), CHARINDEX(',', #dbcc.logmsg)-8)
  10935. WHEN logmsg LIKE 'SQL Server has encountered % longer than 15 seconds %' THEN CONVERT(CHAR(3),833)
  10936. WHEN logmsg LIKE 'A significant part of sql server process memory has been paged out%' THEN CONVERT(CHAR(5),17890)
  10937. ELSE '' END AS err,
  10938. COUNT(logmsg) AS errcnt,
  10939. logdate,
  10940. 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'
  10941. 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.'
  10942. ELSE logmsg END AS logmsg
  10943. FROM #dbcc
  10944. GROUP BY logmsg, logdate
  10945. )
  10946. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog_Summary' AS [Information],
  10947. err AS [Error_Number],
  10948. SUM(errcnt) AS Error_Count,
  10949. MIN(logdate) AS [First_Logged_Date],
  10950. MAX(logdate) AS [Last_Logged_Date],
  10951. logmsg AS [Logged_Message],
  10952. CASE WHEN logmsg LIKE 'Error: 825%' THEN 'IO transient failure. Possible corruption'
  10953. 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'
  10954. WHEN logmsg LIKE 'Error: 855%' OR logmsg LIKE 'Error: 856%' THEN 'Hardware memory corruption'
  10955. WHEN logmsg LIKE 'Error: 3452%' THEN 'Metadata inconsistency in DB. Run DBCC CHECKIDENT'
  10956. WHEN logmsg LIKE 'Error: 3619%' THEN 'Chkpoint failed. No Log space available'
  10957. WHEN logmsg LIKE 'Error: 9002%' THEN 'No Log space available'
  10958. WHEN logmsg LIKE 'Error: 17204%' OR logmsg LIKE 'Error: 17207%' THEN 'Error opening file during startup process'
  10959. WHEN logmsg LIKE 'Error: 17179%' THEN 'No AWE - LPIM related'
  10960. WHEN logmsg LIKE 'Error: 17890%' THEN 'sqlservr process paged out'
  10961. WHEN logmsg LIKE 'Error: 2508%' THEN 'Catalog views inaccuracies in DB. Run DBCC UPDATEUSAGE'
  10962. WHEN logmsg LIKE 'Error: 2511%' THEN 'Index Keys errors'
  10963. WHEN logmsg LIKE 'Error: 3271%' THEN 'IO nonrecoverable error'
  10964. WHEN logmsg LIKE 'Error: 5228%' OR logmsg LIKE 'Error: 5229%' THEN 'Online Index operation errors'
  10965. WHEN logmsg LIKE 'Error: 5242%' THEN 'Page structural inconsistency'
  10966. WHEN logmsg LIKE 'Error: 5243%' THEN 'In-memory structural inconsistency'
  10967. WHEN logmsg LIKE 'Error: 5250%' THEN 'Corrupt page. Error cannot be fixed'
  10968. WHEN logmsg LIKE 'Error: 5901%' THEN 'Chkpoint failed. Possible corruption'
  10969. WHEN logmsg LIKE 'Error: 17130%' THEN 'No lock memory'
  10970. WHEN logmsg LIKE 'Error: 17300%' THEN 'Unable to run new system task'
  10971. WHEN logmsg LIKE 'Error: 802%' THEN 'No BP memory'
  10972. WHEN logmsg LIKE 'Error: 845%' OR logmsg LIKE 'Error: 1105%' OR logmsg LIKE 'Error: 1121%' THEN 'No disk space available'
  10973. WHEN logmsg LIKE 'Error: 1214%' THEN 'Internal parallelism error'
  10974. WHEN logmsg LIKE 'Error: 823%' OR logmsg LIKE 'Error: 824%' THEN 'IO failure. Possible corruption'
  10975. WHEN logmsg LIKE 'Error: 832%' THEN 'Page checksum error. Possible corruption'
  10976. 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'
  10977. WHEN logmsg LIKE 'Error: 5572%' THEN 'Possible FILESTREAM corruption'
  10978. WHEN logmsg LIKE 'Error: 9100%' THEN 'Possible index corruption'
  10979. -- How To Diagnose and Correct Errors 17883, 17884, 17887, and 17888 (http://technet.microsoft.com/en-us/library/cc917684.aspx)
  10980. WHEN logmsg LIKE 'Error: 17883%' THEN 'Non-yielding scheduler: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10981. WHEN logmsg LIKE 'Error: 17884%' OR logmsg LIKE 'Error: 17888%' THEN 'Deadlocked scheduler: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10982. WHEN logmsg LIKE 'Error: 17887%' THEN 'IO completion error: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10983. WHEN logmsg LIKE 'Error: 1205%' THEN 'Deadlocked transaction'
  10984. WHEN logmsg LIKE 'Error: 610%' THEN 'Page header invalid. Possible corruption'
  10985. WHEN logmsg LIKE 'Error: 8621%' THEN 'QP stack overflow during optimization. Please simplify the query'
  10986. WHEN logmsg LIKE 'Error: 8642%' THEN 'QP insufficient threads for parallelism'
  10987. WHEN logmsg LIKE 'Error: 701%' THEN 'Insufficient memory'
  10988. -- How to troubleshoot SQL Server error 8645 (http://support.microsoft.com/kb/309256)
  10989. WHEN logmsg LIKE 'Error: 8645%' THEN 'Insufficient memory: http://support.microsoft.com/kb/309256'
  10990. WHEN logmsg LIKE 'Error: 605%' THEN 'Page retrieval failed. Possible corruption'
  10991. -- How to troubleshoot Msg 5180 (http://support.microsoft.com/kb/2015747)
  10992. WHEN logmsg LIKE 'Error: 5180%' THEN 'Invalid file ID. Possible corruption: http://support.microsoft.com/kb/2015747'
  10993. WHEN logmsg LIKE 'Error: 8966%' THEN 'Unable to read and latch on a PFS or GAM page'
  10994. WHEN logmsg LIKE 'Error: 9001%' OR logmsg LIKE 'Error: 9002%' THEN 'Transaction log errors.'
  10995. WHEN logmsg LIKE 'Error: 9003%' OR logmsg LIKE 'Error: 9004%' OR logmsg LIKE 'Error: 9015%' THEN 'Transaction log errors. Possible corruption'
  10996. -- How to reduce paging of buffer pool memory in the 64-bit version of SQL Server (http://support.microsoft.com/kb/918483)
  10997. 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'
  10998. WHEN logmsg LIKE '%cachestore flush%' THEN 'CacheStore flush'
  10999. ELSE '' END AS [Comment],
  11000. 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','%'), '%%%', '%')
  11001. 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)
  11002. ELSE '' END AS [Look_for_Message_example]
  11003. FROM cte_dbcc
  11004. GROUP BY err, logmsg
  11005. ORDER BY SUM(errcnt) DESC;
  11006. IF @logdetail = 1
  11007. BEGIN
  11008. 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],
  11009. CASE WHEN logmsg LIKE 'Error: 825%' THEN 'IO transient failure. Possible corruption'
  11010. WHEN logmsg LIKE 'Error: 833%' OR logmsg LIKE 'SQL Server has encountered % longer than 15 seconds %' THEN 'Long IO detected'
  11011. WHEN logmsg LIKE 'Error: 855%' OR logmsg LIKE 'Error: 856%' THEN 'Hardware memory corruption'
  11012. WHEN logmsg LIKE 'Error: 3452%' THEN 'Metadata inconsistency in DB. Run DBCC CHECKIDENT'
  11013. WHEN logmsg LIKE 'Error: 3619%' THEN 'Chkpoint failed. No Log space available'
  11014. WHEN logmsg LIKE 'Error: 9002%' THEN 'No Log space available'
  11015. WHEN logmsg LIKE 'Error: 17179%' THEN 'No AWE - LPIM related'
  11016. WHEN logmsg LIKE 'Error: 17890%' THEN 'sqlservr process paged out'
  11017. WHEN logmsg LIKE 'Error: 17204%' OR logmsg LIKE 'Error: 17207%' THEN 'Error opening file during startup process'
  11018. WHEN logmsg LIKE 'Error: 2508%' THEN 'Catalog views inaccuracies in DB. Run DBCC UPDATEUSAGE'
  11019. WHEN logmsg LIKE 'Error: 2511%' THEN 'Index Keys errors'
  11020. WHEN logmsg LIKE 'Error: 3271%' THEN 'IO nonrecoverable error'
  11021. WHEN logmsg LIKE 'Error: 5228%' OR logmsg LIKE 'Error: 5229%' THEN 'Online Index operation errors'
  11022. WHEN logmsg LIKE 'Error: 5242%' THEN 'Page structural inconsistency'
  11023. WHEN logmsg LIKE 'Error: 5243%' THEN 'In-memory structural inconsistency'
  11024. WHEN logmsg LIKE 'Error: 5250%' THEN 'Corrupt page. Error cannot be fixed'
  11025. WHEN logmsg LIKE 'Error: 5901%' THEN 'Chkpoint failed. Possible corruption'
  11026. WHEN logmsg LIKE 'Error: 17130%' THEN 'No lock memory'
  11027. WHEN logmsg LIKE 'Error: 17300%' THEN 'Unable to run new system task'
  11028. WHEN logmsg LIKE 'Error: 802%' THEN 'No BP memory'
  11029. WHEN logmsg LIKE 'Error: 845%' OR logmsg LIKE 'Error: 1105%' OR logmsg LIKE 'Error: 1121%' THEN 'No disk space available'
  11030. WHEN logmsg LIKE 'Error: 1214%' THEN 'Internal parallelism error'
  11031. WHEN logmsg LIKE 'Error: 823%' OR logmsg LIKE 'Error: 824%' THEN 'IO failure. Possible corruption'
  11032. WHEN logmsg LIKE 'Error: 832%' THEN 'Page checksum error. Possible corruption'
  11033. 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'
  11034. WHEN logmsg LIKE 'Error: 5572%' THEN 'Possible FILESTREAM corruption'
  11035. WHEN logmsg LIKE 'Error: 9100%' THEN 'Possible index corruption'
  11036. -- How To Diagnose and Correct Errors 17883, 17884, 17887, and 17888 (http://technet.microsoft.com/en-us/library/cc917684.aspx)
  11037. WHEN logmsg LIKE 'Error: 17883%' THEN 'Non-yielding scheduler'
  11038. WHEN logmsg LIKE 'Error: 17884%' OR logmsg LIKE 'Error: 17888%' THEN 'Deadlocked scheduler'
  11039. WHEN logmsg LIKE 'Error: 17887%' THEN 'IO completion error'
  11040. WHEN logmsg LIKE 'Error: 1205%' THEN 'Deadlocked transaction'
  11041. WHEN logmsg LIKE 'Error: 610%' THEN 'Page header invalid. Possible corruption'
  11042. WHEN logmsg LIKE 'Error: 8621%' THEN 'QP stack overflow during optimization. Please simplify the query'
  11043. WHEN logmsg LIKE 'Error: 8642%' THEN 'QP insufficient threads for parallelism'
  11044. WHEN logmsg LIKE 'Error: 701%' THEN 'Insufficient memory'
  11045. -- How to troubleshoot SQL Server error 8645 (http://support.microsoft.com/kb/309256)
  11046. WHEN logmsg LIKE 'Error: 8645%' THEN 'Insufficient memory'
  11047. WHEN logmsg LIKE 'Error: 605%' THEN 'Page retrieval failed. Possible corruption'
  11048. -- How to troubleshoot Msg 5180 (http://support.microsoft.com/kb/2015747)
  11049. WHEN logmsg LIKE 'Error: 5180%' THEN 'Invalid file ID. Possible corruption'
  11050. WHEN logmsg LIKE 'Error: 8966%' THEN 'Unable to read and latch on a PFS or GAM page'
  11051. WHEN logmsg LIKE 'Error: 9001%' OR logmsg LIKE 'Error: 9002%' THEN 'Transaction log errors.'
  11052. WHEN logmsg LIKE 'Error: 9003%' OR logmsg LIKE 'Error: 9004%' OR logmsg LIKE 'Error: 9015%' THEN 'Transaction log errors. Possible corruption'
  11053. -- How to reduce paging of buffer pool memory in the 64-bit version of SQL Server (http://support.microsoft.com/kb/918483)
  11054. 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'
  11055. WHEN logmsg LIKE '%cachestore flush%' THEN 'CacheStore flush'
  11056. ELSE '' END AS [Comment]
  11057. FROM #dbcc
  11058. ORDER BY logdate DESC
  11059. END
  11060. END
  11061. ELSE
  11062. BEGIN
  11063. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog' AS [Check], '[OK]' AS [Deviation]
  11064. END;
  11065. END
  11066. ELSE
  11067. BEGIN
  11068. RAISERROR('[WARNING: Only a sysadmin or securityadmin can run the "Errorlog" check. Bypassing check]', 16, 1, N'permissions')
  11069. 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')
  11070. --RETURN
  11071. END;
  11072. --------------------------------------------------------------------------------------------------------------------------------
  11073. -- System health error checks subsection
  11074. --------------------------------------------------------------------------------------------------------------------------------
  11075. IF @sqlmajorver > 10
  11076. BEGIN
  11077. RAISERROR (N' |-Starting System health checks', 10, 1) WITH NOWAIT
  11078. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11079. DROP TABLE #SystemHealthSessionData;
  11080. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11081. CREATE TABLE #SystemHealthSessionData (target_data XML)
  11082. -- Store the XML data in a temporary table
  11083. INSERT INTO #SystemHealthSessionData
  11084. SELECT CAST(xet.target_data AS XML)
  11085. FROM sys.dm_xe_session_targets xet
  11086. INNER JOIN sys.dm_xe_sessions xe ON xe.address = xet.event_session_address
  11087. WHERE xe.name = 'system_health'
  11088. IF (SELECT COUNT(*) FROM #SystemHealthSessionData a WHERE CONVERT(VARCHAR(max), target_data) LIKE '%error_reported%') > 0
  11089. BEGIN
  11090. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors' AS [Check], '[WARNING: System Health Session contains important messages.]' AS [Deviation];
  11091. -- Get statistical information about all the errors reported
  11092. ;WITH cteHealthSession (EventXML) AS (SELECT C.query('.') EventXML
  11093. FROM #SystemHealthSessionData a
  11094. CROSS APPLY a.target_data.nodes('/RingBufferTarget/event') AS T(C)
  11095. ),
  11096. cteErrorReported (EventTime, ErrorNumber) AS (SELECT EventXML.value('(/event/@timestamp)[1]', 'datetime') AS EventTime,
  11097. EventXML.value('(/event/data[@name="error_number"]/value)[1]', 'int') AS ErrorNumber
  11098. FROM cteHealthSession
  11099. WHERE EventXML.value('(/event/@name)[1]', 'VARCHAR(500)') = 'error_reported'
  11100. )
  11101. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors_Summary' AS [Information],
  11102. ErrorNumber AS [Error_Number],
  11103. MIN(EventTime) AS [First_Logged_Date],
  11104. MAX(EventTime) AS [Last_Logged_Date],
  11105. COUNT(ErrorNumber) AS Error_Count,
  11106. 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]
  11107. FROM cteErrorReported a
  11108. INNER JOIN sys.messages b ON a.ErrorNumber = b.message_id
  11109. WHERE b.language_id = @langid
  11110. GROUP BY a.ErrorNumber, b.[text]
  11111. -- Get detailed information about all the errors reported
  11112. ;WITH cteHealthSession AS (SELECT C.query('.').value('(/event/@timestamp)[1]', 'datetime') AS EventTime,
  11113. C.query('.').value('(/event/data[@name="error_number"]/value)[1]', 'int') AS ErrorNumber,
  11114. C.query('.').value('(/event/data[@name="severity"]/value)[1]', 'int') AS ErrorSeverity,
  11115. C.query('.').value('(/event/data[@name="state"]/value)[1]', 'int') AS ErrorState,
  11116. C.query('.').value('(/event/data[@name="message"]/value)[1]', 'VARCHAR(MAX)') AS ErrorText,
  11117. C.query('.').value('(/event/action[@name="session_id"]/value)[1]', 'int') AS SessionID,
  11118. C.query('.').value('(/event/data[@name="category"]/text)[1]', 'VARCHAR(10)') AS ErrorCategory
  11119. FROM #SystemHealthSessionData a
  11120. CROSS APPLY a.target_data.nodes('/RingBufferTarget/event') AS T(C)
  11121. WHERE C.query('.').value('(/event/@name)[1]', 'VARCHAR(500)') = 'error_reported')
  11122. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors_Detail' AS [Information],
  11123. EventTime AS [Logged_Date],
  11124. ErrorNumber AS [Error_Number],
  11125. ErrorSeverity AS [Error_Sev],
  11126. ErrorState AS [Error_State],
  11127. ErrorText AS [Logged_Message],
  11128. SessionID
  11129. FROM cteHealthSession
  11130. ORDER BY EventTime
  11131. END
  11132. ELSE
  11133. BEGIN
  11134. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors' AS [Check], '[OK]' AS [Deviation]
  11135. END;
  11136. END;
  11137. --------------------------------------------------------------------------------------------------------------------------------
  11138. -- Clean up temp objects
  11139. --------------------------------------------------------------------------------------------------------------------------------
  11140. RAISERROR (N'Clearing up temporary objects', 10, 1) WITH NOWAIT
  11141. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  11142. DROP TABLE #dbinfo;
  11143. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  11144. DROP TABLE #output_dbinfo;
  11145. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  11146. DROP TABLE #tblIOStall;
  11147. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  11148. DROP TABLE #tmpdbs1;
  11149. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  11150. DROP TABLE #tmpdbs0;
  11151. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  11152. DROP TABLE #tblPerfCount;
  11153. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  11154. DROP TABLE tempdb.dbo.tblPerfThresholds;
  11155. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  11156. DROP TABLE #tblHypObj;
  11157. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  11158. DROP TABLE #tblIxs1;
  11159. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  11160. DROP TABLE #tblIxs2;
  11161. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  11162. DROP TABLE #tblIxs3;
  11163. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  11164. DROP TABLE #tblIxs4;
  11165. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  11166. DROP TABLE #tblIxs5;
  11167. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  11168. DROP TABLE #tblIxs6;
  11169. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  11170. DROP TABLE #tblFK;
  11171. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  11172. DROP TABLE #dbcc;
  11173. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  11174. DROP TABLE #avail_logs;
  11175. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  11176. DROP TABLE #log_info1;
  11177. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  11178. DROP TABLE #log_info2;
  11179. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  11180. DROP TABLE #tmpobjectnames;
  11181. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  11182. DROP TABLE #tmpfinalobjectnames;
  11183. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  11184. DROP TABLE #tblWaits;
  11185. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  11186. DROP TABLE #tblFinalWaits;
  11187. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  11188. DROP TABLE #tblLatches;
  11189. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  11190. DROP TABLE #tblFinalLatches;
  11191. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  11192. DROP TABLE #IndexCreation;
  11193. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  11194. DROP TABLE #IndexRedundant;
  11195. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  11196. DROP TABLE #tblBlkChains;
  11197. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  11198. DROP TABLE #tblStatsSamp;
  11199. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  11200. DROP TABLE #tblSpinlocksBefore;
  11201. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  11202. DROP TABLE #tblSpinlocksAfter;
  11203. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  11204. DROP TABLE #tblFinalSpinlocks;
  11205. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  11206. DROP TABLE #pagerepair;
  11207. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  11208. DROP TABLE #tmp_dm_io_virtual_file_stats;
  11209. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  11210. DROP TABLE #tmp_dm_exec_query_stats;
  11211. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  11212. DROP TABLE #dm_exec_query_stats;
  11213. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  11214. DROP TABLE #tblPendingIOReq;
  11215. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  11216. DROP TABLE #tblPendingIO;
  11217. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  11218. DROP TABLE #qpwarnings;
  11219. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  11220. DROP TABLE #tblStatsUpd;
  11221. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  11222. DROP TABLE #tblPerSku;
  11223. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  11224. DROP TABLE #tblColStoreIXs;
  11225. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11226. DROP TABLE #SystemHealthSessionData;
  11227. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  11228. DROP TABLE #tmpdbfiledetail;
  11229. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  11230. DROP TABLE #tblHints;
  11231. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  11232. DROP TABLE #tblTriggers;
  11233. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  11234. DROP TABLE #tmpIPS;
  11235. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  11236. DROP TABLE #tblCode;
  11237. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  11238. DROP TABLE #tblWorking;
  11239. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  11240. DROP TABLE #tmpdbs_userchoice;
  11241. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  11242. DROP TABLE #xp_cmdshell_CluNodesOutput;
  11243. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  11244. DROP TABLE #xp_cmdshell_CluOutput;
  11245. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  11246. DROP TABLE #xp_cmdshell_Nodes;
  11247. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  11248. DROP TABLE #xp_cmdshell_QFEOutput;
  11249. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  11250. DROP TABLE #xp_cmdshell_QFEFinal;
  11251. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#RegResult'))
  11252. DROP TABLE #RegResult;
  11253. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ServiceStatus'))
  11254. DROP TABLE #ServiceStatus;
  11255. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  11256. DROP TABLE #xp_cmdshell_AcctSPNoutput;
  11257. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  11258. DROP TABLE #xp_cmdshell_DupSPNoutput;
  11259. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  11260. DROP TABLE #FinalDupSPN;
  11261. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  11262. DROP TABLE #ScopedDupSPN;
  11263. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  11264. DROP TABLE #tblDRI;
  11265. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  11266. DROP TABLE #tblInMemDBs;
  11267. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  11268. DROP TABLE #tmpXIS;
  11269. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  11270. DROP TABLE #tmpXNCIS;
  11271. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  11272. DROP TABLE #tmpIPS_CI;
  11273. 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')
  11274. 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')
  11275. 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')
  11276. 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')
  11277. RAISERROR (N'All done!', 10, 1) WITH NOWAIT
  11278. GO