Check_BP_Servers.sql 777 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131
  1. USE [master]
  2. GO
  3. DECLARE @custompath NVARCHAR(500), @allow_xpcmdshell bit, @ptochecks bit, @duration tinyint, @logdetail bit, @diskfrag bit, @ixfrag bit, @ixfragscanmode VARCHAR(8), @bpool_consumer bit, @gen_scripts bit, @dbScope VARCHAR(256), @spn_check bit
  4. /* Best Practices Check - [email protected] (http://aka.ms/BPCheck; http://aka.ms/sqlinsights)
  5. READ ME - Important options for executing BPCheck
  6. Set @duration to the number of seconds between data collection points regarding perf counters, waits and latches.
  7. Duration must be between 10s and 255s (4m 15s), with a default of 90s.
  8. Set @ptochecks to OFF if you want to skip more performance tuning and optimization oriented checks.
  9. Uncomment @custompath below and set the custom desired path for .ps1 files.
  10. If not, default location for .ps1 files is the Log folder.
  11. Set @allow_xpcmdshell to OFF if you want to skip checks that are dependant on xp_cmdshell.
  12. Note that original server setting for xp_cmdshell would be left unchanged if tests were allowed.
  13. Set @spn_check to OFF if you want to skip SPN checks.
  14. Set @diskfrag to ON if you want to check for disk physical fragmentation.
  15. Can take some time in large disks. Requires elevated privileges.
  16. Set @ixfrag to ON if you want to check for index fragmentation.
  17. Can take some time to collect data depending on number of databases and indexes, as well as the scan mode chosen in @ixfragscanmode.
  18. Set @ixfragscanmode to the scanning mode you prefer.
  19. More detail on scanning modes available at http://msdn.microsoft.com/en-us/library/ms188917.aspx
  20. Set @logdetail to OFF if you want to get just the summary info on issues in the Errorlog, rather than the full detail.
  21. Set @bpool_consumer to OFF if you want to list what are the Buffer Pool Consumers from Buffer Descriptors.
  22. Mind that it may take some time in servers with large caches.
  23. Set @gen_scripts to ON if you want to generate index related scripts.
  24. These include drops for Duplicate, Redundant, Hypothetical and Rarely Used indexes, as well as creation statements for FK and Missing Indexes.
  25. Set @dbScope to the appropriate list of database IDs if there's a need to have a specific scope for database specific checks.
  26. Valid input should be numeric value(s) between single quotes, as follows: '1,6,15,123'
  27. Leave NULL for all databases
  28. */
  29. SET @duration = 90
  30. SET @ptochecks = 1 --(1 = ON; 0 = OFF)
  31. --SET @custompath = 'C:\<temp_location>'
  32. SET @allow_xpcmdshell = 1 --(1 = ON; 0 = OFF)
  33. SET @spn_check = 0 --(1 = ON; 0 = OFF)
  34. SET @diskfrag = 1 --(1 = ON; 0 = OFF)
  35. SET @ixfrag = 1 --(1 = ON; 0 = OFF)
  36. SET @ixfragscanmode = 'LIMITED' --(Valid inputs are DEFAULT, NULL, LIMITED, SAMPLED, or DETAILED. The default (NULL) is LIMITED)
  37. SET @logdetail = 0 --(1 = ON; 0 = OFF)
  38. SET @bpool_consumer = 1 --(1 = ON; 0 = OFF)
  39. SET @gen_scripts = 0 --(1 = ON; 0 = OFF)
  40. SET @dbScope = NULL --(NULL = All DBs)
  41. /*
  42. DESCRIPTION: This script checks for skews in the most common best practices from SQL Server 2005 onwards.
  43. DISCLAIMER:
  44. This code is not supported under any Microsoft standard support program or service.
  45. This code and information are provided "AS IS" without warranty of any kind, either expressed or implied.
  46. The entire risk arising out of the use or performance of the script and documentation remains with you.
  47. Furthermore, Microsoft or the author shall not be liable for any damages you may sustain by using this information, whether direct,
  48. indirect, special, incidental or consequential, including, without limitation, damages for loss of business profits, business interruption, loss of business information
  49. or other pecuniary loss even if it has been advised of the possibility of such damages.
  50. Read all the implementation and usage notes thoroughly.
  51. v1 - 28-07-2011 - Initial release
  52. v1.1 - 28-01-2012 - Added some SQL 2012 support.
  53. v1.2 - 08-03-2012 - Added information to Database Information subsection;
  54. Added I/O stall in excess of 50% in database files subsection.
  55. v1.2.1 - 20-03-2012 - Added redundant index subsection;
  56. Added more SQL 2012 support;
  57. Changed database loop method.
  58. v1.2.2 - 22-03-2012 - Added check for Direct Catalog Updates.
  59. v1.2.3 - 05-04-2012 - Added unused index subsection;
  60. Fixed some collation issues.
  61. v1.2.4 - 07-04-2012 - Split in separate listings the unused indexes from rarely used indexes;
  62. Split in separate listings the real duplicates from possibly redundant indexes.
  63. v1.2.5 - 08-04-2012 - Added power plan check, by Aaron Bertrand (http://www.mssqltips.com/tip.asp?tip=2225&ctc).
  64. v1.2.6 - 13-04-2012 - Added NTFS block size check;
  65. Fixed issue in Data and Log locations check.
  66. v1.2.7 - 16-04-2012 - Added Errorlog based checks section.
  67. v1.2.8 - 21-04-2012 - Fixed issue with NTFS block size check;
  68. Added Replication Components installation check;
  69. Scan for Startup Procs checks for Replication Components installation.
  70. v1.2.9 - 04-05-2012 - Fixed issues when running on SQL Server 2005;
  71. COM object creation was revised.
  72. v1.3 - 08-05-2012 - Added support for customizing save location for .ps1 files;
  73. Default location is the Log folder. Optionally, uncomment line where @custompath is set and insert the desired path.
  74. v1.3.2 - 09-05-2012 - Added descriptive column to Database_Options test, to clear what are the Non-optimal_Settings for each database;
  75. Corrected bug with powershell files default save location, in case default location has changed since SQL Server install.
  76. v1.3.3 - 31-05-2012 - Fixed issue with DBCC CHECKDB test and offline databases.
  77. v1.3.4 - 03-06-2012 - Added more system configuration checks.
  78. v1.3.5 - 07-06-2012 - Added suspect pages check;
  79. Added more permissions checks in pre-requisites section;
  80. Added search for Errors in Errorlog checks.
  81. v1.3.6 - 08-06-2012 - Revised support for account checks in SQL 2012.
  82. v1.3.7 - 14-06-2012 - Fixed issue with large Object_Names;
  83. Fixed issue with Powershell 3.0 script;
  84. Data and log in same volume only lists affected objects now;
  85. Fixed blocking issue with hypothetical objects drop statements;
  86. Added duplicate indexes drop statements (all but the 1st of duplicates);
  87. Added tempDB in same location as user DBs check;
  88. Added backup checks.
  89. v1.3.8 - 19-06-2012 - Fixed issue with Errorlog based checks;
  90. Fixed issue with Data and Log locations.
  91. v1.3.9 - 05-07-2012 - Fixed issue with CPUs vs. MaxDOP check.
  92. v1.4.0 - 10-07-2012 - Added LPIM check;
  93. Added info to trace flags subsection.
  94. v1.4.1 - 18-07-2012 - Added information to CPUs vs. MaxDOP check.
  95. Added information about all backups since last Full (Database, File or Partial).
  96. v1.4.2 - 02-08-2012 - Added Processor Affinity information to instance info.
  97. v1.4.3 - 19-09-2012 - Fixed issue with large integer in DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled) subsection.
  98. v1.4.4 - 23-09-2012 - Added events to monitor to SQL Agent alerts for severe errors subsection;
  99. Added comment column for specific errors foun in Errorlog based checks subsection.
  100. v1.4.5 - 24-09-2012 - Fixed issue with Errorlog based checks subsection search.
  101. v1.4.6 - 17-10-2012 - Fixed issue with large percentages in Stall IO check.
  102. v1.4.7 - 24-10-2012 - Fixed issue with Data files and Logs in same physical volume check, where data and fulltext on the same volume raised an issue;
  103. Fixed issue with Service Accounts and Status check where LocalSystem would not raise issues;
  104. Widened search for Redundant Indexes.
  105. v1.4.8 - 01-11-2012 - Added generation of drop statements for existing Rarely Used indexes.
  106. v1.5.0 - 11-11-2012 - Fixed cpu affinity shows all zeros when auto affinity was used;
  107. Fixed issue with duplicate indexes check introduced with v1.4.8;
  108. Fixed issue with Errorlog based checks subsection search where no comments where shown;
  109. Added aggregates to CPU information subsection;
  110. Simplified logic in CPU Affinity in NUMA architecture subsection;
  111. Added checks to Server Memory information subsection;
  112. Added checks to System configurations subsection;
  113. Added a Deprecated features subsection;
  114. Changed perf counters collection method in Perf counters subsection;
  115. Added more counters to Perf counters subsection.
  116. v1.5.1 - 11-11-2012 - Fixed perf counters collection collecting from default instances only.
  117. v1.5.2 - 15-11-2012 - Fixed issue with long mountpoint paths;
  118. Fixed issue with Backup checks subsection;
  119. Added output from sys.messages to Errorlog based checks.
  120. v1.5.4 - 18-11-2012 - Added sql server process trimming to Errorlog based checks;
  121. Added more checks to System configurations subsection;
  122. Added HA information subsection;
  123. Added optimal nr of VLFs and log size to VLF subsection, based on current findings;
  124. Added even file number check for tempDB;
  125. Added minimum file number check for tempDB when < 4;
  126. Added summary to Errorlog based checks;
  127. Added column about IFI status in autogrow sections;
  128. Added further info to VLF section.
  129. v1.5.5 - 19-11-2012 - Added info to Instance Information subsection;
  130. Added Processor Summary subsection aggregating all CPU information;
  131. Added RM task output notifications;
  132. Format binary affinity mask by node for better reading.
  133. v1.5.6 - 24-11-2012 - Changed collection for several tests that can be supported by DMVs on SQL Server 2008 R2 SP1 and above (was implemented for SQL Server 2012 only);
  134. Added checks and information to Server Memory subsection.
  135. v1.5.7 - 10-12-2012 - Changed collection for Index checks to cope with large database names;
  136. Added support for collection through SQLDiag custom collector.
  137. v1.5.9 - 30-12-2012 - Added schema to index script generation;
  138. Fixed conversion issue with Max Worker Threads option;
  139. Added extended pagefile checks;
  140. Added Replication error checks;
  141. Added check for Indexes with large keys (> 900 bytes).
  142. v1.6.1 - 21-01-2013 - Fixed issue with SQL Server 2005 in Server Memory subsection;
  143. Fixed conversion issues with large msticks values;
  144. Fixed issue with Memory reference values.
  145. v1.6.2 - 02-02-2013 - Fixed issues with case sensitive collations;
  146. Expanded search for redundant indexes;
  147. Expanded system configuration checks;
  148. Added Plan use ratio checks;
  149. Added Hints usage check;
  150. Added Linked servers information;
  151. Added AlwaysOn/Mirroring automatic page repairs check;
  152. Added check for user DBs with Auto_Update_Statistics_Asynch enabled and Auto_Update_Statistics disabled;
  153. Extended I/O Stall checks to verify I/O latencies.
  154. v1.6.3 - 13-02-2013 - Added option to skip PS based tests where activating xp_cmdshell is strictly forbidden (See Readme at the top).
  155. v1.6.4 - 18-02-2013 - Added Buffer Node to performance counters collection;
  156. Added information to RM Notifications section;
  157. Added Cached Query Plans issues checks (Top 25 by CPU, IO and Recompiles with plan warnings);
  158. Added Object Naming Convention checks
  159. v1.6.5 - 27-02-2013 - Added check for databases that need to run DBCC CHECKDB (...) WITH DATA_PURITY;
  160. Added Waits and Latches information;
  161. Added check for statistics that need to be updated;
  162. Optimized performance counters collection;
  163. Extended performance counters collection to 90s;
  164. Removed alternate keys from search for Unused and Rarely used indexes;
  165. Added parameter to enable/disable performance tuning and optimization oriented checks;
  166. Added parameter to enable/disable best practices oriented checks;
  167. v1.6.6 - 05-03-2013 - Removed MS Shipped objects from duplicate and redundant indexes check;
  168. Added search for tables with no indexes, tables with no clustered indexes and tables with more indexes than columns.
  169. v1.6.7 - 01-04-2013 - Fixed issue with AlwaysOn/Mirroring automatic page repair subsection in SQL 2008R2 or below;
  170. Fixed issue with Cached Query Plans issues subsection in SQL 2008R2 RTM;
  171. Added more database files information;
  172. Fixed false positives with DBs Autogrowth > 1GB check;
  173. Added check for TF834 (Large Page Support for BP) when Column Store Indexes are used;
  174. Fixed false positives with Power plan subsection.
  175. v1.6.8.1 - 03-04-2013 - Added min server memory setting checks;
  176. Added information to Errorlog checks;
  177. Fixed false negatives with "Data files and Logs / tempDB and user Databases in same volume" checks when PS is not available;
  178. Added check for tempDB Files with different autogrow setting.
  179. v1.6.9 - 11-04-2013 - Added Worker threads exhaustion check;
  180. Added support for sys.dm_db_stats_properties in Statistics update subsection, if on SQL 2008R2 SP2 or SQL 2012 SP1 or higher.
  181. Made changes to latch checks;
  182. Fixed false positives with Indexes with large keys (> 900 bytes) subsection.
  183. v1.7.0.2 - 07-05-2013 - Fixed Statistics update subsection for SQL 2005;
  184. Changed Errorlog aggregates;
  185. Added Historical Latches without BUFFER class;
  186. Added page file size check for WS2003;
  187. Added information to "Tables with more Indexes than Columns" check.
  188. v1.7.1 - 10-05-2013 - Added "Tables with partition misaligned indexes" check.
  189. v1.7.2 - 18-05-2013 - Added windows service pack level to machine information section;
  190. Changed information available in "Database_File_Information", namely pages calculated in MB;
  191. Added Enterprise features usage information per database;
  192. Added batch performance counters (SQL Server 2012);
  193. Rewrote all database loops.
  194. v1.7.3 - 24-05-2013 - "Query Plan Warnings" check now ignores workload in master and mssqlsystemresource databases;
  195. Fixed issue with running BPchecks without PTOChecks.
  196. v1.7.4 - 01-06-2013 - Added FK with no indexes check;
  197. Fixed issue with Statistics update check in prior to 2008R2 SP2 and 2012 SP1.
  198. v1.7.5 - 25-06-2013 - Added information to Enterprise features usage subsection;
  199. Split Unused indexes section into Unused_Indexes_With_Updates and Unused_Indexes_No_Updates;
  200. Extended Objects naming conventions checks;
  201. Added Disabled indexes subsection;
  202. Added indexes with low fill factor subsection;
  203. Added Non-unique clustered indexes subsection;
  204. Fixed issue with Cached Query Plans issues subsection.
  205. v1.7.6 - 20-07-2013 - Added check for AlwaysOn AG replication status per database (http://support.microsoft.com/kb/2857849);
  206. Fixed issue with large values in I/O Stall subsection;
  207. Added search parameters to Objects naming conventions subsection.
  208. v1.7.6.1-24-07-2013 - Fixed issue with Objects naming conventions checks.
  209. v1.7.6.2-30-07-2013 - Fixed issue with Objects naming conventions checks.
  210. v1.7.7 - 05-09-2013 - Added Missing Indexes output (most relevant - score based - use at you own discretion);
  211. Changed Processor Usage info from 1h to 2h.
  212. v1.7.8 - 21-09-2013 - Changed system database exclusion choices;
  213. Added information to User DBs with non-default options subsection;
  214. VLF section shows added information only on databases failing threshold.
  215. v1.7.9 - 09-10-2013 - Fixed issue with false positives in Purity Check;
  216. Added logic to exclude standard names of MS shipped databases from database design related checks;
  217. Added performance counters to collection.
  218. v1.8 - 25-10-2013 - Added blocking chains (over 5s);
  219. Added monitoring duration as parameter;
  220. Added more file related info to Autogrowth checks;
  221. Fixed CPU Affinity bit mask issue on 16 CPU+ servers;
  222. Extended password checks;
  223. Extended logic to exclude MS shipped databases, based on notable schema objects.
  224. v1.8.0.1 - 28-10-2013 - Fixed issues with logic to exclude MS shipped databases.
  225. v1.8.1 - 03-11-2013 - Added owner info to Database Information subsection;
  226. Fixed issue where no warning was raised for DBs that never had a Log Backup, but had Full/Diff Backups in Full or Bulk-logged RM;
  227. Added Statistics sampling < 25 pct check on SQL 2008R2 SP2 / SQL 2012 and above;
  228. Added Pending I/O Requests check;
  229. Added info to Windows Version and Architecture subsection;
  230. Added spinlocks info;
  231. Added Clustered Indexes with GUIDs in key checks;
  232. Extended trace flag checks.
  233. v1.8.2.1 - 11-11-2013 - Removed cursor from VLF checks;
  234. Added checks to System Configurations;
  235. Added checks to TempDB subsection;
  236. Fixed index statement generation in Foreign Keys with no Index subsection;
  237. Fixed issue with Statistics update subsection up to SQL 2008R2 SP2;
  238. Fixed duplicate key issue in Pending I/O Requests check;
  239. Fixed duplicate entries in redundant indexes of Missing Indexes checks;
  240. Fixed syntax issue in Foreign Keys with no Index subsection.
  241. v1.8.2.2 - 14-11-2013 - Added Dynamics GP database exclusions;
  242. Fixed syntax issue in System Configurations checks.
  243. v1.8.3 - 19-12-2013 - Fixed presentation issue in Pending I/O Requests subsection;
  244. Fixed conversion issue in Statistics Update subsection.
  245. v1.8.4 - 13-01-2014 - Fixed issue with database exclusions;
  246. Fixed issue with Service Accounts section in WS2003;
  247. Removed unwarranted information from DBCC CHECKDB, Direct Catalog Updates and Data Purity subsection.
  248. v1.8.4.1 - 06-02-2014- Added Service Accounts and SPN registration checks;
  249. Fixed issue with Redundant index checks on servers with CS collations.
  250. v1.8.5 - 21-02-2014 - Added LowMemoryThreshold and OOM information to Server Memory subsection;
  251. Extended Min Server Memory checks to Server Memory subsection;
  252. Added DBs with Sparse files checks;
  253. Added System health error checks;
  254. Added Resource Governor information;
  255. Added logdetail parameter to control listing the detail of all relevant Errorlog entries - which can sometimes bloat the output file to several hundred MBs;
  256. Fixed blocking chains (over 5s) showing on SP_SERVER_DIAGNOSTICS_SLEEP wait;
  257. Fixed backup size conversion issue;
  258. Fixed false positives in log backup checks;
  259. Fixed tempDB file size check and Database file information subsections based in sys.master_files may cause issues not to be reported;
  260. Fixed arithmetic overflow error in Statistics update check.
  261. v1.8.6 - 14-03-2014 - Duplicate script generation includes logic to account for PK when several IXs are unique;
  262. Optimized database discovery cycle;
  263. Fixed execution issue in AG DBs when no connections are allowed to the databases in the secondary replica, and the databases are not available for read access.
  264. v1.8.7 - 01-04-2014 - Fixed issue in Hypothetical objects drop script generation;
  265. Fixed issue in several subsections when offline DBs exist;
  266. Fixed issue introduced in v1.8.6 version where some checks would skip user DBs;
  267. Added information on clock hand notifications to Server Memory subsection;
  268. Added thresholds to some Performance Counters -> this does NOT replace a longer perf counter data collection and analysis.
  269. v1.8.7.1 - 03-04-2014 - Added Service Pack Supportability check;
  270. Fixed overflow issue in clock hand notifications;
  271. Fixed issue with clock hand notifications and SQL 2005.
  272. v1.8.8 - 23-04-2014 - Changed Pagefile free space check;
  273. Fixed missing index script creation of covering indexes;
  274. Fixed divide by zero errors in perf counters;
  275. Fixed issue with statistics checks in DBs with cmpt level 80;
  276. Fixed tempDB data file size issue - check was ok, but listed information might not be accurate;
  277. Added category column to all outputs (preparation for future developments).
  278. v1.8.9 - 09-05-2014 - Detailed categorization of memory related waits;
  279. Detailed MaxMem recommendation output;
  280. Added recommended MaxDOP value to Parallelism_MaxDOP check output;
  281. Fixed issue with No_Full_Backups check.
  282. v1.9 - 04-06-2014 - Refined search for duplicate and redundant indexes;
  283. Added partition misalign test (offset < 64KB);
  284. Added Buffer Pool Extension info subsection.
  285. v1.9.1 - 09-06-2014 - Fixed issue with duplicate and redundant index script generation.
  286. v1.9.2 - 13-06-2014 - Fixed calculation in page file checks;
  287. Added process paged out check (besides existing based in errorlog search).
  288. v1.9.3 - 08-07-2014 - Fixed backup checks reporting wrong size;
  289. Changed backup chain based checks to ignore copy_only backups;
  290. Updated Service Pack Supportability check;
  291. Added Cluster Quorum Model check;
  292. Added Cluster QFE node equality check.
  293. v1.9.4 - 16-07-2014 - Added Backups and Database files in same location check;
  294. Enhanced Hints Usage check with info from sql modules;
  295. Fixed Objects naming conventions checks not reporting issues.
  296. v1.9.5 - 17-09-2014 - Changed Hypothetical object search scope to all DBs, including MS shipped;
  297. Changed missing index check to include all missing by order of score, but still generating script only when score >= 100000;
  298. Added features to Enterprise features check;
  299. Expanded TF checks.
  300. v1.9.6.1 - 20-10-2014 - Fixed hypothetical statistics search;
  301. Fixed Parallelism_MaxDOP check on large NUMA nodes and specific MaxDOP settings;
  302. Fixed Cluster Quorum Model false positive when PS is not available;
  303. Changed Powershell availability verification to single step;
  304. Added user objects in master check;
  305. Added logon triggers information;
  306. Added database triggers information;
  307. Added Database file autogrows last 72h information;
  308. Added Cluster NIC Binding order check;
  309. Added Disk Fragmentation Analysis (only if running with elevated privs and enabled with variable @diskfrag);
  310. Added Index Fragmentation Analysis (only if enabled with variable @ixfrag);
  311. Fixed trace flag checks recommending trace flags that did not apply to server hardware.
  312. v1.9.6.2 - 23-10-2014 - Fixed false positive on Cluster NIC Binding order check;
  313. v1.9.6.3 - 25-10-2014 - Fixed syntax error on Cluster NIC Binding order check;
  314. v1.9.7 - 12-11-2014 - Changed Cluster Quorum Model check output;
  315. Fixed conversion issue with Buffer Pool Consumers section;
  316. Fixed issue on server that has only AG secondary replicas;
  317. Added model information to Machine Information section;
  318. Added @bpool_consumer option to skip listing Buffer Pool Consumers;
  319. Added @gen_scripts option to skip generating scripts (disabled by default);
  320. Added listing of which duplicate indexes are eligible for deletion;
  321. Added search for which of the duplicate indexes that are eligible for deletion are hard coded in sql modules.
  322. v1.9.8 - 10-12-2014 - Fixed issue with Cluster NIC Binding order subsection on case sensitive instances;
  323. Fixed issue with Database file autogrows last 72h subsection on case sensitive instances;
  324. Fixed issues with PS based checks running in PS v1;
  325. Fixed illegal characters issue in XML conversion;
  326. Fixed syntax error in SQL 2014 Memory Consumers from In-Memory OLTP Engine.
  327. v1.9.8.1 - 16-12-2014 - Fixed issues in Enterprise features usage subsection on SQL 2012 and AlwaysOn in use.
  328. v1.9.9 - 30-01-2015 - Fixed conversion issue in Plan_use_ratio check;
  329. Added HADR info to Database Information subsection;
  330. Added NUMA info to Server Memory subsection.
  331. v1.9.9.1 - 06-02-2015 - Fixed NUMA info collection issue up to SQL 2008R2 introduced in v1.9.9.
  332. v1.9.9.2 - 13-02-2015 - Fixed NUMA info collection issue on SQL 2012 and above introduced in v1.9.9;
  333. Added support to scope only specific databases by ID.
  334. v1.9.9.3 - 15-03-2015 - Fixed some information in "Database Information" section not being collected, introduced in v1.9.9.2.
  335. v1.9.9.5 - 11-04-2015 - Fixed System health error checks conversion error;
  336. Extended Memory Allocations from Memory Clerks checks;
  337. Extended logic to exclude MS shipped databases;
  338. Fixed overflow error in Blocking Chains check if larger than Integer supports;
  339. Fixed insert error in Pending I/O Requests check.
  340. v2.0.0 - 22-04-2015 - Added Declarative Referential Integrity - Untrusted Constraints checks;
  341. Added XTP Index Health Analysis;
  342. Added CCI Index Health Analysis: pseudo-fragmentation for CCI is the ratio of deleted_rows to total_rows;
  343. Renamed "Index Fragmentation Analysis" to "Index Health Analysis" subsection;
  344. Added storage analysis for In-Memory OLTP Engine in Database Information subsection;
  345. Fixed sp_server_diagnostics showing up as blocked session with long blocking time;
  346. Extended AO cluster information;
  347. Database filter now always includes sys DBs.
  348. v2.0.1 - 23-04-2015 - Fixed issue with SQL 2012 in Index Health analysis.
  349. v2.0.2 - 14-05-2015 - Added Default data collections (check for default trace, blackbox trace, SystemHealth xEvent session, sp_server_diagnostics xEvent session);
  350. Extended Objects naming conventions checks to functions;
  351. Added info on Inefficient Plans by CPU and Read I/O;
  352. Improved search for hypothetical objects;
  353. Added script generation to fix issues from Declarative Referential Integrity - Untrusted Constraints checks.
  354. v2.0.2.1 - 18-05-2015 - Fixed Declarative Referential Integrity script generation.
  355. v2.0.3 - 10-09-2015 - Added information about current PMO to Global Trace Flags check when 8048 may be missing.
  356. v2.0.3.1 - 11-09-2015 - Fixed PMO check up to 2008R2.
  357. v2.1 - 9/30/2016 - Fixed issue with LPIM check in SQL Server 2005;
  358. Tuned Memory Allocations from In-Memory OLTP Engine checks;
  359. Tuned I/O stall checks to separate overall stall time from avg latency tests;
  360. Fixed issue with DBs Autogrowth > 1GB check missing files if IFI is enabled;
  361. Updated Cached Query Plans section with new DMV columns;
  362. Workaround for windows version not correct under W10/WS2016;
  363. Added Disk space information;
  364. Added overall support for SQL Server 2012 SP3, 2014 SP2 and 2016 in multiple checks;
  365. Added plans with Inefficient Memory Use to Performance checks.
  366. v2.1.1 - 10/01/2016 - Fixed issues with Database Information subsection in SQL 2005 to 2008R2.
  367. v2.1.2 - 10/25/2016 - Added incremental stats as default to Database Options check;
  368. Added W10 Aniversary Edition to OS versions;
  369. Fixed Indexing per Table subsection accounting for hypotheical indexes.
  370. v2.1.3 - 10/26/2016 - Fixed conversion issue with Account checks;
  371. Fixed negative CPU usage in avg cpu usage last 2h check.
  372. v2.1.4 - 11/08/2016 - Fixed autogrows in last 72h shown in MB instead of KB.
  373. v2.1.5 - 11/17/2016 - Added support for SQL Server 2016 SP1 (Enterprise_features_usage, LPIM and IFI checks).
  374. v2.1.5.1 - 11/23/2016 - Fixed User DBs with non-default options subsection in SQL 2012.
  375. v2.1.5.2 - 2/23/2017 - Fixed conversion error in Service_Account_checks section.
  376. v2.1.5.3 - 2/26/2017 - Added SQL 2016 support for AlwaysOn_Replicas information section;
  377. Fixed conversion error when multiple TCP ports.
  378. v2.1.5.4 - 3/28/2017 - Fixed collation issues.
  379. PURPOSE: Checks SQL Server in scope for some of most common skewed Best Practices. Valid from SQL Server 2005 onwards.
  380. - Contains the following information:
  381. |- Uptime
  382. |- Windows Version and Architecture
  383. |- Disk space
  384. |- HA Information
  385. |- Linked servers info
  386. |- Instance info
  387. |- Resource Governor info
  388. |- Logon triggers
  389. |- Database Information
  390. |- Database file autogrows last 72h
  391. |- Database triggers
  392. |- Enterprise features usage
  393. |- Backups
  394. |- System Configuration
  395. - And performs the following checks (* means only when @ptochecks is ON):
  396. |- Processor
  397. |- Number of available Processors for this instance vs. MaxDOP setting
  398. |- Processor Affinity in NUMA architecture
  399. |- Additional Processor information
  400. |- Processor utilization rate in the last 2 hours *
  401. |- Memory
  402. |- Server Memory
  403. |- RM Task *
  404. |- Clock hands *
  405. |- Buffer Pool Consumers from Buffer Descriptors *
  406. |- Memory Allocations from Memory Clerks *
  407. |- Memory Consumers from In-Memory OLTP Engine *
  408. |- Memory Allocations from In-Memory OLTP Engine *
  409. |- OOM
  410. |- LPIM
  411. |- Pagefile
  412. |- Pagefile
  413. |- I/O
  414. |- I/O Stall subsection (wait for 5s) *
  415. |- Pending disk I/O Requests subsection (wait for a max of 5s) *
  416. |- Server
  417. |- Power plan
  418. |- NTFS block size in volumes that hold database files <> 64KB
  419. |- Disk Fragmentation Analysis (if enabled)
  420. |- Cluster Quorum Model
  421. |- Cluster QFE node equality
  422. |- Cluster NIC Binding order
  423. |- Service Accounts
  424. |- Service Accounts Status
  425. |- Service Accounts and SPN registration
  426. |- Instance
  427. |- Recommended build check
  428. |- Backups
  429. |- Global trace flags
  430. |- System configurations
  431. |- IFI
  432. |- Full Text Configurations
  433. |- Deprecated features *
  434. |- Default data collections (default trace, blackbox trace, SystemHealth xEvent session, sp_server_diagnostics xEvent session)
  435. |- Database and tempDB
  436. |- User objects in master
  437. |- DBs with collation <> master
  438. |- DBs with skewed compatibility level
  439. |- User DBs with non-default options
  440. |- DBs with Sparse files
  441. |- DBs Autogrow in percentage
  442. |- DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled)
  443. |- VLF
  444. |- Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware)
  445. |- tempDB data file configurations
  446. |- tempDB Files autogrow of equal size
  447. |- Performance
  448. |- Perf counters, Waits and Latches (wait for 90s) *
  449. |- Worker thread exhaustion *
  450. |- Blocking Chains *
  451. |- Plan use ratio *
  452. |- Hints usage *
  453. |- Cached Query Plans issues *
  454. |- Inefficient Query Plans *
  455. |- Declarative Referential Integrity - Untrusted Constraints *
  456. |- Indexes and Statistics
  457. |- Statistics update *
  458. |- Statistics sampling *
  459. |- Hypothetical objects *
  460. |- Row Index Fragmentation Analysis (if enabled) *
  461. |- CS Index Health Analysis (if enabled) *
  462. |- XTP Index Health Analysis (if enabled) *
  463. |- Duplicate or Redundant indexes *
  464. |- Unused and rarely used indexes *
  465. |- Indexes with large keys (> 900 bytes) *
  466. |- Indexes with fill factor < 80 pct *
  467. |- Disabled indexes *
  468. |- Non-unique clustered indexes *
  469. |- Clustered Indexes with GUIDs in key *
  470. |- Foreign Keys with no Index *
  471. |- Indexing per Table *
  472. |- Missing Indexes *
  473. |- Naming Convention
  474. |- Objects naming conventions
  475. |- Security
  476. |- Password check
  477. |- Maintenance and Monitoring
  478. |- SQL Agent alerts for severe errors
  479. |- DBCC CHECKDB, Direct Catalog Updates and Data Purity
  480. |- AlwaysOn/Mirroring automatic page repair
  481. |- Suspect pages
  482. |- Replication Errors
  483. |- Errorlog based checks
  484. |- System health checks
  485. DISCLAIMER:
  486. This code and information are provided "AS IS" without warranty of any kind, either expressed or implied.
  487. 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.
  488. IMPORTANT pre-requisites:
  489. - Only a sysadmin/local host admin will be able to perform all checks.
  490. - If you want to perform all checks under non-sysadmin credentials, then that login must be:
  491. Member of serveradmin server role or have the ALTER SETTINGS server permission;
  492. Member of MSDB SQLAgentOperatorRole role, or have SELECT permission on the sysalerts table in MSDB;
  493. Granted EXECUTE permissions on the following extended sprocs to run checks: sp_OACreate, sp_OADestroy, sp_OAGetErrorInfo, xp_enumerrorlogs, xp_fileexist and xp_regenumvalues;
  494. Granted EXECUTE permissions on xp_msver;
  495. Granted the VIEW SERVER STATE permission;
  496. Granted the VIEW DATABASE STATE permission;
  497. Granted EXECUTE permissions on xp_cmdshell or a xp_cmdshell proxy account should exist to run checks that access disk or OS security configurations.
  498. Member of securityadmin role, or have EXECUTE permissions on sp_readerrorlog.
  499. Otherwise some checks will be bypassed and warnings will be shown.
  500. - Powershell must be installed to run checks that access disk configurations, as well as allow execution of remote signed or unsigned scripts.
  501. */
  502. SET NOCOUNT ON;
  503. SET ANSI_WARNINGS ON;
  504. SET QUOTED_IDENTIFIER ON;
  505. SET DATEFORMAT mdy;
  506. RAISERROR (N'Starting Pre-requisites section', 10, 1) WITH NOWAIT
  507. --------------------------------------------------------------------------------------------------------------------------------
  508. -- Pre-requisites section
  509. --------------------------------------------------------------------------------------------------------------------------------
  510. DECLARE @sqlcmd NVARCHAR(max), @params NVARCHAR(500), @sqlmajorver int
  511. /*
  512. Reference: SERVERPROPERTY for sql major, minor and build versions supported after:
  513. @sqlmajorver >= 13 OR (@sqlmajorver = 12 AND @sqlbuild >= 2556 AND @sqlbuild < 4100) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427)
  514. */
  515. SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  516. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 0)
  517. BEGIN
  518. RAISERROR('[WARNING: Only a sysadmin can run ALL the checks]', 16, 1, N'sysadmin')
  519. --RETURN
  520. END;
  521. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 0)
  522. BEGIN
  523. DECLARE @pid int, @pname sysname, @msdbpid int, @masterpid int
  524. DECLARE @permstbl TABLE ([name] sysname);
  525. DECLARE @permstbl_msdb TABLE ([id] tinyint IDENTITY(1,1), [perm] tinyint)
  526. SET @params = '@msdbpid_in int'
  527. SELECT @pid = principal_id, @pname=name FROM master.sys.server_principals (NOLOCK) WHERE sid = SUSER_SID()
  528. SELECT @masterpid = principal_id FROM master.sys.database_principals (NOLOCK) WHERE sid = SUSER_SID()
  529. SELECT @msdbpid = principal_id FROM msdb.sys.database_principals (NOLOCK) WHERE sid = SUSER_SID()
  530. -- Perms 1
  531. IF (ISNULL(IS_SRVROLEMEMBER(N'serveradmin'), 0) <> 1) AND ((SELECT COUNT(l.name)
  532. FROM master.sys.server_permissions p (NOLOCK) INNER JOIN master.sys.server_principals l (NOLOCK)
  533. ON p.grantee_principal_id = l.principal_id
  534. AND p.class = 100 -- Server
  535. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  536. AND l.is_disabled = 0
  537. AND p.permission_name = 'ALTER SETTINGS'
  538. AND QUOTENAME(l.name) = QUOTENAME(@pname)) = 0)
  539. BEGIN
  540. 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')
  541. RETURN
  542. END
  543. ELSE IF (ISNULL(IS_SRVROLEMEMBER(N'serveradmin'), 0) <> 1) AND ((SELECT COUNT(l.name)
  544. FROM master.sys.server_permissions p (NOLOCK) INNER JOIN sys.server_principals l (NOLOCK)
  545. ON p.grantee_principal_id = l.principal_id
  546. AND p.class = 100 -- Server
  547. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  548. AND l.is_disabled = 0
  549. AND p.permission_name = 'VIEW SERVER STATE'
  550. AND QUOTENAME(l.name) = QUOTENAME(@pname)) = 0)
  551. BEGIN
  552. 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')
  553. RETURN
  554. END
  555. -- Perms 2
  556. INSERT INTO @permstbl
  557. SELECT a.name
  558. FROM master.sys.all_objects a (NOLOCK) INNER JOIN master.sys.database_permissions b (NOLOCK) ON a.[OBJECT_ID] = b.major_id
  559. WHERE a.type IN ('P', 'X') AND b.grantee_principal_id <>0
  560. AND b.grantee_principal_id <>2
  561. AND b.grantee_principal_id = @masterpid;
  562. INSERT INTO @permstbl_msdb ([perm])
  563. EXECUTE sp_executesql N'USE msdb; SELECT COUNT([name])
  564. FROM msdb.sys.sysusers (NOLOCK) WHERE [uid] IN (SELECT [groupuid]
  565. FROM msdb.sys.sysmembers (NOLOCK) WHERE [memberuid] = @msdbpid_in)
  566. AND [name] = ''SQLAgentOperatorRole''', @params, @msdbpid_in = @msdbpid;
  567. INSERT INTO @permstbl_msdb ([perm])
  568. EXECUTE sp_executesql N'USE msdb; SELECT COUNT(dp.grantee_principal_id)
  569. FROM msdb.sys.tables AS tbl (NOLOCK)
  570. INNER JOIN msdb.sys.database_permissions AS dp (NOLOCK) ON dp.major_id=tbl.object_id AND dp.class=1
  571. INNER JOIN msdb.sys.database_principals AS grantor_principal (NOLOCK) ON grantor_principal.principal_id = dp.grantor_principal_id
  572. INNER JOIN msdb.sys.database_principals AS grantee_principal (NOLOCK) ON grantee_principal.principal_id = dp.grantee_principal_id
  573. WHERE dp.state = ''G''
  574. AND dp.grantee_principal_id = @msdbpid_in
  575. AND dp.type = ''SL''', @params, @msdbpid_in = @msdbpid;
  576. IF (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 1) = 0 AND (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 2) = 0
  577. BEGIN
  578. 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')
  579. --RETURN
  580. END
  581. 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)
  582. BEGIN
  583. 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')
  584. --RETURN
  585. END
  586. 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
  587. BEGIN
  588. 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')
  589. --RETURN
  590. END
  591. ELSE IF (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') = 0 OR
  592. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') = 0 OR
  593. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') = 0 OR
  594. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') = 0 OR
  595. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') = 0 OR
  596. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 0 OR
  597. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 0 OR
  598. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_servicecontrol') = 0
  599. BEGIN
  600. 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')
  601. --RETURN
  602. END
  603. ELSE IF (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_msver') = 0 AND @sqlmajorver < 11
  604. BEGIN
  605. RAISERROR('[WARNING: Must be granted EXECUTE permissions on xp_msver to run full scope of checks]', 16, 1, N'extended_sprocs')
  606. --RETURN
  607. END
  608. END;
  609. -- Declare Global Variables
  610. DECLARE @UpTime VARCHAR(12),@StartDate DATETIME
  611. DECLARE @agt smallint, @ole smallint, @sao smallint, @xcmd smallint
  612. DECLARE @ErrorSeverity int, @ErrorState int, @ErrorMessage NVARCHAR(4000)
  613. DECLARE @CMD NVARCHAR(4000)
  614. DECLARE @path NVARCHAR(2048)
  615. DECLARE @sqlminorver int, @sqlbuild int, @clustered bit, @winver VARCHAR(5), @server VARCHAR(128), @instancename NVARCHAR(128), @arch smallint, @winsp VARCHAR(25), @SystemManufacturer VARCHAR(128)
  616. DECLARE @existout int, @FSO int, @FS int, @OLEResult int, @FileID int
  617. DECLARE @FileName VARCHAR(200), @Text1 VARCHAR(2000), @CMD2 VARCHAR(100)
  618. DECLARE @src VARCHAR(255), @desc VARCHAR(255), @psavail VARCHAR(20), @psver tinyint
  619. DECLARE @dbid int, @dbname VARCHAR(1000)
  620. SELECT @instancename = CONVERT(VARCHAR(128),SERVERPROPERTY('InstanceName'))
  621. SELECT @server = RTRIM(CONVERT(VARCHAR(128), SERVERPROPERTY('MachineName')))
  622. --SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  623. SELECT @sqlminorver = CONVERT(int, (@@microsoftversion / 0x10000) & 0xff);
  624. SELECT @sqlbuild = CONVERT(int, @@microsoftversion & 0xffff);
  625. SELECT @clustered = CONVERT(bit,ISNULL(SERVERPROPERTY('IsClustered'),0))
  626. -- Test Powershell policy
  627. IF @allow_xpcmdshell = 1
  628. BEGIN
  629. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  630. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  631. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  632. AND (SELECT COUNT(l.name)
  633. FROM sys.server_permissions p JOIN sys.server_principals l
  634. ON p.grantee_principal_id = l.principal_id
  635. AND p.class = 100 -- Server
  636. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  637. AND l.is_disabled = 0
  638. AND p.permission_name = 'ALTER SETTINGS'
  639. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  640. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  641. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  642. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0)))
  643. BEGIN
  644. DECLARE @pstbl_avail TABLE ([KeyExist] int)
  645. BEGIN TRY
  646. INSERT INTO @pstbl_avail
  647. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\PowerShell\1' -- check if Powershell is installed
  648. END TRY
  649. BEGIN CATCH
  650. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  651. SELECT @ErrorMessage = 'Could not determine if Powershell is installed - Error raised in TRY block. ' + ERROR_MESSAGE()
  652. RAISERROR (@ErrorMessage, 16, 1);
  653. END CATCH
  654. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  655. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  656. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  657. RAISERROR ('|-Configuration options set for Powershell enablement verification', 10, 1) WITH NOWAIT
  658. IF @sao = 0
  659. BEGIN
  660. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  661. END
  662. IF @xcmd = 0
  663. BEGIN
  664. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  665. END
  666. IF @ole = 0
  667. BEGIN
  668. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  669. END
  670. IF (SELECT [KeyExist] FROM @pstbl_avail) = 1
  671. BEGIN
  672. DECLARE @psavail_output TABLE ([PS_OUTPUT] VARCHAR(2048));
  673. INSERT INTO @psavail_output
  674. EXEC master.dbo.xp_cmdshell N'%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Get-ExecutionPolicy"'
  675. SELECT @psavail = [PS_OUTPUT] FROM @psavail_output WHERE [PS_OUTPUT] IS NOT NULL;
  676. END
  677. ELSE
  678. BEGIN
  679. RAISERROR (' [WARNING: Powershell is not installed. Install WinRM to proceed with PS based checks]',16,1);
  680. END
  681. IF (@psavail IS NOT NULL AND @psavail NOT IN ('RemoteSigned','Unrestricted'))
  682. RAISERROR (' [WARNING: Execution of Powershell scripts is disabled on this system.
  683. To change the execution policy, type the following command in Powershell console: Set-ExecutionPolicy RemoteSigned
  684. 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:
  685. Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  686. AllSigned - Only scripts signed by a trusted publisher can be run.
  687. RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  688. |- REQUIRED by BP Check
  689. Unrestricted - No restrictions; all Windows PowerShell scripts can be run.]',16,1);
  690. IF (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  691. BEGIN
  692. RAISERROR ('|- [INFORMATION: Powershell is installed and enabled for script execution]', 10, 1) WITH NOWAIT
  693. DECLARE @psver_output TABLE ([PS_OUTPUT] VARCHAR(1024));
  694. INSERT INTO @psver_output
  695. EXEC master.dbo.xp_cmdshell N'%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Get-Host | Format-Table -Property Version"'
  696. -- Gets PS version, as commands issued to PS v1 do not support -File
  697. SELECT @psver = ISNULL(LEFT([PS_OUTPUT],1),2) FROM @psver_output WHERE [PS_OUTPUT] IS NOT NULL AND ISNUMERIC(LEFT([PS_OUTPUT],1)) = 1;
  698. SET @ErrorMessage = '|- [INFORMATION: Installed Powershell is version ' + CONVERT(CHAR(1), @psver) + ']'
  699. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  700. END;
  701. IF @xcmd = 0
  702. BEGIN
  703. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  704. END
  705. IF @ole = 0
  706. BEGIN
  707. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  708. END
  709. IF @sao = 0
  710. BEGIN
  711. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  712. END;
  713. END
  714. ELSE
  715. BEGIN
  716. RAISERROR(' [WARNING: Missing permissions for Powershell enablement verification]', 16, 1, N'sysadmin')
  717. --RETURN
  718. END
  719. END;
  720. --------------------------------------------------------------------------------------------------------------------------------
  721. -- Information section
  722. --------------------------------------------------------------------------------------------------------------------------------
  723. RAISERROR (N'Starting Information section', 10, 1) WITH NOWAIT
  724. --------------------------------------------------------------------------------------------------------------------------------
  725. -- Uptime subsection
  726. --------------------------------------------------------------------------------------------------------------------------------
  727. RAISERROR (N'|-Starting Uptime', 10, 1) WITH NOWAIT
  728. IF @sqlmajorver < 10
  729. BEGIN
  730. SET @sqlcmd = N'SELECT @UpTimeOUT = DATEDIFF(mi, login_time, GETDATE()), @StartDateOUT = login_time FROM master..sysprocesses (NOLOCK) WHERE spid = 1';
  731. END
  732. ELSE
  733. BEGIN
  734. SET @sqlcmd = N'SELECT @UpTimeOUT = DATEDIFF(mi,sqlserver_start_time,GETDATE()), @StartDateOUT = sqlserver_start_time FROM sys.dm_os_sys_info (NOLOCK)';
  735. END
  736. SET @params = N'@UpTimeOUT VARCHAR(12) OUTPUT, @StartDateOUT DATETIME OUTPUT';
  737. EXECUTE sp_executesql @sqlcmd, @params, @UpTimeOUT=@UpTime OUTPUT, @StartDateOUT=@StartDate OUTPUT;
  738. 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
  739. --------------------------------------------------------------------------------------------------------------------------------
  740. -- Windows Version and Architecture subsection
  741. --------------------------------------------------------------------------------------------------------------------------------
  742. RAISERROR (N'|-Starting Windows Version and Architecture', 10, 1) WITH NOWAIT
  743. IF @sqlmajorver >= 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  744. BEGIN
  745. 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)';
  746. SET @params = N'@winverOUT VARCHAR(5) OUTPUT, @winspOUT VARCHAR(25) OUTPUT, @archOUT smallint OUTPUT';
  747. EXECUTE sp_executesql @sqlcmd, @params, @winverOUT=@winver OUTPUT, @winspOUT=@winsp OUTPUT, @archOUT=@arch OUTPUT;
  748. END
  749. ELSE
  750. BEGIN
  751. BEGIN TRY
  752. DECLARE @str VARCHAR(500), @str2 VARCHAR(500), @str3 VARCHAR(500)
  753. DECLARE @sysinfo TABLE (id int,
  754. [Name] NVARCHAR(256),
  755. Internal_Value bigint,
  756. Character_Value NVARCHAR(256));
  757. INSERT INTO @sysinfo
  758. EXEC xp_msver;
  759. 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
  760. FROM @sysinfo
  761. WHERE [Name] LIKE 'WindowsVersion%';
  762. SELECT @arch = CASE WHEN RTRIM(Character_Value) LIKE '%x64%' OR RTRIM(Character_Value) LIKE '%AMD64%' THEN 64
  763. WHEN RTRIM(Character_Value) LIKE '%x86%' OR RTRIM(Character_Value) LIKE '%32%' THEN 32
  764. WHEN RTRIM(Character_Value) LIKE '%IA64%' THEN 128 END
  765. FROM @sysinfo
  766. WHERE [Name] LIKE 'Platform%';
  767. SET @str = (SELECT @@VERSION)
  768. SELECT @str2 = RIGHT(@str, LEN(@str)-CHARINDEX('Windows',@str) + 1)
  769. SELECT @str3 = RIGHT(@str2, LEN(@str2)-CHARINDEX(': ',@str2))
  770. SELECT @winsp = LTRIM(LEFT(@str3, CHARINDEX(')',@str3) -1))
  771. END TRY
  772. BEGIN CATCH
  773. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  774. SELECT @ErrorMessage = 'Windows Version and Architecture subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  775. RAISERROR (@ErrorMessage, 16, 1);
  776. END CATCH
  777. END;
  778. DECLARE @machineinfo TABLE ([Value] NVARCHAR(256), [Data] NVARCHAR(256))
  779. INSERT INTO @machineinfo
  780. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemManufacturer';
  781. INSERT INTO @machineinfo
  782. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemProductName';
  783. INSERT INTO @machineinfo
  784. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','SystemFamily';
  785. INSERT INTO @machineinfo
  786. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSVendor';
  787. INSERT INTO @machineinfo
  788. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSVersion';
  789. INSERT INTO @machineinfo
  790. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\BIOS','BIOSReleaseDate';
  791. INSERT INTO @machineinfo
  792. EXEC xp_instance_regread 'HKEY_LOCAL_MACHINE','HARDWARE\DESCRIPTION\System\CentralProcessor\0','ProcessorNameString';
  793. SELECT @SystemManufacturer = [Data] FROM @machineinfo WHERE [Value] = 'SystemManufacturer';
  794. SELECT 'Information' AS [Category], 'Machine' AS [Information],
  795. CASE @winver WHEN '5.2' THEN 'XP/WS2003'
  796. WHEN '6.0' THEN 'Vista/WS2008'
  797. WHEN '6.1' THEN 'W7/WS2008R2'
  798. WHEN '6.2' THEN 'W8/WS2012'
  799. WHEN '6.3' THEN 'W8.1/WS2012R2'
  800. WHEN '10.0' THEN 'W10/WS2016'
  801. END AS [Windows_Version],
  802. @winsp AS [Service_Pack_Level],
  803. @arch AS [Architecture],
  804. SERVERPROPERTY('MachineName') AS [Machine_Name],
  805. SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [NetBIOS_Name],
  806. @SystemManufacturer AS [System_Manufacturer],
  807. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'SystemFamily') AS [System_Family],
  808. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'SystemProductName') AS [System_ProductName],
  809. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSVendor') AS [BIOS_Vendor],
  810. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSVersion') AS [BIOS_Version],
  811. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'BIOSReleaseDate') AS [BIOS_Release_Date],
  812. (SELECT [Data] FROM @machineinfo WHERE [Value] = 'ProcessorNameString') AS [Processor_Name];
  813. --------------------------------------------------------------------------------------------------------------------------------
  814. -- Disk space subsection
  815. --------------------------------------------------------------------------------------------------------------------------------
  816. RAISERROR (N'|-Starting Disk space', 10, 1) WITH NOWAIT
  817. SELECT DISTINCT 'Information' AS [Category], 'Disk_Space' AS [Information], vs.logical_volume_name,
  818. vs.volume_mount_point, vs.file_system_type, CONVERT(int,vs.total_bytes/1048576.0) AS TotalSpace_MB,
  819. CONVERT(int,vs.available_bytes/1048576.0) AS FreeSpace_MB, vs.is_compressed
  820. FROM sys.master_files mf
  821. CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.[file_id]) vs
  822. ORDER BY FreeSpace_MB ASC;
  823. --------------------------------------------------------------------------------------------------------------------------------
  824. -- HA Information subsection
  825. --------------------------------------------------------------------------------------------------------------------------------
  826. RAISERROR (N'|-Starting HA Information', 10, 1) WITH NOWAIT
  827. IF @clustered = 1
  828. BEGIN
  829. IF @sqlmajorver < 11
  830. BEGIN
  831. EXEC ('SELECT ''Information'' AS [Category], ''Cluster'' AS [Information], NodeName AS node_name FROM sys.dm_os_cluster_nodes (NOLOCK)')
  832. END
  833. ELSE
  834. BEGIN
  835. EXEC ('SELECT ''Information'' AS [Category], ''Cluster'' AS [Information], NodeName AS node_name, status_description, is_current_owner FROM sys.dm_os_cluster_nodes (NOLOCK)')
  836. END
  837. SELECT 'Information' AS [Category], 'Cluster' AS [Information], DriveName AS cluster_shared_drives FROM sys.dm_io_cluster_shared_drives (NOLOCK)
  838. END
  839. ELSE
  840. BEGIN
  841. SELECT 'Information' AS [Category], 'Cluster' AS [Information], 'NOT_CLUSTERED' AS [Status]
  842. END;
  843. IF @sqlmajorver > 10
  844. BEGIN
  845. DECLARE @IsHadrEnabled tinyint, @HadrManagerStatus tinyint
  846. SELECT @IsHadrEnabled = CONVERT(tinyint, SERVERPROPERTY('IsHadrEnabled'))
  847. SELECT @HadrManagerStatus = CONVERT(tinyint, SERVERPROPERTY('HadrManagerStatus'))
  848. SELECT 'Information' AS [Category], 'AlwaysOn_AG' AS [Information],
  849. CASE @IsHadrEnabled WHEN 0 THEN 'Disabled'
  850. WHEN 1 THEN 'Enabled' END AS [AlwaysOn_Availability_Groups],
  851. CASE WHEN @IsHadrEnabled = 1 THEN
  852. CASE @HadrManagerStatus WHEN 0 THEN '[Not started, pending communication]'
  853. WHEN 1 THEN '[Started and running]'
  854. WHEN 2 THEN '[Not started and failed]'
  855. END
  856. END AS [Status];
  857. IF @IsHadrEnabled = 1
  858. BEGIN
  859. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster)
  860. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster' AS [Information], cluster_name, quorum_type_desc, quorum_state_desc
  861. FROM sys.dm_hadr_cluster;
  862. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster_members)
  863. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster_Members' AS [Information], member_name, member_type_desc, member_state_desc, number_of_quorum_votes
  864. FROM sys.dm_hadr_cluster_members;
  865. IF EXISTS (SELECT 1 FROM sys.dm_hadr_cluster_networks)
  866. SELECT 'Information' AS [Category], 'AlwaysOn_Cluster_Networks' AS [Information], member_name, network_subnet_ip, network_subnet_ipv4_mask, is_public, is_ipv4
  867. FROM sys.dm_hadr_cluster_networks;
  868. END;
  869. IF @ptochecks = 1 AND @IsHadrEnabled = 1
  870. BEGIN
  871. -- Note: If low_water_mark_for_ghosts number is not increasing over time, it implies that ghost cleanup might not happen.
  872. SET @sqlcmd = 'SELECT ''Information'' AS [Category], ''AlwaysOn_Replicas'' AS [Information], database_id, group_id, replica_id, group_database_id, is_local, synchronization_state_desc,
  873. is_commit_participant, synchronization_health_desc, database_state_desc, is_suspended, suspend_reason_desc, last_sent_time, last_received_time, last_hardened_time,
  874. last_redone_time, log_send_queue_size, log_send_rate, redo_queue_size, redo_rate, filestream_send_rate, last_commit_time,
  875. low_water_mark_for_ghosts' + CASE WHEN @sqlmajorver > 12 THEN ', secondary_lag_seconds' ELSE '' END + '
  876. FROM sys.dm_hadr_database_replica_states'
  877. EXECUTE sp_executesql @sqlcmd
  878. SELECT 'Information' AS [Category], 'AlwaysOn_Replica_Cluster' AS [Information], replica_id, group_database_id, database_name, is_failover_ready, is_pending_secondary_suspend,
  879. is_database_joined, recovery_lsn, truncation_lsn
  880. FROM sys.dm_hadr_database_replica_cluster_states;
  881. END
  882. END;
  883. --------------------------------------------------------------------------------------------------------------------------------
  884. -- Linked servers info subsection
  885. --------------------------------------------------------------------------------------------------------------------------------
  886. RAISERROR (N'|-Starting Linked servers info', 10, 1) WITH NOWAIT
  887. 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
  888. BEGIN
  889. SET @sqlcmd = 'SELECT ''Information'' AS [Category], ''Linked_servers'' AS [Information], s.name, s.product,
  890. s.provider, s.data_source, s.location, s.provider_string, s.catalog, s.connect_timeout,
  891. s.query_timeout, s.is_linked, s.is_remote_login_enabled, s.is_rpc_out_enabled,
  892. s.is_data_access_enabled, s.is_collation_compatible, s.uses_remote_collation, s.collation_name,
  893. s.lazy_schema_validation, s.is_system, s.is_publisher, s.is_subscriber, s.is_distributor,
  894. s.is_nonsql_subscriber' + CASE WHEN @sqlmajorver > 9 THEN ', s.is_remote_proc_transaction_promotion_enabled' ELSE '' END + ',
  895. s.modify_date, CASE WHEN l.local_principal_id = 0 THEN ''local or wildcard'' ELSE p.name END AS [local_principal],
  896. CASE WHEN l.uses_self_credential = 0 THEN ''use own credentials'' ELSE ''use supplied username and pwd'' END AS uses_self_credential,
  897. l.remote_name, l.modify_date AS [linked_login_modify_date]
  898. FROM sys.servers AS s (NOLOCK)
  899. INNER JOIN sys.linked_logins AS l (NOLOCK) ON s.server_id = l.server_id
  900. INNER JOIN sys.server_principals AS p (NOLOCK) ON p.principal_id = l.local_principal_id
  901. WHERE s.is_linked = 1'
  902. EXECUTE sp_executesql @sqlcmd
  903. END
  904. ELSE
  905. BEGIN
  906. SELECT 'Information' AS [Category], 'Linked_servers' AS [Information], '[None]' AS [Status]
  907. END;
  908. --------------------------------------------------------------------------------------------------------------------------------
  909. -- Instance info subsection
  910. --------------------------------------------------------------------------------------------------------------------------------
  911. RAISERROR (N'|-Starting Instance info', 10, 1) WITH NOWAIT
  912. DECLARE @port VARCHAR(15), @replication int, @RegKey NVARCHAR(255), @cpuaffin VARCHAR(255), @cpucount int, @numa int
  913. DECLARE @i int, @cpuaffin_fixed VARCHAR(300)
  914. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild < 2500)
  915. BEGIN
  916. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  917. BEGIN
  918. BEGIN TRY
  919. SELECT @RegKey = CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) IS NULL THEN N'Software\Microsoft\MSSQLServer\MSSQLServer\SuperSocketNetLib\Tcp'
  920. ELSE N'Software\Microsoft\Microsoft SQL Server\' + CAST(SERVERPROPERTY('InstanceName') AS NVARCHAR(128)) + N'\MSSQLServer\SuperSocketNetLib\Tcp' END
  921. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'TcpPort', @port OUTPUT, NO_OUTPUT
  922. END TRY
  923. BEGIN CATCH
  924. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  925. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  926. RAISERROR (@ErrorMessage, 16, 1);
  927. END CATCH
  928. END
  929. ELSE
  930. BEGIN
  931. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing TCP port check]', 16, 1, N'sysadmin')
  932. --RETURN
  933. END
  934. END
  935. ELSE
  936. BEGIN
  937. BEGIN TRY
  938. SET @sqlcmd = N'SELECT @portOUT = MAX(CONVERT(VARCHAR(15),value_data)) FROM sys.dm_server_registry WHERE registry_key LIKE ''%MSSQLServer\SuperSocketNetLib\Tcp\%'' AND value_name LIKE N''%TcpPort%'' AND CONVERT(float,value_data) > 0;';
  939. SET @params = N'@portOUT VARCHAR(15) OUTPUT';
  940. EXECUTE sp_executesql @sqlcmd, @params, @portOUT = @port OUTPUT;
  941. IF @port IS NULL
  942. BEGIN
  943. SET @sqlcmd = N'SELECT @portOUT = CONVERT(VARCHAR(15),value_data) FROM sys.dm_server_registry WHERE registry_key LIKE ''%MSSQLServer\SuperSocketNetLib\Tcp\%'' AND value_name LIKE N''%TcpDynamicPort%'' AND CONVERT(float,value_data) > 0;';
  944. SET @params = N'@portOUT VARCHAR(15) OUTPUT';
  945. EXECUTE sp_executesql @sqlcmd, @params, @portOUT = @port OUTPUT;
  946. END
  947. END TRY
  948. BEGIN CATCH
  949. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  950. SELECT @ErrorMessage = 'Instance info subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  951. RAISERROR (@ErrorMessage, 16, 1);
  952. END CATCH
  953. END
  954. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 1)
  955. BEGIN
  956. BEGIN TRY
  957. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Replication', N'IsInstalled', @replication OUTPUT, NO_OUTPUT
  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 3. ' + ERROR_MESSAGE()
  962. RAISERROR (@ErrorMessage, 16, 1);
  963. END CATCH
  964. END
  965. ELSE
  966. BEGIN
  967. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing replication check]', 16, 1, N'sysadmin')
  968. --RETURN
  969. END
  970. SELECT @cpucount = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64
  971. SELECT @numa = COUNT(DISTINCT parent_node_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64;
  972. ;WITH bits AS
  973. (SELECT 7 AS N, 128 AS E UNION ALL SELECT 6, 64 UNION ALL
  974. SELECT 5, 32 UNION ALL SELECT 4, 16 UNION ALL SELECT 3, 8 UNION ALL
  975. SELECT 2, 4 UNION ALL SELECT 1, 2 UNION ALL SELECT 0, 1),
  976. bytes AS
  977. (SELECT 1 M UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
  978. SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL
  979. SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9)
  980. -- CPU Affinity is shown highest to lowest CPU ID
  981. SELECT @cpuaffin = CASE WHEN [value] = 0 THEN REPLICATE('1', @cpucount)
  982. ELSE RIGHT((SELECT ((CONVERT(tinyint, SUBSTRING(CONVERT(binary(9), [value]), M, 1)) & E) / E) AS [text()]
  983. FROM bits CROSS JOIN bytes
  984. ORDER BY M, N DESC
  985. FOR XML PATH('')), @cpucount) END
  986. FROM sys.configurations (NOLOCK)
  987. WHERE name = 'affinity mask';
  988. SET @cpuaffin_fixed = @cpuaffin
  989. IF @numa > 1
  990. BEGIN
  991. -- format binary mask by node for better reading
  992. SET @i = @cpucount/@numa + 1
  993. WHILE @i <= @cpucount
  994. BEGIN
  995. SELECT @cpuaffin_fixed = STUFF(@cpuaffin_fixed, @i, 1, '_' + SUBSTRING(@cpuaffin, @i, 1))
  996. SET @i = @i + @cpucount/@numa + 1
  997. END
  998. END
  999. SELECT 'Information' AS [Category], 'Instance' AS [Information],
  1000. (CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) IS NULL THEN 'DEFAULT_INSTANCE'
  1001. ELSE CONVERT(VARCHAR(128), SERVERPROPERTY('InstanceName')) END) AS Instance_Name,
  1002. (CASE WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'CLUSTERED'
  1003. WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'NOT_CLUSTERED'
  1004. ELSE 'INVALID INPUT/ERROR' END) AS Failover_Clustered,
  1005. /*The version of SQL Server instance in the form: major.minor.build*/
  1006. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductVersion')) AS Product_Version,
  1007. /*Level of the version of SQL Server Instance*/
  1008. 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
  1009. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductBuildType'))
  1010. ELSE 'NA' END AS Product_Build_Type,
  1011. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductLevel')) AS Product_Level,
  1012. 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
  1013. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductUpdateLevel'))
  1014. ELSE 'NA' END AS Product_Update_Level,
  1015. 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
  1016. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductUpdateReference'))
  1017. ELSE 'NA' END AS Product_Update_Ref_KB,
  1018. CONVERT(VARCHAR(128), SERVERPROPERTY('Edition')) AS Edition,
  1019. CONVERT(VARCHAR(128), SERVERPROPERTY('MachineName')) AS Machine_Name,
  1020. RTRIM(@port) AS TCP_Port,
  1021. @@SERVICENAME AS Service_Name,
  1022. /*To identify which sqlservr.exe belongs to this instance*/
  1023. SERVERPROPERTY('ProcessID') AS Process_ID,
  1024. CONVERT(VARCHAR(128), SERVERPROPERTY('ServerName')) AS Server_Name,
  1025. @cpuaffin_fixed AS Affinity_Mask_Bitmask,
  1026. CONVERT(VARCHAR(128), SERVERPROPERTY('Collation')) AS [Server_Collation],
  1027. (CASE WHEN @replication = 1 THEN 'Installed'
  1028. WHEN @replication = 0 THEN 'Not_Installed'
  1029. ELSE 'INVALID INPUT/ERROR' END) AS Replication_Components_Installation,
  1030. (CASE WHEN SERVERPROPERTY('IsFullTextInstalled') = 1 THEN 'Installed'
  1031. WHEN SERVERPROPERTY('IsFulltextInstalled') = 0 THEN 'Not_Installed'
  1032. ELSE 'INVALID INPUT/ERROR' END) AS Full_Text_Installation,
  1033. (CASE WHEN SERVERPROPERTY('IsIntegratedSecurityOnly') = 1 THEN 'Integrated_Security'
  1034. WHEN SERVERPROPERTY('IsIntegratedSecurityOnly') = 0 THEN 'SQL_Server_Security'
  1035. ELSE 'INVALID INPUT/ERROR' END) AS [Security],
  1036. (CASE WHEN SERVERPROPERTY('IsSingleUser') = 1 THEN 'Single_User'
  1037. WHEN SERVERPROPERTY('IsSingleUser') = 0 THEN 'Multi_User'
  1038. ELSE 'INVALID INPUT/ERROR' END) AS [Single_User],
  1039. (CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('LicenseType')) = 'PER_SEAT' THEN 'Per_Seat_Mode'
  1040. WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('LicenseType')) = 'PER_PROCESSOR' THEN 'Per_Processor_Mode'
  1041. ELSE 'Disabled' END) AS License_Type, -- From SQL Server 2008R2 always returns DISABLED.
  1042. CONVERT(NVARCHAR(128), SERVERPROPERTY('BuildClrVersion')) AS CLR_Version,
  1043. CASE WHEN @sqlmajorver >= 10 THEN
  1044. CASE WHEN SERVERPROPERTY('FilestreamConfiguredLevel') = 0 THEN 'Disabled'
  1045. WHEN SERVERPROPERTY('FilestreamConfiguredLevel') = 1 THEN 'Enabled_for_TSQL'
  1046. ELSE 'Enabled for TSQL and Win32' END
  1047. ELSE 'Not compatible' END AS Filestream_Configured_Level,
  1048. CASE WHEN @sqlmajorver >= 10 THEN
  1049. CASE WHEN SERVERPROPERTY('FilestreamEffectiveLevel') = 0 THEN 'Disabled'
  1050. WHEN SERVERPROPERTY('FilestreamEffectiveLevel') = 1 THEN 'Enabled_for_TSQL'
  1051. ELSE 'Enabled for TSQL and Win32' END
  1052. ELSE 'Not compatible' END AS Filestream_Effective_Level,
  1053. CASE WHEN @sqlmajorver >= 10 THEN
  1054. SERVERPROPERTY('FilestreamShareName')
  1055. ELSE 'Not compatible' END AS Filestream_Share_Name,
  1056. CASE WHEN @sqlmajorver >= 12 THEN
  1057. SERVERPROPERTY('IsXTPSupported')
  1058. ELSE 'Not compatible' END AS XTP_Compatible,
  1059. CASE WHEN @sqlmajorver >= 13 THEN
  1060. SERVERPROPERTY('IsPolybaseInstalled')
  1061. ELSE 'Not compatible' END AS Polybase_Installed,
  1062. CASE WHEN @sqlmajorver >= 13 THEN
  1063. SERVERPROPERTY('IsAdvancedAnalyticsInstalled')
  1064. ELSE 'Not compatible' END AS R_Services_Installed;
  1065. --------------------------------------------------------------------------------------------------------------------------------
  1066. -- Buffer Pool Extension info subsection
  1067. --------------------------------------------------------------------------------------------------------------------------------
  1068. RAISERROR (N'|-Starting Buffer Pool Extension info', 10, 1) WITH NOWAIT
  1069. IF @sqlmajorver > 11
  1070. BEGIN
  1071. SELECT 'Information' AS [Category], 'BP_Extension' AS [Information],
  1072. CASE WHEN state = 0 THEN 'BP_Extension_Disabled'
  1073. WHEN state = 1 THEN 'BP_Extension_is_Disabling'
  1074. WHEN state = 3 THEN 'BP_Extension_is_Enabling'
  1075. WHEN state = 5 THEN 'BP_Extension_Enabled'
  1076. END AS state,
  1077. [path], current_size_in_kb
  1078. FROM sys.dm_os_buffer_pool_extension_configuration
  1079. END
  1080. ELSE
  1081. BEGIN
  1082. SELECT 'Information' AS [Category], 'BP_Extension' AS [Information], '[NA]' AS state
  1083. END;
  1084. --------------------------------------------------------------------------------------------------------------------------------
  1085. -- Resource Governor info subsection
  1086. --------------------------------------------------------------------------------------------------------------------------------
  1087. RAISERROR (N'|-Starting Resource Governor info', 10, 1) WITH NOWAIT
  1088. IF @sqlmajorver > 9
  1089. BEGIN
  1090. 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
  1091. FROM sys.dm_resource_governor_configuration
  1092. 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,
  1093. 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,
  1094. 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 + '
  1095. 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
  1096. EXECUTE sp_executesql @sqlcmd
  1097. 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,
  1098. 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,
  1099. total_lock_wait_time_ms, total_query_optimization_count, total_suboptimal_plan_generation_count, total_reduced_memgrant_count, max_request_grant_memory_kb,
  1100. active_parallel_thread_count, importance, request_max_memory_grant_percent, request_max_cpu_time_sec, request_memory_grant_timeout_sec,
  1101. group_max_requests, max_dop' + CASE WHEN @sqlmajorver > 10 THEN ', effective_max_dop' ELSE '' END + '
  1102. FROM sys.dm_resource_governor_workload_groups'
  1103. EXECUTE sp_executesql @sqlcmd
  1104. END;
  1105. --------------------------------------------------------------------------------------------------------------------------------
  1106. -- Logon triggers subsection
  1107. --------------------------------------------------------------------------------------------------------------------------------
  1108. RAISERROR (N'|-Starting Logon triggers', 10, 1) WITH NOWAIT
  1109. IF (SELECT COUNT([name]) FROM sys.server_triggers WHERE is_disabled = 0 AND is_ms_shipped = 0) > 0
  1110. BEGIN
  1111. SELECT 'Information' AS [Category], 'Logon_Triggers' AS [Information], name AS [Trigger_Name], type_desc AS [Trigger_Type],create_date, modify_date
  1112. FROM sys.server_triggers WHERE is_disabled = 0 AND is_ms_shipped = 0
  1113. ORDER BY name;
  1114. END
  1115. ELSE
  1116. BEGIN
  1117. SELECT 'Information' AS [Category], 'Logon_Triggers' AS [Information], '[NA]' AS [Comment]
  1118. END;
  1119. --------------------------------------------------------------------------------------------------------------------------------
  1120. -- Database Information subsection
  1121. --------------------------------------------------------------------------------------------------------------------------------
  1122. RAISERROR (N'|-Starting Database Information', 10, 1) WITH NOWAIT
  1123. RAISERROR (N' |-Building DB list', 10, 1) WITH NOWAIT
  1124. DECLARE @curdbname VARCHAR(1000), @curdbid int, @currole tinyint, @cursecondary_role_allow_connections tinyint, @state tinyint
  1125. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  1126. DROP TABLE #tmpdbs0;
  1127. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  1128. 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);
  1129. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  1130. DROP TABLE #tmpdbfiledetail;
  1131. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  1132. 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)
  1133. IF @sqlmajorver < 11
  1134. BEGIN
  1135. INSERT INTO #tmpdbs0 ([dbid], [dbname], [compatibility_level], is_read_only, [state], is_distributor, [role], [secondary_role_allow_connections], [isdone])
  1136. SELECT database_id, name, [compatibility_level], is_read_only, [state], is_distributor, 1, 1, 0 FROM master.sys.databases (NOLOCK)
  1137. END;
  1138. IF @sqlmajorver > 10
  1139. BEGIN
  1140. 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])
  1141. 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
  1142. FROM master.sys.databases sd (NOLOCK)
  1143. LEFT JOIN sys.dm_hadr_database_replica_states d ON sd.database_id = d.database_id
  1144. LEFT JOIN sys.availability_replicas ar ON d.group_id = ar.group_id AND d.replica_id = ar.replica_id
  1145. LEFT JOIN sys.dm_hadr_availability_replica_states ars ON d.group_id = ars.group_id AND d.replica_id = ars.replica_id
  1146. LEFT JOIN sys.dm_hadr_database_replica_cluster_states rcs ON rcs.database_name = sd.name AND rcs.replica_id = ar.replica_id
  1147. 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;
  1148. END;
  1149. /* Validate if database scope is set */
  1150. IF @dbScope IS NOT NULL AND ISNUMERIC(@dbScope) <> 1 AND @dbScope NOT LIKE '%,%'
  1151. BEGIN
  1152. 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;
  1153. RETURN
  1154. END;
  1155. RAISERROR (N' |-Applying specific database scope list, if any', 10, 1) WITH NOWAIT
  1156. IF @dbScope IS NOT NULL
  1157. BEGIN
  1158. SELECT @sqlcmd = 'DELETE FROM #tmpdbs0 WHERE [dbid] > 4 AND [dbid] NOT IN (' + REPLACE(@dbScope,' ','') + ')'
  1159. EXEC sp_executesql @sqlcmd;
  1160. END;
  1161. IF @sqlmajorver < 11
  1162. BEGIN
  1163. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1164. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1165. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1166. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1167. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1168. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1169. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
  1170. db.is_auto_update_stats_async_on, db.is_parameterization_forced,
  1171. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1172. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on, ''NA'' AS [is_indirect_checkpoint_on],
  1173. db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1174. FROM master.sys.databases AS db (NOLOCK)
  1175. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1176. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1177. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1178. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1179. 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 + '
  1180. ORDER BY [Database_Name]
  1181. OPTION (RECOMPILE)'
  1182. END
  1183. ELSE IF @sqlmajorver = 11
  1184. BEGIN
  1185. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1186. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1187. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1188. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1189. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1190. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1191. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
  1192. db.is_auto_update_stats_async_on, db.is_parameterization_forced,
  1193. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1194. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1195. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1196. db.target_recovery_time_in_seconds, db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1197. FROM master.sys.databases AS db (NOLOCK)
  1198. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1199. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1200. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1201. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1202. 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 + '
  1203. ORDER BY [Database_Name]
  1204. OPTION (RECOMPILE)'
  1205. END
  1206. ELSE IF @sqlmajorver = 12
  1207. BEGIN
  1208. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1209. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1210. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1211. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1212. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1213. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1214. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_create_stats_incremental_on,
  1215. db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.delayed_durability_desc AS [delayed_durability_status],
  1216. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1217. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1218. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1219. db.target_recovery_time_in_seconds, db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced
  1220. FROM master.sys.databases AS db (NOLOCK)
  1221. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1222. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1223. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1224. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1225. 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 + '
  1226. ORDER BY [Database_Name]
  1227. OPTION (RECOMPILE)'
  1228. END
  1229. ELSE IF @sqlmajorver >= 13
  1230. BEGIN
  1231. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Databases'' AS [Information],
  1232. db.[name] AS [Database_Name], SUSER_SNAME(db.owner_sid) AS [Owner_Name], db.[database_id],
  1233. db.recovery_model_desc AS [Recovery_Model], db.create_date, db.log_reuse_wait_desc AS [Log_Reuse_Wait_Description],
  1234. ls.cntr_value AS [Log_Size_KB], lu.cntr_value AS [Log_Used_KB],
  1235. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log_Used_pct],
  1236. db.[compatibility_level] AS [DB_Compatibility_Level], db.collation_name AS [DB_Collation],
  1237. db.page_verify_option_desc AS [Page_Verify_Option], db.is_auto_create_stats_on, db.is_auto_create_stats_incremental_on,
  1238. db.is_auto_update_stats_on, db.is_auto_update_stats_async_on, db.delayed_durability_desc AS [delayed_durability_status],
  1239. db.is_query_store_on, db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  1240. db.is_read_only, db.is_auto_close_on, db.is_auto_shrink_on,
  1241. CASE WHEN db.target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  1242. db.target_recovery_time_in_seconds, db.is_encrypted, db.is_trustworthy_on, db.is_db_chaining_on, db.is_parameterization_forced,
  1243. db.is_memory_optimized_elevate_to_snapshot_on, db.is_remote_data_archive_enabled, db.is_mixed_page_allocation_on
  1244. FROM master.sys.databases AS db (NOLOCK)
  1245. INNER JOIN sys.dm_os_performance_counters AS lu (NOLOCK) ON db.name = lu.instance_name
  1246. INNER JOIN sys.dm_os_performance_counters AS ls (NOLOCK) ON db.name = ls.instance_name
  1247. WHERE lu.counter_name LIKE N''Log File(s) Used Size (KB)%''
  1248. AND ls.counter_name LIKE N''Log File(s) Size (KB)%''
  1249. 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 + '
  1250. ORDER BY [Database_Name]
  1251. OPTION (RECOMPILE)'
  1252. END
  1253. EXECUTE sp_executesql @sqlcmd;
  1254. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1255. BEGIN
  1256. SELECT TOP 1 @curdbname = [dbname], @curdbid = [dbid], @currole = [role], @state = [state], @cursecondary_role_allow_connections = secondary_role_allow_connections FROM #tmpdbs0 WHERE isdone = 0
  1257. IF (@currole = 2 AND @cursecondary_role_allow_connections = 0) OR @state <> 0
  1258. BEGIN
  1259. 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
  1260. FROM sys.master_files (NOLOCK) WHERE [database_id] = ' + CONVERT(VARCHAR(10), @curdbid)
  1261. END
  1262. ELSE
  1263. BEGIN
  1264. SET @sqlcmd = 'USE ' + QUOTENAME(@curdbname) + ';
  1265. 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
  1266. FROM sys.database_files (NOLOCK)'
  1267. END
  1268. BEGIN TRY
  1269. INSERT INTO #tmpdbfiledetail
  1270. EXECUTE sp_executesql @sqlcmd
  1271. END TRY
  1272. BEGIN CATCH
  1273. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1274. SELECT @ErrorMessage = 'Database Information subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1275. RAISERROR (@ErrorMessage, 16, 1);
  1276. END CATCH
  1277. UPDATE #tmpdbs0
  1278. SET isdone = 1
  1279. WHERE [dbid] = @curdbid
  1280. END;
  1281. 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,
  1282. 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,
  1283. 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,
  1284. is_media_read_only, is_read_only, is_sparse, is_name_reserved
  1285. FROM #tmpdbfiledetail
  1286. ORDER BY database_id, [file_id];
  1287. IF @sqlmajorver >= 12
  1288. BEGIN
  1289. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1290. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  1291. DROP TABLE #tblInMemDBs;
  1292. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  1293. CREATE TABLE #tblInMemDBs ([DBName] sysname, [Has_MemoryOptimizedObjects] bit, [MemoryAllocated_MemoryOptimizedObjects_KB] DECIMAL(18,2), [MemoryUsed_MemoryOptimizedObjects_KB] DECIMAL(18,2));
  1294. UPDATE #tmpdbs0
  1295. SET isdone = 0;
  1296. UPDATE #tmpdbs0
  1297. SET isdone = 1
  1298. WHERE [state] <> 0 OR [dbid] < 5;
  1299. UPDATE #tmpdbs0
  1300. SET isdone = 1
  1301. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1302. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1303. BEGIN
  1304. RAISERROR (N' |-Starting Storage analysis for In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  1305. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1306. BEGIN
  1307. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1308. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1309. SELECT ''' + @dbname + ''' AS [DBName], ISNULL((SELECT 1 FROM sys.filegroups FG WHERE FG.[type] = ''FX''), 0) AS [Has_MemoryOptimizedObjects],
  1310. 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],
  1311. 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];'
  1312. BEGIN TRY
  1313. INSERT INTO #tblInMemDBs
  1314. EXECUTE sp_executesql @sqlcmd
  1315. END TRY
  1316. BEGIN CATCH
  1317. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1318. SELECT @ErrorMessage = 'Storage analysis for In-Memory OLTP Engine subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1319. RAISERROR (@ErrorMessage, 16, 1);
  1320. END CATCH
  1321. UPDATE #tmpdbs0
  1322. SET isdone = 1
  1323. WHERE [dbid] = @dbid
  1324. END
  1325. END;
  1326. IF (SELECT COUNT([DBName]) FROM #tblInMemDBs WHERE [Has_MemoryOptimizedObjects] = 1) > 0
  1327. BEGIN
  1328. SELECT 'Information' AS [Category], 'InMem_Database_Storage' AS [Information], DBName AS [Database_Name],
  1329. [MemoryAllocated_MemoryOptimizedObjects_KB], [MemoryUsed_MemoryOptimizedObjects_KB]
  1330. FROM #tblInMemDBs WHERE Has_MemoryOptimizedObjects = 1
  1331. ORDER BY DBName;
  1332. END
  1333. ELSE
  1334. BEGIN
  1335. SELECT 'Information' AS [Category], 'InMem_Database_Storage' AS [Information], '[NA]' AS [Comment]
  1336. END
  1337. END;
  1338. -- http://support.microsoft.com/kb/2857849
  1339. IF @sqlmajorver > 10 AND @IsHadrEnabled = 1
  1340. BEGIN
  1341. SELECT 'Information' AS [Category], 'AlwaysOn_AG_Databases' AS [Information], dc.database_name AS [Database_Name],
  1342. d.synchronization_health_desc, d.synchronization_state_desc, d.database_state_desc
  1343. FROM sys.dm_hadr_database_replica_states d
  1344. INNER JOIN sys.availability_databases_cluster dc ON d.group_database_id=dc.group_database_id
  1345. WHERE d.is_local=1
  1346. END;
  1347. --------------------------------------------------------------------------------------------------------------------------------
  1348. -- Database file autogrows last 72h subsection
  1349. --------------------------------------------------------------------------------------------------------------------------------
  1350. RAISERROR (N' |-Starting database file autogrows last 72h', 10, 1) WITH NOWAIT
  1351. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE is_default = 1)
  1352. BEGIN
  1353. DECLARE @tracefilename VARCHAR(500)
  1354. SELECT @tracefilename = LEFT([path],LEN([path]) - PATINDEX('%\%', REVERSE([path]))) + '\log.trc' FROM sys.traces WHERE is_default = 1;
  1355. WITH AutoGrow_CTE (databaseid, [filename], Growth, Duration, StartTime, EndTime)
  1356. AS
  1357. (
  1358. SELECT databaseid, [filename], SUM(IntegerData*8) AS Growth, Duration, StartTime, EndTime--, CASE WHEN EventClass =
  1359. FROM ::fn_trace_gettable(@tracefilename, default)
  1360. WHERE EventClass >= 92 AND EventClass <= 95 AND DATEDIFF(hh,StartTime,GETDATE()) < 72 -- Last 24h
  1361. GROUP BY databaseid, [filename], IntegerData, Duration, StartTime, EndTime
  1362. )
  1363. SELECT 'Information' AS [Category], 'Recorded_Autogrows_Lst72H' AS [Information], DB_NAME(database_id) AS Database_Name,
  1364. mf.name AS logical_file_name, mf.size*8 / 1024 AS size_MB, mf.type_desc,
  1365. ag.Growth AS [growth_KB], CASE WHEN is_percent_growth = 1 THEN 'Pct' ELSE 'MB' END AS growth_type,
  1366. Duration/1000 AS Growth_Duration_ms, ag.StartTime, ag.EndTime
  1367. FROM sys.master_files mf
  1368. LEFT OUTER JOIN AutoGrow_CTE ag ON mf.database_id=ag.databaseid AND mf.name=ag.[filename]
  1369. WHERE ag.Growth > 0 --Only where growth occurred
  1370. GROUP BY database_id, mf.name, mf.size, ag.Growth, ag.Duration, ag.StartTime, ag.EndTime, is_percent_growth, mf.growth, mf.type_desc
  1371. ORDER BY Database_Name, logical_file_name, ag.StartTime;
  1372. END
  1373. ELSE
  1374. BEGIN
  1375. SELECT 'Information' AS [Category], 'Recorded_Autogrows_Lst72H' AS [Information], '[WARNING: Could not gather information on autogrow times]' AS [Comment]
  1376. END;
  1377. --------------------------------------------------------------------------------------------------------------------------------
  1378. -- Database triggers subsection
  1379. --------------------------------------------------------------------------------------------------------------------------------
  1380. IF @ptochecks = 1
  1381. BEGIN
  1382. RAISERROR (N' |-Starting database triggers', 10, 1) WITH NOWAIT
  1383. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1384. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  1385. DROP TABLE #tblTriggers;
  1386. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  1387. 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);
  1388. UPDATE #tmpdbs0
  1389. SET isdone = 0;
  1390. UPDATE #tmpdbs0
  1391. SET isdone = 1
  1392. WHERE [state] <> 0 OR [dbid] < 5;
  1393. UPDATE #tmpdbs0
  1394. SET isdone = 1
  1395. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1396. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1397. BEGIN
  1398. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1399. BEGIN
  1400. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1401. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1402. 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
  1403. FROM sys.triggers AS st
  1404. INNER JOIN sys.tables stb ON st.parent_id = stb.[object_id]
  1405. INNER JOIN sys.schemas ss ON stb.[schema_id] = ss.[schema_id]
  1406. WHERE st.is_ms_shipped = 0
  1407. ORDER BY stb.name, st.name;'
  1408. BEGIN TRY
  1409. INSERT INTO #tblTriggers
  1410. EXECUTE sp_executesql @sqlcmd
  1411. END TRY
  1412. BEGIN CATCH
  1413. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1414. SELECT @ErrorMessage = 'Database triggers subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1415. RAISERROR (@ErrorMessage, 16, 1);
  1416. END CATCH
  1417. UPDATE #tmpdbs0
  1418. SET isdone = 1
  1419. WHERE [dbid] = @dbid
  1420. END
  1421. END;
  1422. IF (SELECT COUNT([triggerName]) FROM #tblTriggers) > 0
  1423. BEGIN
  1424. SELECT 'Information' AS [Category], 'Database_Triggers' AS [Information], DBName AS [Database_Name],
  1425. triggerName AS [Trigger_Name], schemaName AS [Schema_Name], tableName AS [Table_Name],
  1426. type_desc AS [Trigger_Type], parent_class_desc AS [Trigger_Parent],
  1427. CASE is_instead_of_trigger WHEN 1 THEN 'INSTEAD_OF' ELSE 'AFTER' END AS [Trigger_Behavior],
  1428. create_date, modify_date,
  1429. CASE WHEN is_disabled = 1 THEN 'YES' ELSE 'NO' END AS [is_disabled],
  1430. CASE WHEN is_not_for_replication = 1 THEN 'YES' ELSE 'NO' END AS [is_not_for_replication]
  1431. FROM #tblTriggers
  1432. ORDER BY DBName, tableName, triggerName;
  1433. END
  1434. ELSE
  1435. BEGIN
  1436. SELECT 'Information' AS [Category], 'Database_Triggers' AS [Information], '[NA]' AS [Comment]
  1437. END
  1438. END;
  1439. --------------------------------------------------------------------------------------------------------------------------------
  1440. -- Enterprise features usage subsection
  1441. --------------------------------------------------------------------------------------------------------------------------------
  1442. IF @sqlmajorver > 9
  1443. BEGIN
  1444. RAISERROR (N'|-Starting Enterprise features usage', 10, 1) WITH NOWAIT
  1445. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  1446. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  1447. DROP TABLE #tblPerSku;
  1448. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  1449. CREATE TABLE #tblPerSku ([DBName] sysname NULL, [Feature_Name] VARCHAR(100));
  1450. UPDATE #tmpdbs0
  1451. SET isdone = 0;
  1452. UPDATE #tmpdbs0
  1453. SET isdone = 1
  1454. WHERE [state] <> 0 OR [dbid] < 5;
  1455. UPDATE #tmpdbs0
  1456. SET isdone = 1
  1457. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  1458. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1459. BEGIN
  1460. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  1461. BEGIN
  1462. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  1463. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1464. SELECT ''' + @dbname + ''' AS [DBName], feature_name FROM sys.dm_db_persisted_sku_features (NOLOCK);'
  1465. BEGIN TRY
  1466. INSERT INTO #tblPerSku
  1467. EXECUTE sp_executesql @sqlcmd
  1468. END TRY
  1469. BEGIN CATCH
  1470. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1471. SELECT @ErrorMessage = 'Enterprise features usage subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1472. RAISERROR (@ErrorMessage, 16, 1);
  1473. END CATCH
  1474. UPDATE #tmpdbs0
  1475. SET isdone = 1
  1476. WHERE [dbid] = @dbid
  1477. END
  1478. END;
  1479. IF @sqlmajorver > 10 AND ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13) AND @IsHadrEnabled = 1
  1480. BEGIN
  1481. INSERT INTO #tblPerSku
  1482. SELECT NULL, 'Always_On' AS feature_name
  1483. END;
  1484. 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
  1485. BEGIN
  1486. INSERT INTO #tblPerSku
  1487. 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
  1488. END;
  1489. IF (@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13
  1490. BEGIN
  1491. DELETE FROM #tblPerSku
  1492. WHERE Feature_Name IN ('ColumnStoreIndex','InMemoryOLTP')
  1493. END;
  1494. IF (SELECT COUNT([Feature_Name]) FROM #tblPerSku) > 0
  1495. BEGIN
  1496. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Check], '[INFORMATION: Some databases are using Enterprise only features]' AS [Comment]
  1497. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Information], DBName AS [Database_Name], [Feature_Name]
  1498. FROM #tblPerSku
  1499. ORDER BY 2, 3
  1500. END
  1501. ELSE
  1502. BEGIN
  1503. SELECT 'Information' AS [Category], 'Enterprise_features_usage' AS [Check], '[NA]' AS [Comment]
  1504. END
  1505. END;
  1506. --------------------------------------------------------------------------------------------------------------------------------
  1507. -- Backups since last Full Information subsection
  1508. --------------------------------------------------------------------------------------------------------------------------------
  1509. RAISERROR (N'|-Starting Backups', 10, 1) WITH NOWAIT
  1510. IF @sqlmajorver > 10
  1511. BEGIN
  1512. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Backups_since_last_Full'' AS [Information],
  1513. [database_name] AS [Database_Name], CASE WHEN type = ''D'' THEN ''Database''
  1514. WHEN type = ''I'' THEN ''Diff_Database''
  1515. WHEN type = ''L'' THEN ''Log''
  1516. WHEN type = ''F'' THEN ''File''
  1517. WHEN type = ''G'' THEN ''Diff_file''
  1518. WHEN type = ''P'' THEN ''Partial''
  1519. WHEN type = ''Q'' THEN ''Diff_partial''
  1520. ELSE NULL END AS [bck_type],
  1521. [backup_start_date], [backup_finish_date],
  1522. CONVERT(decimal(20,2),backup_size/1024.00/1024.00) AS [backup_size_MB],
  1523. CONVERT(decimal(20,2),compressed_backup_size/1024.00/1024.00) AS [compressed_backup_size_MB],
  1524. [recovery_model], [user_name],
  1525. database_backup_lsn AS [full_base_lsn], [differential_base_lsn], [expiration_date],
  1526. [is_password_protected], [has_backup_checksums], [is_readonly], is_copy_only, [has_incomplete_metadata] AS [Tail_log]
  1527. FROM msdb.dbo.backupset bck1 (NOLOCK)
  1528. WHERE is_copy_only = 0 -- No COPY_ONLY backups
  1529. 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)
  1530. ORDER BY database_name, backup_start_date DESC'
  1531. END
  1532. ELSE
  1533. BEGIN
  1534. SET @sqlcmd = N'SELECT ''Information'' AS [Category], ''Backups_since_last_Full'' AS [Information],
  1535. [database_name] AS [Database_Name], CASE WHEN type = ''D'' THEN ''Database''
  1536. WHEN type = ''I'' THEN ''Diff_Database''
  1537. WHEN type = ''L'' THEN ''Log''
  1538. WHEN type = ''F'' THEN ''File''
  1539. WHEN type = ''G'' THEN ''Diff_file''
  1540. WHEN type = ''P'' THEN ''Partial''
  1541. WHEN type = ''Q'' THEN ''Diff_partial''
  1542. ELSE NULL END AS [bck_type],
  1543. [backup_start_date], [backup_finish_date],
  1544. CONVERT(decimal(20,2),backup_size/1024.00/1024.00) AS [backup_size_MB],
  1545. ''[NA]'' AS [compressed_backup_size_MB],
  1546. [recovery_model], [user_name],
  1547. database_backup_lsn AS [full_base_lsn], [differential_base_lsn], [expiration_date],
  1548. [is_password_protected], [has_backup_checksums], [is_readonly], is_copy_only, [has_incomplete_metadata] AS [Tail_log]
  1549. FROM msdb.dbo.backupset bck1 (NOLOCK)
  1550. WHERE is_copy_only = 0 -- No COPY_ONLY backups
  1551. 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)
  1552. ORDER BY database_name, backup_start_date DESC'
  1553. END;
  1554. EXECUTE sp_executesql @sqlcmd;
  1555. --------------------------------------------------------------------------------------------------------------------------------
  1556. -- System Configuration subsection
  1557. --------------------------------------------------------------------------------------------------------------------------------
  1558. RAISERROR (N'|-Starting System Configuration', 10, 1) WITH NOWAIT
  1559. SELECT 'Information' AS [Category], 'All_System_Configurations' AS [Information],
  1560. name AS [Name],
  1561. configuration_id AS [Number],
  1562. minimum AS [Minimum],
  1563. maximum AS [Maximum],
  1564. is_dynamic AS [Dynamic],
  1565. is_advanced AS [Advanced],
  1566. value AS [ConfigValue],
  1567. value_in_use AS [RunValue],
  1568. description AS [Description]
  1569. FROM sys.configurations (NOLOCK)
  1570. ORDER BY name OPTION (RECOMPILE);
  1571. --------------------------------------------------------------------------------------------------------------------------------
  1572. -- Pre-checks section
  1573. --------------------------------------------------------------------------------------------------------------------------------
  1574. RAISERROR (N'Starting Pre-Checks - Building DB list excluding MS shipped', 10, 1) WITH NOWAIT
  1575. DECLARE @MSdb int
  1576. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  1577. DROP TABLE #tmpdbs1;
  1578. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  1579. CREATE TABLE #tmpdbs1 (id int IDENTITY(1,1), [dbid] int, [dbname] VARCHAR(1000), [role] tinyint, [secondary_role_allow_connections] tinyint, isdone bit)
  1580. RAISERROR (N'|-Excluding MS shipped by standard names and databases belonging to non-readable AG secondary replicas (if available)', 10, 1) WITH NOWAIT
  1581. -- Ignore MS shipped databases and databases belonging to non-readable AG secondary replicas
  1582. INSERT INTO #tmpdbs1 ([dbid], [dbname], [role], [secondary_role_allow_connections], [isdone])
  1583. SELECT [dbid], [dbname], [role], [secondary_role_allow_connections], 0
  1584. FROM #tmpdbs0 (NOLOCK)
  1585. WHERE is_read_only = 0 AND [state] = 0 AND [dbid] > 4 AND is_distributor = 0
  1586. AND [role] <> 2 AND (secondary_role_allow_connections <> 0 OR secondary_role_allow_connections IS NULL)
  1587. AND lower([dbname]) NOT IN ('virtualmanagerdb', --Virtual Machine Manager
  1588. 'scspfdb', --Service Provider Foundation
  1589. 'semanticsdb', --Semantic Search
  1590. 'servicemanager','service manager','dwstagingandconfig','dwrepository','dwdatamart','dwasdatabase','omdwdatamart','cmdwdatamart', --SCSM
  1591. 'ssodb','bamanalysis','bamarchive','bamalertsapplication','bamalertsnsmain','bamprimaryimport','bamstarschema','biztalkmgmtdb','biztalkmsgboxdb','biztalkdtadb','biztalkruleenginedb','bamprimaryimport','biztalkedidb','biztalkhwsdb','tpm','biztalkanalysisdb','bamprimaryimportsuccessfully', --BizTalk
  1592. 'aspstate','aspnet', --ASP.NET
  1593. 'mscrm_config', --Dynamics CRM
  1594. 'cpsdyn','lcslog','lcscdr','lis','lyss','mgc','qoemetrics','rgsconfig','rgsdyn','rtc','rtcab','rtcab1','rtcdyn','rtcshared','rtcxds','xds', --Lync
  1595. 'activitylog','branchdb','clienttracelog','eventlog','listingssettings','servicegroupdb','tservercontroller','vodbackend', --MediaRoom
  1596. 'operationsmanager','operationsmanagerdw','operationsmanagerac', --SCOM
  1597. 'orchestrator', --Orchestrator
  1598. 'sso','wss_search','wss_search_config','sharedservices_db','sharedservices_search_db','wss_content','profiledb', 'social db','sync db', --Sharepoint
  1599. 'susdb', --WSUS
  1600. 'projectserver_archive','projectserver_draft','projectserver_published','projectserver_reporting', --Project Server
  1601. 'reportserver','reportservertempdb','rsdb','rstempdb', --SSRS
  1602. 'fastsearchadmindatabase', --Fast Search
  1603. 'ppsmonitoring','ppsplanningservice','ppsplanningsystem', --PerformancePoint Services
  1604. 'dynamics', --Dynamics GP
  1605. 'microsoftdynamicsax','microsoftdynamicsaxbaseline', --Dynamics AX
  1606. 'fimservice','fimsynchronizationservice', --Forefront Identity Manager
  1607. 'sbgatewaydatabase','sbmanagementdb', --Service Bus
  1608. 'wfinstancemanagementdb','wfmanagementdb','wfresourcemanagementdb' --Workflow Manager
  1609. )
  1610. AND [dbname] NOT LIKE 'repANDtingservice[_]%' --SSRS
  1611. AND [dbname] NOT LIKE 'tfs[_]%' --TFS
  1612. AND [dbname] NOT LIKE 'defaultpowerpivotserviceapplicationdb%' --PowerPivot
  1613. AND [dbname] NOT LIKE 'perfANDmancepoint service[_]%' --PerfANDmancePoint Services
  1614. AND [dbname] NOT LIKE '%database nav%' --Dynamics NAV
  1615. AND [dbname] NOT LIKE '%[_]mscrm' --Dynamics CRM
  1616. AND [dbname] NOT LIKE 'dpmdb[_]%' --DPM
  1617. AND [dbname] NOT LIKE 'sbmessagecontainer%' --Service Bus
  1618. AND [dbname] NOT LIKE 'sma%' --SCSMA
  1619. AND [dbname] NOT LIKE 'releasemanagement%' --TFS Release Management
  1620. AND [dbname] NOT LIKE 'projectwebapp%' --Project Server
  1621. AND [dbname] NOT LIKE 'sms[_]%' AND [dbname] NOT LIKE 'cm[_]%' --SCCM
  1622. AND [dbname] NOT LIKE 'fepdw%' AND [dbname] NOT LIKE 'FEPDB[_]%' --Forefront Endpoint Protection
  1623. --Sharepoint
  1624. AND [dbname] NOT LIKE 'sharepoint[_]admincontent%' AND [dbname] NOT LIKE 'sharepoint[_]config%' AND [dbname] NOT LIKE 'wss[_]content%' AND [dbname] NOT LIKE 'wss[_]search%'
  1625. 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%'
  1626. AND [dbname] NOT LIKE 'sharedservicescontent%' AND [dbname] NOT LIKE 'application[_]registry[_]service[_]db%' AND [dbname] NOT LIKE 'search[_]service[_]application[_]propertystANDedb[_]%'
  1627. AND [dbname] NOT LIKE 'subscriptionsettings[_]%' AND [dbname] NOT LIKE 'webanalyticsserviceapplication[_]stagingdb[_]%' AND [dbname] NOT LIKE 'webanalyticsserviceapplication[_]repANDtingdb[_]%'
  1628. AND [dbname] NOT LIKE 'bdc[_]service[_]db[_]%' AND [dbname] NOT LIKE 'managed metadata service[_]%' AND [dbname] NOT LIKE 'perfANDmancepoint service application[_]%'
  1629. 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%'
  1630. 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[_]%'
  1631. AND [dbname] NOT LIKE 'wANDdautomationservices[_]%' AND [dbname] NOT LIKE 'wss[_]logging%' AND [dbname] NOT LIKE 'wss[_]usageapplication%' AND [dbname] NOT LIKE 'appmng[_]service[_]db%'
  1632. AND [dbname] NOT LIKE 'search[_]service[_]application[_]analyticsrepANDtingstANDedb[_]%' AND [dbname] NOT LIKE 'search[_]service[_]application[_]linksstANDedb[_]%' AND [dbname] NOT LIKE 'sharepoint[_]logging[_]%'
  1633. 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%'
  1634. IF EXISTS (SELECT name FROM msdb.sys.objects (NOLOCK) WHERE name='MSdistributiondbs' AND is_ms_shipped = 1)
  1635. BEGIN
  1636. DELETE FROM #tmpdbs1 WHERE [dbid] IN (SELECT DB_ID(name) FROM msdb.dbo.MSdistributiondbs)
  1637. END;
  1638. RAISERROR (N'|-Excluding MS shipped by notable object names', 10, 1) WITH NOWAIT
  1639. -- Removing other noticeable MS shipped DBs
  1640. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  1641. BEGIN
  1642. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  1643. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  1644. 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)
  1645. OR (OBJECT_ID(''dbo.Versions'',''U'') IS NOT NULL
  1646. 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)
  1647. 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)
  1648. 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)
  1649. 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)
  1650. 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)
  1651. 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)
  1652. 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)
  1653. 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)
  1654. 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)
  1655. 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)
  1656. 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)
  1657. 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)
  1658. )
  1659. 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)
  1660. 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)
  1661. 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)
  1662. 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)
  1663. -- End Sharepoint
  1664. 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)
  1665. 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)
  1666. -- End ASP.NET
  1667. 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)
  1668. -- End PowerPivot
  1669. 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)
  1670. -- End Orchestrator
  1671. 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)
  1672. -- End VMM
  1673. 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)
  1674. -- End Service Provider Foundation
  1675. 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)
  1676. 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))
  1677. -- End BizTalk
  1678. 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)
  1679. -- End Dynamics AX
  1680. OR (OBJECT_ID(''dbo.Notification'',''U'') IS NOT NULL AND OBJECT_ID(''dbo.SystemUserRoles'',''U'') IS NOT NULL
  1681. AND (OBJECT_ID(''dbo.p_GetCrmUserId'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.p_GetPrivilegesInRole'',''P'') IS NOT NULL)
  1682. OR (OBJECT_ID(''dbo.p_AccountOVRollup'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.p_GetDbSize'',''P'') IS NOT NULL))
  1683. -- End Dynamics CRM
  1684. 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'')))
  1685. -- End Dynamics NAV
  1686. 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)
  1687. -- End Dynamics GP
  1688. 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)
  1689. -- End SCCM
  1690. 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)
  1691. -- End Forefront Endpoint Protection
  1692. 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)
  1693. -- End Fast Search
  1694. OR (OBJECT_ID(''fim.Objects'',''U'') IS NOT NULL AND SCHEMA_ID(''debug'') IS NOT NULL)
  1695. 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)
  1696. -- End Forefront Identity Manager
  1697. 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)
  1698. 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)
  1699. -- End PerformancePoint Services
  1700. 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))
  1701. -- End Project Server
  1702. OR (OBJECT_ID(''apm.MESSAGES'',''U'') IS NOT NULL AND SCHEMA_ID(''CS'') IS NOT NULL OR SCHEMA_ID(''CM'') IS NOT NULL)
  1703. 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)
  1704. 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)
  1705. 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)
  1706. -- End SCOM
  1707. OR (OBJECT_ID(''dbo.version'',''U'') IS NOT NULL AND EXISTS(SELECT 1 FROM sys.internal_tables (NOLOCK) WHERE name LIKE ''language[_]model[_]%''))
  1708. -- End Semantic Search
  1709. 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)
  1710. -- End WSUS
  1711. 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)
  1712. -- End DPM
  1713. OR ((OBJECT_ID(''dbo.DomainTable'',''U'') IS NOT NULL AND OBJECT_ID(''etl.Source'',''U'') IS NOT NULL)
  1714. 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)
  1715. 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))
  1716. -- End SCSM
  1717. 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)
  1718. -- End SSRS
  1719. OR (OBJECT_ID(''dbo.prc_ChangeHostId'',''P'') IS NOT NULL AND OBJECT_ID(''dbo.prc_EnablePrefixCompression'',''P'') IS NOT NULL
  1720. 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)
  1721. 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))
  1722. 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)
  1723. -- End TFS
  1724. 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)
  1725. -- End TFS Release Management
  1726. 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)
  1727. 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)
  1728. 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)
  1729. -- End Service Bus
  1730. 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)
  1731. 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)
  1732. 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)
  1733. -- End Workflow Manager
  1734. 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)
  1735. -- End SCSMA
  1736. BEGIN
  1737. SELECT @MSdbOUT = ' + CONVERT(VARCHAR(10), @dbid) + '
  1738. END'
  1739. SET @params = N'@MSdbOUT int OUTPUT';
  1740. EXECUTE sp_executesql @sqlcmd, @params, @MSdbOUT=@MSdb OUTPUT
  1741. IF @MSdb = @dbid
  1742. BEGIN
  1743. DELETE FROM #tmpdbs1
  1744. WHERE [dbid] = @dbid;
  1745. END
  1746. ELSE
  1747. BEGIN
  1748. UPDATE #tmpdbs1
  1749. SET isdone = 1
  1750. WHERE [dbid] = @dbid
  1751. END
  1752. END;
  1753. UPDATE #tmpdbs1
  1754. SET isdone = 0;
  1755. RAISERROR (N'|-Applying 2nd layer of specific database scope, if any', 10, 1) WITH NOWAIT
  1756. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  1757. DROP TABLE #tmpdbs_userchoice;
  1758. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  1759. CREATE TABLE #tmpdbs_userchoice ([dbid] int PRIMARY KEY, [dbname] VARCHAR(1000))
  1760. IF @dbScope IS NOT NULL
  1761. BEGIN
  1762. SELECT @sqlcmd = 'SELECT [dbid], [dbname]
  1763. FROM #tmpdbs0 (NOLOCK)
  1764. WHERE is_read_only = 0 AND [state] = 0 AND [dbid] > 4 AND is_distributor = 0
  1765. AND [role] <> 2 AND (secondary_role_allow_connections <> 0 OR secondary_role_allow_connections IS NULL)
  1766. AND [dbid] IN (' + REPLACE(@dbScope,' ','') + ')'
  1767. INSERT INTO #tmpdbs_userchoice ([dbid], [dbname])
  1768. EXEC sp_executesql @sqlcmd;
  1769. SELECT @sqlcmd = 'DELETE FROM #tmpdbs1 WHERE [dbid] NOT IN (' + REPLACE(@dbScope,' ','') + ')'
  1770. EXEC sp_executesql @sqlcmd;
  1771. END;
  1772. --------------------------------------------------------------------------------------------------------------------------------
  1773. -- Checks section
  1774. --------------------------------------------------------------------------------------------------------------------------------
  1775. RAISERROR (N'Starting Checks section', 10, 1) WITH NOWAIT
  1776. RAISERROR (N'|-Starting Processor Checks', 10, 1) WITH NOWAIT
  1777. --------------------------------------------------------------------------------------------------------------------------------
  1778. -- Number of available Processors for this instance vs. MaxDOP setting subsection
  1779. --------------------------------------------------------------------------------------------------------------------------------
  1780. RAISERROR (N' |-Starting Number of available Processors for this instance vs. MaxDOP setting', 10, 1) WITH NOWAIT
  1781. DECLARE /*@cpucount int, @numa int, */@affined_cpus int
  1782. /*
  1783. DECLARE @i int, @cpuaffin_fixed VARCHAR(300)
  1784. SET @cpuaffin_fixed = @cpuaffin
  1785. SET @i = @cpucount/@numa + 1
  1786. WHILE @i <= @cpucount
  1787. BEGIN
  1788. SELECT @cpuaffin_fixed = STUFF(@cpuaffin_fixed, @i, 1, '_' + SUBSTRING(@cpuaffin, @i, 1))
  1789. SET @i = @i + @cpucount/@numa + 1
  1790. END
  1791. */
  1792. SELECT @affined_cpus = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE is_online = 1 AND scheduler_id < 255 AND parent_node_id < 64;
  1793. --SELECT @cpucount = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64
  1794. SELECT 'Processor_checks' AS [Category], 'Parallelism_MaxDOP' AS [Check],
  1795. CASE WHEN [value] > @affined_cpus THEN '[WARNING: MaxDOP setting exceeds available processor count (affinity)]'
  1796. 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)]'
  1797. 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]'
  1798. 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]'
  1799. ELSE '[OK]'
  1800. END AS [Deviation]
  1801. FROM sys.configurations (NOLOCK) WHERE name = 'max degree of parallelism';
  1802. SELECT 'Processor_checks' AS [Category], 'Parallelism_MaxDOP' AS [Information],
  1803. CASE WHEN [value] > @affined_cpus THEN @affined_cpus
  1804. WHEN @numa = 1 AND @affined_cpus > 8 AND ([value] = 0 OR [value] > 8) THEN 8
  1805. WHEN @numa > 1 AND (@cpucount/@numa) < 8 AND ([value] = 0 OR [value] > (@cpucount/@numa)) THEN @cpucount/@numa
  1806. WHEN @numa > 1 AND (@cpucount/@numa) >= 8 AND ([value] = 0 OR [value] > 8 OR [value] > (@cpucount/@numa)) THEN 8
  1807. ELSE 0
  1808. END AS [Recommended_MaxDOP],
  1809. [value] AS [Current_MaxDOP], @cpucount AS [Available_Processors], @affined_cpus AS [Affined_Processors],
  1810. -- Processor Affinity is shown highest to lowest CPU ID
  1811. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1812. FROM sys.configurations (NOLOCK) WHERE name = 'max degree of parallelism';
  1813. --------------------------------------------------------------------------------------------------------------------------------
  1814. -- Processor Affinity in NUMA architecture subsection
  1815. --------------------------------------------------------------------------------------------------------------------------------
  1816. RAISERROR (N' |-Starting Processor Affinity in NUMA architecture', 10, 1) WITH NOWAIT
  1817. IF @numa > 1
  1818. BEGIN
  1819. 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),
  1820. 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)
  1821. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Check],
  1822. CASE WHEN (SELECT COUNT(*) FROM ncpuCTE) > 0 THEN '[WARNING: Current NUMA configuration is not recommended. At least one node has a single assigned CPU]'
  1823. 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]'
  1824. ELSE '[OK]' END AS [Deviation]
  1825. FROM sys.dm_os_sys_info (NOLOCK)
  1826. OPTION (RECOMPILE);
  1827. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Information], cpu_count AS [Logical_CPU_Count],
  1828. (SELECT COUNT(DISTINCT parent_node_id) FROM sys.dm_os_schedulers WHERE scheduler_id < 255 AND parent_node_id < 64) AS [NUMA_Nodes],
  1829. -- Processor Affinity is shown highest to lowest CPU ID
  1830. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1831. FROM sys.dm_os_sys_info (NOLOCK)
  1832. OPTION (RECOMPILE);
  1833. END
  1834. ELSE
  1835. BEGIN
  1836. SELECT 'Processor_checks' AS [Category], 'Affinity_NUMA' AS [Check], '[Not_NUMA]' AS [Deviation]
  1837. FROM sys.dm_os_sys_info (NOLOCK)
  1838. OPTION (RECOMPILE);
  1839. END;
  1840. --------------------------------------------------------------------------------------------------------------------------------
  1841. -- Additional Processor information subsection
  1842. --------------------------------------------------------------------------------------------------------------------------------
  1843. RAISERROR (N' |-Starting Additional Processor information', 10, 1) WITH NOWAIT
  1844. -- Processor Info
  1845. SELECT 'Processor_checks' AS [Category], 'Processor_Summary' AS [Information], cpu_count AS [Logical_CPU_Count], hyperthread_ratio AS [Cores2Socket_Ratio],
  1846. cpu_count/hyperthread_ratio AS [CPU_Sockets],
  1847. 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],
  1848. @affined_cpus AS [Affined_Processors],
  1849. -- Processor Affinity is shown highest to lowest Processor ID
  1850. @cpuaffin_fixed AS Affinity_Mask_Bitmask
  1851. FROM sys.dm_os_sys_info (NOLOCK)
  1852. OPTION (RECOMPILE);
  1853. IF @ptochecks = 1
  1854. BEGIN
  1855. RAISERROR (N' |-Starting Processor utilization rate in the last 2 hours', 10, 1) WITH NOWAIT
  1856. -- Processor utilization rate in the last 2 hours
  1857. DECLARE @ts_now bigint
  1858. DECLARE @tblAggCPU TABLE (SQLProc tinyint, SysIdle tinyint, OtherProc tinyint, Minutes tinyint)
  1859. SELECT @ts_now = ms_ticks FROM sys.dm_os_sys_info (NOLOCK);
  1860. WITH cteCPU (record_id, SystemIdle, SQLProcessUtilization, [timestamp]) AS (SELECT
  1861. record.value('(./Record/@id)[1]', 'int') AS record_id,
  1862. record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS SystemIdle,
  1863. record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS SQLProcessUtilization,
  1864. [TIMESTAMP] FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  1865. FROM sys.dm_os_ring_buffers (NOLOCK)
  1866. WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
  1867. AND record LIKE '%<SystemHealth>%') AS x
  1868. )
  1869. INSERT INTO @tblAggCPU
  1870. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 10
  1871. FROM cteCPU
  1872. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -10, GETDATE())
  1873. UNION ALL
  1874. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 20
  1875. FROM cteCPU
  1876. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -10, GETDATE()) AND
  1877. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -20, GETDATE())
  1878. UNION ALL
  1879. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 30
  1880. FROM cteCPU
  1881. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -20, GETDATE()) AND
  1882. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -30, GETDATE())
  1883. UNION ALL
  1884. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 40
  1885. FROM cteCPU
  1886. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -30, GETDATE()) AND
  1887. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -40, GETDATE())
  1888. UNION ALL
  1889. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 50
  1890. FROM cteCPU
  1891. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -40, GETDATE()) AND
  1892. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -50, GETDATE())
  1893. UNION ALL
  1894. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 60
  1895. FROM cteCPU
  1896. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -50, GETDATE()) AND
  1897. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -60, GETDATE())
  1898. UNION ALL
  1899. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 70
  1900. FROM cteCPU
  1901. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -60, GETDATE()) AND
  1902. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -70, GETDATE())
  1903. UNION ALL
  1904. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 80
  1905. FROM cteCPU
  1906. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -70, GETDATE()) AND
  1907. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -80, GETDATE())
  1908. UNION ALL
  1909. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 90
  1910. FROM cteCPU
  1911. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -80, GETDATE()) AND
  1912. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -90, GETDATE())
  1913. UNION ALL
  1914. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 100
  1915. FROM cteCPU
  1916. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -90, GETDATE()) AND
  1917. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -100, GETDATE())
  1918. UNION ALL
  1919. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 110
  1920. FROM cteCPU
  1921. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -100, GETDATE()) AND
  1922. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -110, GETDATE())
  1923. UNION ALL
  1924. SELECT AVG(SQLProcessUtilization), AVG(SystemIdle), CASE WHEN AVG(SystemIdle) + AVG(SQLProcessUtilization) < 100 THEN 100 - AVG(SystemIdle) - AVG(SQLProcessUtilization) ELSE 0 END, 120
  1925. FROM cteCPU
  1926. WHERE DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) <= DATEADD(mi, -110, GETDATE()) AND
  1927. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) > DATEADD(mi, -120, GETDATE())
  1928. IF (SELECT COUNT(SysIdle) FROM @tblAggCPU WHERE SysIdle < 30) > 0
  1929. BEGIN
  1930. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[WARNING: Detected CPU usage over 70 pct]' AS [Deviation];
  1931. END
  1932. ELSE IF (SELECT COUNT(SysIdle) FROM @tblAggCPU WHERE SysIdle < 10) > 0
  1933. BEGIN
  1934. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[WARNING: Detected CPU usage over 90 pct]' AS [Deviation];
  1935. END
  1936. ELSE
  1937. BEGIN
  1938. SELECT 'Processor_checks' AS [Category], 'Processor_Usage_last_2h' AS [Check], '[OK]' AS [Deviation];
  1939. END;
  1940. 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]
  1941. FROM @tblAggCPU;
  1942. END;
  1943. RAISERROR (N'|-Starting Memory Checks', 10, 1) WITH NOWAIT
  1944. --------------------------------------------------------------------------------------------------------------------------------
  1945. -- Server Memory subsection
  1946. --------------------------------------------------------------------------------------------------------------------------------
  1947. RAISERROR (N' |-Starting Server Memory', 10, 1) WITH NOWAIT
  1948. DECLARE @maxservermem bigint, @minservermem bigint, @systemmem bigint, @systemfreemem bigint, @numa_nodes_afinned tinyint, @LowMemoryThreshold int
  1949. DECLARE @commit_target bigint -- Includes stolen and reserved memory in the memory manager
  1950. DECLARE @committed bigint -- Does not include reserved memory in the memory manager
  1951. DECLARE @mwthreads_count int, @xtp int
  1952. IF @sqlmajorver = 9
  1953. BEGIN
  1954. SET @sqlcmd = N'SELECT @systemmemOUT = t1.record.value(''(./Record/MemoryRecord/TotalPhysicalMemory)[1]'', ''bigint'')/1024,
  1955. @systemfreememOUT = t1.record.value(''(./Record/MemoryRecord/AvailablePhysicalMemory)[1]'', ''bigint'')/1024
  1956. FROM (SELECT MAX([TIMESTAMP]) AS [TIMESTAMP], CONVERT(xml, record) AS record
  1957. FROM sys.dm_os_ring_buffers (NOLOCK)
  1958. WHERE ring_buffer_type = N''RING_BUFFER_RESOURCE_MONITOR''
  1959. AND record LIKE ''%RESOURCE_MEMPHYSICAL%''
  1960. GROUP BY record) AS t1';
  1961. END
  1962. ELSE
  1963. BEGIN
  1964. SET @sqlcmd = N'SELECT @systemmemOUT = total_physical_memory_kb/1024, @systemfreememOUT = available_physical_memory_kb/1024 FROM sys.dm_os_sys_memory';
  1965. END
  1966. SET @params = N'@systemmemOUT bigint OUTPUT, @systemfreememOUT bigint OUTPUT';
  1967. EXECUTE sp_executesql @sqlcmd, @params, @systemmemOUT=@systemmem OUTPUT, @systemfreememOUT=@systemfreemem OUTPUT;
  1968. IF @sqlmajorver >= 9 AND @sqlmajorver < 11
  1969. BEGIN
  1970. SET @sqlcmd = N'SELECT @commit_targetOUT=bpool_commit_target*8, @committedOUT=bpool_committed*8 FROM sys.dm_os_sys_info (NOLOCK)'
  1971. END
  1972. ELSE IF @sqlmajorver >= 11
  1973. BEGIN
  1974. SET @sqlcmd = N'SELECT @commit_targetOUT=committed_target_kb, @committedOUT=committed_kb FROM sys.dm_os_sys_info (NOLOCK)'
  1975. END
  1976. SET @params = N'@commit_targetOUT bigint OUTPUT, @committedOUT bigint OUTPUT';
  1977. EXECUTE sp_executesql @sqlcmd, @params, @commit_targetOUT=@commit_target OUTPUT, @committedOUT=@committed OUTPUT;
  1978. SELECT @minservermem = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE [Name] = 'min server memory (MB)';
  1979. SELECT @maxservermem = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE [Name] = 'max server memory (MB)';
  1980. SELECT @mwthreads_count = max_workers_count FROM sys.dm_os_sys_info;
  1981. 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
  1982. /*
  1983. From Windows Internals book by David Solomon and Mark Russinovich:
  1984. "The default level of available memory that signals a low-memory-resource notification event is approximately 32 MB per 4 GB,
  1985. 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."
  1986. */
  1987. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  1988. BEGIN
  1989. BEGIN TRY
  1990. SELECT @RegKey = N'System\CurrentControlSet\Control\SessionManager\MemoryManagement'
  1991. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'LowMemoryThreshold', @LowMemoryThreshold OUTPUT, NO_OUTPUT
  1992. IF @LowMemoryThreshold IS NULL
  1993. SELECT @LowMemoryThreshold = CASE WHEN @systemmem <= 4096 THEN 32 ELSE 64 END
  1994. END TRY
  1995. BEGIN CATCH
  1996. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  1997. SELECT @ErrorMessage = 'Server Memory subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  1998. RAISERROR (@ErrorMessage, 16, 1);
  1999. END CATCH
  2000. END
  2001. ELSE
  2002. BEGIN
  2003. RAISERROR('[WARNING: Missing permissions for full "Instance info" checks. Bypassing LowMemoryThreshold check]', 16, 1, N'sysadmin')
  2004. --RETURN
  2005. END;
  2006. SELECT 'Memory_checks' AS [Category], 'Memory_issues_MaxServerMem' AS [Check],
  2007. CASE WHEN @maxservermem = 2147483647 THEN '[WARNING: MaxMem setting is default. Please revise memory settings]'
  2008. WHEN @maxservermem > @systemmem THEN '[WARNING: MaxMem setting exceeds available system memory]'
  2009. WHEN @numa > 1 AND (@maxservermem/@numa) * @numa_nodes_afinned > (@systemmem/@numa) * @numa_nodes_afinned THEN '[WARNING: Current MaxMem setting will leverage node foreign memory.
  2010. Maximum value for MaxMem setting on this configuration is ' + CONVERT(NVARCHAR,(@systemmem/@numa) * @numa_nodes_afinned) + ' for a single instance]'
  2011. ELSE '[OK]'
  2012. END AS [Deviation], @maxservermem AS [sql_max_mem_MB];
  2013. SELECT 'Memory_checks' AS [Category], 'Memory_issues_MinServerMem' AS [Check],
  2014. 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]'
  2015. 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]'
  2016. 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]'
  2017. WHEN @numa > 1 AND (@minservermem/@numa) * @numa_nodes_afinned > (@systemmem/@numa) * @numa_nodes_afinned THEN '[WARNING: Current MinMem setting will leverage node foreign memory]'
  2018. ELSE '[OK]'
  2019. END AS [Deviation], @minservermem AS [sql_min_mem_MB];
  2020. SELECT 'Memory_checks' AS [Category], 'Memory_issues_FreeMem' AS [Check],
  2021. CASE WHEN (@systemfreemem*100)/@systemmem <= 5 THEN '[WARNING: Less than 5 percent of Free Memory available. Please revise memory settings]'
  2022. /* 64 is the default LowMemThreshold for windows on a system with 8GB of mem or more*/
  2023. WHEN @systemfreemem <= 64*3 THEN '[WARNING: System Free Memory is dangerously low. Please revise memory settings]'
  2024. ELSE '[OK]'
  2025. END AS [Deviation], @systemmem AS system_total_physical_memory_MB, @systemfreemem AS system_available_physical_memory_MB;
  2026. SELECT 'Memory_checks' AS [Category], 'Memory_issues_CommitedMem' AS [Check],
  2027. CASE WHEN @commit_target > @committed AND @sqlmajorver >= 11 THEN '[INFORMATION: Memory manager will try to obtain additional memory]'
  2028. WHEN @commit_target < @committed AND @sqlmajorver >= 11 THEN '[INFORMATION: Memory manager will try to shrink the amount of memory committed]'
  2029. WHEN @commit_target > @committed AND @sqlmajorver < 11 THEN '[INFORMATION: Buffer Pool will try to obtain additional memory]'
  2030. WHEN @commit_target < @committed AND @sqlmajorver < 11 THEN '[INFORMATION: Buffer Pool will try to shrink]'
  2031. ELSE '[OK]'
  2032. END AS [Deviation], @commit_target/1024 AS sql_commit_target_MB, @committed/1024 AS sql_commited_MB;
  2033. SELECT 'Memory_checks' AS [Category], 'Memory_reference' AS [Check],
  2034. CASE WHEN @arch IS NULL THEN '[WARNING: Could not determine architecture needed for check]'
  2035. 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
  2036. (@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
  2037. (@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
  2038. (@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
  2039. (@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
  2040. (@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
  2041. (@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]'
  2042. ELSE '[OK]'
  2043. END AS [Deviation],
  2044. 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))
  2045. 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))
  2046. 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))
  2047. 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))
  2048. 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))
  2049. 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))
  2050. 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))
  2051. END AS [Recommended_MaxMem_MB_SingleInstance],
  2052. CASE WHEN @systemmem <= 2048 THEN 512
  2053. WHEN @systemmem BETWEEN 2049 AND 4096 THEN 819
  2054. WHEN @systemmem BETWEEN 4097 AND 8192 THEN 1228
  2055. WHEN @systemmem BETWEEN 8193 AND 12288 THEN 2048
  2056. WHEN @systemmem BETWEEN 12289 AND 24576 THEN 2560
  2057. WHEN @systemmem BETWEEN 24577 AND 32768 THEN 3072
  2058. WHEN @systemmem > 32768 THEN 4096
  2059. END AS [Mem_MB_for_OS],
  2060. 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)
  2061. 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)
  2062. 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)
  2063. 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)
  2064. 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)
  2065. 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)
  2066. WHEN @systemmem > 32768 THEN @mwthreads_count*(CASE WHEN @arch = 64 THEN 2 WHEN @arch = 128 THEN 4 WHEN @arch = 32 THEN 0.5 END)
  2067. END AS [Potential_threads_mem_MB],
  2068. @mwthreads_count AS [Configured_workers];
  2069. IF @sqlmajorver = 9
  2070. BEGIN
  2071. SELECT 'Memory_checks' AS [Category], 'Memory_Summary' AS [Information],
  2072. @maxservermem AS sql_max_mem_MB, @minservermem AS sql_min_mem_MB,
  2073. @commit_target/1024 AS sql_commit_target_MB, --BPool in SQL 2005 to 2008R2
  2074. @committed/1024 AS sql_commited_MB, --BPool in SQL 2005 to 2008R2
  2075. @systemmem AS system_total_physical_memory_MB,
  2076. @systemfreemem AS system_available_physical_memory_MB
  2077. END
  2078. ELSE
  2079. BEGIN
  2080. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Memory_Summary'' AS [Information],
  2081. @maxservermemIN AS sql_max_mem_MB, @minservermemIN AS sql_min_mem_MB,
  2082. @commit_targetIN/1024 AS sql_commit_target_MB, --BPool in SQL 2005 to 2008R2
  2083. @committedIN/1024 AS sql_commited_MB, --BPool in SQL 2005 to 2008R2
  2084. physical_memory_in_use_kb/1024 AS sql_physical_memory_in_use_MB,
  2085. large_page_allocations_kb/1024 AS sql_large_page_allocations_MB,
  2086. locked_page_allocations_kb/1024 AS sql_locked_page_allocations_MB,
  2087. @systemmemIN AS system_total_physical_memory_MB,
  2088. @systemfreememIN AS system_available_physical_memory_MB,
  2089. total_virtual_address_space_kb/1024 AS sql_total_VAS_MB,
  2090. virtual_address_space_reserved_kb/1024 AS sql_VAS_reserved_MB,
  2091. virtual_address_space_committed_kb/1024 AS sql_VAS_committed_MB,
  2092. virtual_address_space_available_kb/1024 AS sql_VAS_available_MB,
  2093. page_fault_count AS sql_page_fault_count,
  2094. memory_utilization_percentage AS sql_memory_utilization_percentage,
  2095. process_physical_memory_low AS sql_process_physical_memory_low,
  2096. process_virtual_memory_low AS sql_process_virtual_memory_low
  2097. FROM sys.dm_os_process_memory (NOLOCK)'
  2098. SET @params = N'@maxservermemIN bigint, @minservermemIN bigint, @systemmemIN bigint, @systemfreememIN bigint, @commit_targetIN bigint, @committedIN bigint';
  2099. EXECUTE sp_executesql @sqlcmd, @params, @maxservermemIN=@maxservermem, @minservermemIN=@minservermem,@systemmemIN=@systemmem, @systemfreememIN=@systemfreemem, @commit_targetIN=@commit_target, @committedIN=@committed
  2100. END;
  2101. IF @numa > 1 AND @sqlmajorver > 10
  2102. BEGIN
  2103. 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;')
  2104. END
  2105. ELSE IF @numa > 1 AND @sqlmajorver = 10
  2106. BEGIN
  2107. 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;')
  2108. END;
  2109. IF @ptochecks = 1
  2110. BEGIN
  2111. RAISERROR (N' |-Starting RM Task', 10, 1) WITH NOWAIT
  2112. IF @LowMemoryThreshold IS NOT NULL
  2113. SELECT 'Memory_checks' AS [Category], 'Memory_RM_Tresholds' AS [Information], @LowMemoryThreshold AS [MEMPHYSICAL_LOW_Threshold], @LowMemoryThreshold * 3 AS [MEMPHYSICAL_HIGH_Threshold]
  2114. SELECT 'Memory_checks' AS [Category], 'Memory_RM_Notifications' AS [Information],
  2115. 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())
  2116. ELSE DATEADD(s, ([TIMESTAMP]/1000) - (si.ms_ticks/1000), GETDATE()) END AS Event_Time,
  2117. record.value('(./Record/ResourceMonitor/Notification)[1]', 'VARCHAR(max)') AS [Notification],
  2118. record.value('(./Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint')/1024 AS [Total_Physical_Mem_MB],
  2119. record.value('(./Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint')/1024 AS [Avail_Physical_Mem_MB],
  2120. record.value('(./Record/MemoryRecord/AvailableVirtualAddressSpace)[1]', 'bigint')/1024 AS [Avail_VAS_MB],
  2121. record.value('(./Record/MemoryRecord/TotalPageFile)[1]', 'bigint')/1024 AS [Total_Pagefile_MB],
  2122. record.value('(./Record/MemoryRecord/AvailablePageFile)[1]', 'bigint')/1024 AS [Avail_Pagefile_MB]
  2123. FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  2124. FROM sys.dm_os_ring_buffers (NOLOCK)
  2125. WHERE ring_buffer_type = N'RING_BUFFER_RESOURCE_MONITOR') AS x
  2126. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2127. --WHERE CASE WHEN x.[timestamp] BETWEEN -2147483648 AND 2147483648 THEN DATEADD(ms, x.[timestamp] - si.ms_ticks, GETDATE())
  2128. -- ELSE DATEADD(s, (x.[timestamp]/1000) - (si.ms_ticks/1000), GETDATE()) END >= DATEADD(hh, -12, GETDATE())
  2129. ORDER BY 2 DESC;
  2130. RAISERROR (N' |-Starting Hand Movements from Cache Clock Hands', 10, 1) WITH NOWAIT
  2131. IF (SELECT COUNT(rounds_count) FROM sys.dm_os_memory_cache_clock_hands (NOLOCK) WHERE rounds_count > 0) > 0
  2132. BEGIN
  2133. IF @sqlmajorver >= 11
  2134. BEGIN
  2135. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Clock_Hand_Notifications'' AS [Information], mcch.name, mcch.[type],
  2136. mcch.clock_hand, mcch.clock_status, SUM(mcch.rounds_count) AS rounds_count,
  2137. SUM(mcch.removed_all_rounds_count) AS cache_entries_removed_all_rounds,
  2138. SUM(mcch.removed_last_round_count) AS cache_entries_removed_last_round,
  2139. SUM(mcch.updated_last_round_count) AS cache_entries_updated_last_round,
  2140. SUM(mcc.pages_kb) AS cache_pages_kb,
  2141. SUM(mcc.pages_in_use_kb) AS cache_pages_in_use_kb,
  2142. SUM(mcc.entries_count) AS cache_entries_count,
  2143. SUM(mcc.entries_in_use_count) AS cache_entries_in_use_count,
  2144. 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())
  2145. 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())
  2146. ELSE NULL END AS last_clock_hand_move
  2147. FROM sys.dm_os_memory_cache_counters mcc (NOLOCK)
  2148. INNER JOIN sys.dm_os_memory_cache_clock_hands mcch (NOLOCK) ON mcc.cache_address = mcch.cache_address
  2149. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2150. WHERE mcch.rounds_count > 0
  2151. 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
  2152. ORDER BY SUM(mcch.removed_all_rounds_count) DESC, mcch.[type];'
  2153. END
  2154. ELSE
  2155. BEGIN
  2156. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''Clock_Hand_Notifications'' AS [Information], mcch.name, mcch.[type],
  2157. mcch.clock_hand, mcch.clock_status, SUM(mcch.rounds_count) AS rounds_count,
  2158. SUM(mcch.removed_all_rounds_count) AS cache_entries_removed_all_rounds,
  2159. SUM(mcch.removed_last_round_count) AS cache_entries_removed_last_round,
  2160. SUM(mcch.updated_last_round_count) AS cache_entries_updated_last_round,
  2161. SUM(mcc.single_pages_kb) AS cache_single_pages_kb,
  2162. SUM(mcc.multi_pages_kb) AS cache_multi_pages_kb,
  2163. SUM(mcc.single_pages_in_use_kb) AS cache_single_pages_in_use_kb,
  2164. SUM(mcc.multi_pages_in_use_kb) AS cache_multi_pages_in_use_kb,
  2165. SUM(mcc.entries_count) AS cache_entries_count,
  2166. SUM(mcc.entries_in_use_count) AS cache_entries_in_use_count,
  2167. 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())
  2168. 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())
  2169. ELSE NULL END AS last_clock_hand_move
  2170. FROM sys.dm_os_memory_cache_counters mcc (NOLOCK)
  2171. INNER JOIN sys.dm_os_memory_cache_clock_hands mcch (NOLOCK) ON mcc.cache_address = mcch.cache_address
  2172. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2173. WHERE mcch.rounds_count > 0
  2174. 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
  2175. ORDER BY SUM(mcch.removed_all_rounds_count) DESC, mcch.[type];'
  2176. END
  2177. EXECUTE sp_executesql @sqlcmd;
  2178. END
  2179. ELSE
  2180. BEGIN
  2181. SELECT 'Memory_checks' AS [Category], 'Clock_Hand_Notifications' AS [Information], '[OK]' AS Comment
  2182. END;
  2183. IF @bpool_consumer = 1
  2184. BEGIN
  2185. RAISERROR (N' |-Starting Buffer Pool Consumers from Buffer Descriptors', 10, 1) WITH NOWAIT
  2186. -- Note: in case of NUMA architecture, more than one entry per database is expected
  2187. SET @sqlcmd = 'SELECT ''Memory_checks'' AS [Category], ''Buffer_Pool_Consumers'' AS [Information],
  2188. COUNT_BIG(DISTINCT page_id)*8/1024 AS total_pages_MB,
  2189. CASE database_id WHEN 32767 THEN ''ResourceDB'' ELSE DB_NAME(database_id) END AS database_name,
  2190. SUM(row_count)/COUNT_BIG(DISTINCT page_id) AS avg_row_count_per_page,
  2191. SUM(CONVERT(BIGINT, free_space_in_bytes))/COUNT_BIG(DISTINCT page_id) AS avg_free_space_bytes_per_page
  2192. ' + CASE WHEN @sqlmajorver >= 12 THEN ',is_in_bpool_extension' ELSE '' END + '
  2193. ' + CASE WHEN @sqlmajorver = 10 THEN ',numa_node' ELSE '' END + '
  2194. ' + CASE WHEN @sqlmajorver >= 11 THEN ',AVG(read_microsec) AS avg_read_microsec' ELSE '' END + '
  2195. FROM sys.dm_os_buffer_descriptors
  2196. --WHERE bd.page_type IN (''DATA_PAGE'', ''INDEX_PAGE'')
  2197. GROUP BY database_id' + CASE WHEN @sqlmajorver >= 10 THEN ', numa_node' ELSE '' END + CASE WHEN @sqlmajorver >= 12 THEN ', is_in_bpool_extension' ELSE '' END + '
  2198. ORDER BY total_pages_MB DESC;'
  2199. EXECUTE sp_executesql @sqlcmd;
  2200. END
  2201. RAISERROR (N' |-Starting Memory Allocations from Memory Clerks', 10, 1) WITH NOWAIT
  2202. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], [type] AS Alloc_Type,
  2203. ' + 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'
  2204. ELSE 'SUM(pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb + awe_allocated_kb) AS Alloc_Mem_KB' END + '
  2205. FROM sys.dm_os_memory_clerks
  2206. WHERE type IN (''CACHESTORE_COLUMNSTOREOBJECTPOOL'',''CACHESTORE_CLRPROC'',''CACHESTORE_OBJCP'',''CACHESTORE_PHDR'',''CACHESTORE_SQLCP'',''CACHESTORE_TEMPTABLES'',
  2207. ''MEMORYCLERK_SQLBUFFERPOOL'',''MEMORYCLERK_SQLCLR'',''MEMORYCLERK_SQLGENERAL'',''MEMORYCLERK_SQLLOGPOOL'',''MEMORYCLERK_SQLOPTIMIZER'',
  2208. ''MEMORYCLERK_SQLQUERYCOMPILE'',''MEMORYCLERK_SQLQUERYEXEC'',''MEMORYCLERK_SQLQUERYPLAN'',''MEMORYCLERK_SQLSTORENG'',''MEMORYCLERK_XTP'',
  2209. ''OBJECTSTORE_LOCK_MANAGER'',''OBJECTSTORE_SNI_PACKET'',''USERSTORE_DBMETADATA'',''USERSTORE_OBJPERM'')
  2210. GROUP BY [type]
  2211. UNION ALL
  2212. SELECT ''Memory_checks'' AS [Category], ''Others'' AS Alloc_Type,
  2213. ' + CASE WHEN @sqlmajorver < 11 THEN 'SUM(single_pages_kb + multi_pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb) AS Alloc_Mem_KB'
  2214. ELSE 'SUM(pages_kb + virtual_memory_committed_kb + shared_memory_committed_kb) AS Alloc_Mem_KB' END + '
  2215. FROM sys.dm_os_memory_clerks
  2216. WHERE type NOT IN (''CACHESTORE_COLUMNSTOREOBJECTPOOL'',''CACHESTORE_CLRPROC'',''CACHESTORE_OBJCP'',''CACHESTORE_PHDR'',''CACHESTORE_SQLCP'',''CACHESTORE_TEMPTABLES'',
  2217. ''MEMORYCLERK_SQLBUFFERPOOL'',''MEMORYCLERK_SQLCLR'',''MEMORYCLERK_SQLGENERAL'',''MEMORYCLERK_SQLLOGPOOL'',''MEMORYCLERK_SQLOPTIMIZER'',
  2218. ''MEMORYCLERK_SQLQUERYCOMPILE'',''MEMORYCLERK_SQLQUERYEXEC'',''MEMORYCLERK_SQLQUERYPLAN'',''MEMORYCLERK_SQLSTORENG'',''MEMORYCLERK_XTP'',
  2219. ''OBJECTSTORE_LOCK_MANAGER'',''OBJECTSTORE_SNI_PACKET'',''USERSTORE_DBMETADATA'',''USERSTORE_OBJPERM'')
  2220. ORDER BY Alloc_Mem_KB'
  2221. EXECUTE sp_executesql @sqlcmd;
  2222. IF @sqlmajorver >= 12
  2223. BEGIN
  2224. SET @sqlcmd = N'SELECT @xtpOUT = COUNT(*) FROM sys.dm_db_xtp_memory_consumers';
  2225. SET @params = N'@xtpOUT int OUTPUT';
  2226. EXECUTE sp_executesql @sqlcmd, @params, @xtpOUT = @xtp OUTPUT;
  2227. IF @xtp > 0
  2228. BEGIN
  2229. RAISERROR (N' |-Starting Memory Consumers from In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  2230. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''InMemory_Consumers'' AS Alloc_Type,
  2231. OBJECT_NAME([object_id]) AS [Object_Name], memory_consumer_type_desc, [object_id], index_id,
  2232. allocated_bytes/(1024*1024) AS Allocated_MB, used_bytes/(1024*1024) AS Used_MB,
  2233. CASE WHEN used_bytes IS NULL THEN ''used_bytes_is_varheap_only'' ELSE '''' END AS [Comment]
  2234. FROM sys.dm_db_xtp_memory_consumers
  2235. WHERE [object_id] > 0
  2236. ORDER BY Allocated_MB DESC' -- Only user objects; system objects are negative numbers
  2237. EXECUTE sp_executesql @sqlcmd;
  2238. RAISERROR (N' |-Starting Memory Allocations from In-Memory OLTP Engine', 10, 1) WITH NOWAIT
  2239. SET @sqlcmd = N'SELECT ''Memory_checks'' AS [Category], ''InMemory_Alloc'' AS Alloc_Type,
  2240. SUM(allocated_bytes)/(1024*1024) AS total_allocated_MB, SUM(used_bytes)/(1024*1024) AS total_used_MB
  2241. FROM sys.dm_db_xtp_memory_consumers
  2242. ORDER BY total_allocated_MB DESC'
  2243. EXECUTE sp_executesql @sqlcmd;
  2244. END;
  2245. END;
  2246. END;
  2247. RAISERROR (N' |-Starting OOM', 10, 1) WITH NOWAIT
  2248. IF (SELECT COUNT([TIMESTAMP]) FROM sys.dm_os_ring_buffers (NOLOCK) WHERE ring_buffer_type = N'RING_BUFFER_OOM') > 0
  2249. BEGIN
  2250. SELECT 'Memory_checks' AS [Category], 'OOM_Notifications' AS [Information],
  2251. 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())
  2252. ELSE DATEADD(s, ([TIMESTAMP]/1000) - (si.ms_ticks/1000), GETDATE()) END AS Event_Time,
  2253. record.value('(./Record/OOM/Action)[1]', 'varchar(50)') AS [Action],
  2254. record.value('(./Record/OOM/Resources)[1]', 'int') AS [Resources],
  2255. record.value('(./Record/OOM/Task)[1]', 'varchar(20)') AS [Task],
  2256. record.value('(./Record/OOM/Pool)[1]', 'int') AS [PoolID],
  2257. rgrp.name AS [PoolName],
  2258. record.value('(./Record/MemoryRecord/MemoryUtilization)[1]', 'bigint') AS [MemoryUtilPct],
  2259. record.value('(./Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint')/1024 AS [Total_Physical_Mem_MB],
  2260. record.value('(./Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint')/1024 AS [Avail_Physical_Mem_MB],
  2261. record.value('(./Record/MemoryRecord/AvailableVirtualAddressSpace)[1]', 'bigint')/1024 AS [Avail_VAS_MB],
  2262. record.value('(./Record/MemoryRecord/TotalPageFile)[1]', 'bigint')/1024 AS [Total_Pagefile_MB],
  2263. record.value('(./Record/MemoryRecord/AvailablePageFile)[1]', 'bigint')/1024 AS [Avail_Pagefile_MB]
  2264. FROM (SELECT [TIMESTAMP], CONVERT(xml, record) AS record
  2265. FROM sys.dm_os_ring_buffers (NOLOCK)
  2266. WHERE ring_buffer_type = N'RING_BUFFER_OOM') AS x
  2267. CROSS JOIN sys.dm_os_sys_info si (NOLOCK)
  2268. LEFT JOIN sys.resource_governor_resource_pools rgrp (NOLOCK) ON rgrp.pool_id = record.value('(./Record/OOM/Pool)[1]', 'int')
  2269. --WHERE CASE WHEN x.[timestamp] BETWEEN -2147483648 AND 2147483648 THEN DATEADD(ms, x.[timestamp] - si.ms_ticks, GETDATE())
  2270. -- ELSE DATEADD(s, (x.[timestamp]/1000) - (si.ms_ticks/1000), GETDATE()) END >= DATEADD(hh, -12, GETDATE())
  2271. ORDER BY 2 DESC;
  2272. END
  2273. ELSE
  2274. BEGIN
  2275. SELECT 'Memory_checks' AS [Category], 'OOM_Notifications' AS [Information], '[OK]' AS Comment
  2276. END;
  2277. --------------------------------------------------------------------------------------------------------------------------------
  2278. -- LPIM subsection
  2279. --------------------------------------------------------------------------------------------------------------------------------
  2280. RAISERROR (N' |-Starting LPIM', 10, 1) WITH NOWAIT
  2281. DECLARE @lpim bit, @lognumber int, @logcount int
  2282. IF ((@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13)
  2283. BEGIN
  2284. SET @sqlcmd = N'SELECT @lpimOUT = CASE WHEN sql_memory_model = 2 THEN 1 ELSE 0 END FROM sys.dm_os_sys_info';
  2285. SET @params = N'@lpimOUT bit OUTPUT';
  2286. EXECUTE sp_executesql @sqlcmd, @params, @lpimOUT=@lpim OUTPUT;
  2287. END
  2288. ELSE IF ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13)
  2289. BEGIN
  2290. SET @sqlcmd = N'SELECT @lpimOUT = CASE WHEN locked_page_allocations_kb > 0 THEN 1 ELSE 0 END FROM sys.dm_os_process_memory (NOLOCK)'
  2291. SET @params = N'@lpimOUT bit OUTPUT';
  2292. EXECUTE sp_executesql @sqlcmd, @params, @lpimOUT=@lpim OUTPUT
  2293. END
  2294. ELSE IF @sqlmajorver = 9
  2295. BEGIN
  2296. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2297. OR ISNULL(IS_SRVROLEMEMBER(N'securityadmin'), 0) = 1 -- Is securityadmin
  2298. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_readerrorlog') > 0
  2299. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_readerrorlog') > 0
  2300. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_enumerrorlogs') > 0)
  2301. BEGIN
  2302. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimdbcc'))
  2303. DROP TABLE #lpimdbcc;
  2304. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimdbcc'))
  2305. CREATE TABLE #lpimdbcc (logdate DATETIME, spid VARCHAR(50), logmsg VARCHAR(4000))
  2306. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimavail_logs'))
  2307. DROP TABLE #lpimavail_logs;
  2308. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#lpimavail_logs'))
  2309. CREATE TABLE #lpimavail_logs (lognum int, logdate DATETIME, logsize int)
  2310. -- Get the number of available logs
  2311. INSERT INTO #lpimavail_logs
  2312. EXEC xp_enumerrorlogs
  2313. SELECT @lognumber = MIN(lognum) FROM #lpimavail_logs WHERE DATEADD(dd, DATEDIFF(dd, 0, logdate), 0) >= DATEADD(dd, DATEDIFF(dd, 0, @StartDate), 0)
  2314. SELECT @logcount = ISNULL(MAX(lognum),@lognumber) FROM #lpimavail_logs WHERE DATEADD(dd, DATEDIFF(dd, 0, logdate), 0) >= DATEADD(dd, DATEDIFF(dd, 0, @StartDate), 0)
  2315. IF @lognumber IS NULL
  2316. BEGIN
  2317. SELECT @ErrorMessage = '[WARNING: Could not retrieve information about Locked pages usage in SQL Server 2005]'
  2318. RAISERROR (@ErrorMessage, 16, 1);
  2319. END
  2320. ELSE
  2321. WHILE @lognumber < @logcount
  2322. BEGIN
  2323. -- Cycle through sql error logs (Cannot use Large Page Extensions: lock memory privilege was not granted)
  2324. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''Using locked pages for buffer pool'''
  2325. BEGIN TRY
  2326. INSERT INTO #lpimdbcc (logdate, spid, logmsg)
  2327. EXECUTE (@sqlcmd);
  2328. END TRY
  2329. BEGIN CATCH
  2330. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2331. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  2332. RAISERROR (@ErrorMessage, 16, 1);
  2333. END CATCH
  2334. -- Next log
  2335. --SET @lognumber = @lognumber + 1
  2336. SELECT @lognumber = MIN(lognum) FROM #lpimavail_logs WHERE lognum > @lognumber
  2337. END
  2338. IF (SELECT COUNT(*) FROM #lpimdbcc) > 0
  2339. BEGIN
  2340. SET @lpim = 1
  2341. END
  2342. ELSE IF (SELECT COUNT(*) FROM #lpimdbcc) = 0 AND @lognumber IS NOT NULL
  2343. BEGIN
  2344. SET @lpim = 0
  2345. END;
  2346. DROP TABLE #lpimavail_logs;
  2347. DROP TABLE #lpimdbcc;
  2348. END
  2349. ELSE
  2350. BEGIN
  2351. RAISERROR('[WARNING: Only a sysadmin or securityadmin can run the "Locked_pages" check. Bypassing check]', 16, 1, N'permissions')
  2352. 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')
  2353. --RETURN
  2354. END;
  2355. END
  2356. IF @lpim = 0 AND CONVERT(DECIMAL(3,1), @winver) < 6.0 AND @arch = 64
  2357. BEGIN
  2358. 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]
  2359. END
  2360. ELSE IF @lpim = 1 AND CONVERT(DECIMAL(3,1), @winver) < 6.0 AND @arch = 64
  2361. BEGIN
  2362. 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]
  2363. END
  2364. ELSE IF @lpim = 1 AND CONVERT(DECIMAL(3,1), @winver) >= 6.0 AND @arch = 64
  2365. BEGIN
  2366. 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]
  2367. END
  2368. ELSE IF @lpim IS NULL
  2369. BEGIN
  2370. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[Could_not_retrieve_information]' AS [Deviation]
  2371. END
  2372. ELSE
  2373. BEGIN
  2374. SELECT 'Memory_checks' AS [Category], 'Locked_pages' AS [Check], '[Not_used]' AS [Deviation]
  2375. END;
  2376. --------------------------------------------------------------------------------------------------------------------------------
  2377. -- Pagefile subsection
  2378. --------------------------------------------------------------------------------------------------------------------------------
  2379. RAISERROR (N'|-Starting Pagefile Checks', 10, 1) WITH NOWAIT
  2380. DECLARE @pf_value tinyint--, @RegKey NVARCHAR(255)
  2381. DECLARE @pagefile bigint, @freepagefile bigint, @paged bigint
  2382. DECLARE @tbl_pf_value TABLE (Value VARCHAR(25), Data VARCHAR(50))
  2383. IF @sqlmajorver = 9
  2384. BEGIN
  2385. SET @sqlcmd = N'SELECT @pagefileOUT = (t1.record.value(''(./Record/MemoryRecord/TotalPageFile)[1]'', ''bigint'')-t1.record.value(''(./Record/MemoryRecord/TotalPhysicalMemory)[1]'', ''bigint''))/1024,
  2386. @freepagefileOUT = (t1.record.value(''(./Record/MemoryRecord/AvailablePageFile)[1]'', ''bigint'')-t1.record.value(''(./Record/MemoryRecord/AvailablePhysicalMemory)[1]'', ''bigint''))/1024,
  2387. @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
  2388. FROM (SELECT MAX([TIMESTAMP]) AS [TIMESTAMP], CONVERT(xml, record) AS record
  2389. FROM sys.dm_os_ring_buffers (NOLOCK)
  2390. WHERE ring_buffer_type = N''RING_BUFFER_RESOURCE_MONITOR''
  2391. AND record LIKE ''%RESOURCE_MEMPHYSICAL%''
  2392. GROUP BY record) AS t1';
  2393. END
  2394. ELSE
  2395. BEGIN
  2396. SET @sqlcmd = N'SELECT @pagefileOUT = (total_page_file_kb-total_physical_memory_kb)/1024,
  2397. @freepagefileOUT = (available_page_file_kb-available_physical_memory_kb)/1024,
  2398. @pagedOUT = ((total_page_file_kb-available_page_file_kb)/total_page_file_kb)
  2399. FROM sys.dm_os_sys_memory (NOLOCK)';
  2400. END
  2401. SET @params = N'@pagefileOUT bigint OUTPUT, @freepagefileOUT bigint OUTPUT, @pagedOUT bigint OUTPUT';
  2402. EXECUTE sp_executesql @sqlcmd, @params, @pagefileOUT=@pagefile OUTPUT, @freepagefileOUT=@freepagefile OUTPUT, @pagedOUT=@paged OUTPUT;
  2403. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1)
  2404. BEGIN
  2405. BEGIN TRY
  2406. SELECT @RegKey = N'System\CurrentControlSet\Control\Session Manager\Memory Management'
  2407. INSERT INTO @tbl_pf_value
  2408. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @RegKey, N'PagingFiles', NO_OUTPUT
  2409. END TRY
  2410. BEGIN CATCH
  2411. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2412. SELECT @ErrorMessage = 'Pagefile subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  2413. RAISERROR (@ErrorMessage, 16, 1);
  2414. END CATCH
  2415. END
  2416. ELSE
  2417. BEGIN
  2418. RAISERROR('[WARNING: Missing permissions for full "Pagefile" checks. Bypassing System managed pagefile check]', 16, 1, N'sysadmin')
  2419. --RETURN
  2420. END;
  2421. IF (SELECT COUNT(*) FROM @tbl_pf_value) > 0
  2422. BEGIN
  2423. SELECT @pf_value = CASE WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data = '') > 0 THEN 1
  2424. WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data = '?:\pagefile.sys') > 0 THEN 2
  2425. WHEN (SELECT COUNT(*) FROM @tbl_pf_value WHERE Data LIKE '%:\pagefile.sys 0 0%') > 0 THEN 3
  2426. ELSE 0 END
  2427. FROM @tbl_pf_value
  2428. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_management' AS [Check],
  2429. CASE WHEN @pf_value = 1 THEN '[WARNING: No pagefile is configured]'
  2430. WHEN @pf_value = 2 THEN '[WARNING: Pagefile is managed automatically on ALL drives]'
  2431. WHEN @pf_value = 3 THEN '[WARNING: Pagefile is managed automatically]'
  2432. ELSE '[OK]' END AS [Deviation]
  2433. END
  2434. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_free_space' AS [Check],
  2435. CASE WHEN @freepagefile <= 150 THEN '[WARNING: Pagefile free space is dangerously low. Please revise Pagefile settings]'
  2436. WHEN (@freepagefile*100)/@pagefile <= 10 THEN '[WARNING: Less than 10 percent of Pagefile is available. Please revise Pagefile settings]'
  2437. WHEN (@freepagefile*100)/@pagefile <= 30 THEN '[INFORMATION: Less than 30 percent of Pagefile is available]'
  2438. ELSE '[OK]' END AS [Deviation],
  2439. @pagefile AS total_pagefile_MB, @freepagefile AS available_pagefile_MB;
  2440. SELECT 'Pagefile_checks' AS [Category], 'Pagefile_minimum_size' AS [Check],
  2441. 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]'
  2442. 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]'
  2443. WHEN @winver <> '5.2' THEN '[NA]'
  2444. ELSE '[OK]' END AS [Deviation],
  2445. @pagefile AS total_pagefile_MB;
  2446. SELECT 'Pagefile_checks' AS [Category], 'Process_paged_out' AS [Check],
  2447. CASE WHEN @paged > 0 THEN '[WARNING: Part of SQL Server process memory has been paged out. Please revise LPIM settings]'
  2448. ELSE '[OK]' END AS [Deviation],
  2449. @paged AS paged_out_MB;
  2450. IF @ptochecks = 1
  2451. RAISERROR (N'|-Starting I/O Checks', 10, 1) WITH NOWAIT
  2452. --------------------------------------------------------------------------------------------------------------------------------
  2453. -- I/O stall in database files over 50% of cumulative sampled time or I/O latencies over 20ms in the last 5s subsection
  2454. -- io_stall refers to user processes waited for I/O. This number can be much greater than the sample_ms.
  2455. -- Might indicate that your I/O has insufficient service capabilities (HBA queue depths, reduced throughput, etc).
  2456. --------------------------------------------------------------------------------------------------------------------------------
  2457. IF @ptochecks = 1
  2458. BEGIN
  2459. RAISERROR (N' |-Starting I/O Stall subsection (wait for 5s)', 10, 1) WITH NOWAIT
  2460. DECLARE @mincol DATETIME, @maxcol DATETIME
  2461. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  2462. DROP TABLE #tmp_dm_io_virtual_file_stats;
  2463. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  2464. 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),
  2465. [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,
  2466. [num_of_bytes_written] bigint,[io_stall_write_ms] bigint,[io_stall] bigint,[size_on_disk_bytes] bigint,
  2467. CONSTRAINT PK_dm_io_virtual_file_stats PRIMARY KEY CLUSTERED(database_id, [file_id], [retrieval_time]));
  2468. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  2469. DROP TABLE #tblIOStall;
  2470. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  2471. CREATE TABLE #tblIOStall (database_id int, [file_id] int, [DBName] sysname, [logical_file_name] NVARCHAR(255), [type_desc] NVARCHAR(60),
  2472. [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,
  2473. 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,
  2474. avg_io_stall_write_pct int, cumulative_io_stall_write_pct int, cumulative_sample_HH int, io_stall_pct_of_cumulative_sample int,
  2475. CONSTRAINT PK_IOStall PRIMARY KEY CLUSTERED(database_id, [file_id]));
  2476. SELECT @mincol = GETDATE()
  2477. INSERT INTO #tmp_dm_io_virtual_file_stats
  2478. SELECT @mincol, f.database_id, f.[file_id], DB_NAME(f.database_id), f.name AS logical_file_name, f.type_desc,
  2479. CAST (CASE
  2480. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2481. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2482. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2483. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2484. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2485. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2486. ELSE f.physical_name
  2487. END AS NVARCHAR(255)) AS physical_location,
  2488. fs.[sample_ms],fs.[num_of_reads],fs.[num_of_bytes_read],fs.[io_stall_read_ms],fs.[num_of_writes],
  2489. fs.[num_of_bytes_written],fs.[io_stall_write_ms],fs.[io_stall],fs.[size_on_disk_bytes]
  2490. FROM sys.dm_io_virtual_file_stats (default, default) AS fs
  2491. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id]
  2492. WAITFOR DELAY '00:00:05' -- wait 5s between pooling
  2493. SELECT @maxcol = GETDATE()
  2494. INSERT INTO #tmp_dm_io_virtual_file_stats
  2495. SELECT @maxcol, f.database_id, f.[file_id], DB_NAME(f.database_id), f.name AS logical_file_name, f.type_desc,
  2496. CAST (CASE
  2497. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2498. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2499. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2500. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2501. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2502. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2503. ELSE f.physical_name
  2504. END AS NVARCHAR(255)) AS physical_location,
  2505. fs.[sample_ms],fs.[num_of_reads],fs.[num_of_bytes_read],fs.[io_stall_read_ms],fs.[num_of_writes],
  2506. fs.[num_of_bytes_written],fs.[io_stall_write_ms],fs.[io_stall],fs.[size_on_disk_bytes]
  2507. FROM sys.dm_io_virtual_file_stats (default, default) AS fs
  2508. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id]
  2509. ;WITH cteFileStats1 AS (SELECT database_id,[file_id],[DBName],[logical_file_name],[type_desc],
  2510. [physical_location],[sample_ms],[num_of_reads],[num_of_bytes_read],[io_stall_read_ms],[num_of_writes],
  2511. [num_of_bytes_written],[io_stall_write_ms],[io_stall],[size_on_disk_bytes]
  2512. FROM #tmp_dm_io_virtual_file_stats WHERE [retrieval_time] = @mincol),
  2513. cteFileStats2 AS (SELECT database_id,[file_id],[DBName],[logical_file_name],[type_desc],
  2514. [physical_location],[sample_ms],[num_of_reads],[num_of_bytes_read],[io_stall_read_ms],[num_of_writes],
  2515. [num_of_bytes_written],[io_stall_write_ms],[io_stall],[size_on_disk_bytes]
  2516. FROM #tmp_dm_io_virtual_file_stats WHERE [retrieval_time] = @maxcol)
  2517. INSERT INTO #tblIOStall
  2518. SELECT t1.database_id, t1.[file_id], t1.[DBName], t1.logical_file_name, t1.type_desc, t1.physical_location,
  2519. t1.size_on_disk_bytes/1024/1024 AS size_on_disk_Mbytes,
  2520. (t2.num_of_reads-t1.num_of_reads) AS num_of_reads,
  2521. (t2.num_of_writes-t1.num_of_writes) AS num_of_writes,
  2522. (t2.num_of_bytes_read-t1.num_of_bytes_read)/1024 AS num_of_KBytes_read,
  2523. (t2.num_of_bytes_written-t1.num_of_bytes_written)/1024 AS num_of_KBytes_written,
  2524. (t2.io_stall-t1.io_stall) AS io_stall_ms,
  2525. (t2.io_stall_read_ms-t1.io_stall_read_ms) AS io_stall_read_ms,
  2526. (t2.io_stall_write_ms-t1.io_stall_write_ms) AS io_stall_write_ms,
  2527. ((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,
  2528. ((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,
  2529. ((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,
  2530. ((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,
  2531. ((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,
  2532. ((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,
  2533. ABS((t2.sample_ms/1000)/60/60) AS cumulative_sample_HH,
  2534. ((t2.io_stall/1000/60)*100)/(ABS((t2.sample_ms/1000)/60)) AS io_stall_pct_of_cumulative_sample
  2535. FROM cteFileStats1 t1 INNER JOIN cteFileStats2 t2 ON t1.database_id = t2.database_id AND t1.[file_id] = t2.[file_id]
  2536. IF (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE avg_read_latency_ms >= 20) > 0
  2537. OR (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE avg_write_latency_ms >= 20) > 0
  2538. BEGIN
  2539. 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]
  2540. 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,
  2541. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2542. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2543. 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
  2544. FROM #tblIOStall
  2545. WHERE avg_read_latency_ms >= 20 OR avg_write_latency_ms >= 20
  2546. ORDER BY avg_read_latency_ms DESC, avg_write_latency_ms DESC, [DBName], [type_desc], [logical_file_name]
  2547. END
  2548. ELSE IF (SELECT COUNT([logical_file_name]) FROM #tblIOStall WHERE io_stall_pct_of_cumulative_sample > 50) > 0
  2549. BEGIN
  2550. 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]
  2551. SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Information], [DBName] AS [Database_Name], [logical_file_name], [type_desc], avg_read_latency_ms, avg_write_latency_ms,
  2552. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2553. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2554. avg_io_stall_read_pct, cumulative_io_stall_read_pct, avg_io_stall_write_pct, cumulative_io_stall_write_pct, cumulative_sample_HH, io_stall_pct_of_cumulative_sample
  2555. FROM #tblIOStall
  2556. WHERE io_stall_pct_of_cumulative_sample > 50
  2557. ORDER BY io_stall_pct_of_cumulative_sample DESC, [DBName], [type_desc], [logical_file_name]
  2558. END
  2559. ELSE
  2560. BEGIN
  2561. SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Check], '[OK]' AS [Deviation]
  2562. /*SELECT 'IO_checks' AS [Category], 'Stalled_IO' AS [Information], [DBName] AS [Database_Name], [logical_file_name], [type_desc], avg_read_latency_ms, avg_write_latency_ms,
  2563. [physical_location], size_on_disk_Mbytes, num_of_reads AS physical_reads, num_of_writes AS physical_writes,
  2564. num_of_KBytes_read, num_of_KBytes_written, io_stall_ms, io_stall_read_ms, io_stall_write_ms,
  2565. avg_io_stall_read_pct, cumulative_io_stall_read_pct, avg_io_stall_write_pct, cumulative_io_stall_write_pct, cumulative_sample_HH, io_stall_pct_of_cumulative_sample
  2566. FROM #tblIOStall
  2567. ORDER BY [DBName], [type_desc], [logical_file_name]*/
  2568. END;
  2569. END;
  2570. --------------------------------------------------------------------------------------------------------------------------------
  2571. -- Pending disk I/O Requests subsection
  2572. -- Indicate that your I/O has insufficient service capabilities (HBA queue depths, reduced throughput, etc).
  2573. --------------------------------------------------------------------------------------------------------------------------------
  2574. IF @ptochecks = 1
  2575. BEGIN
  2576. RAISERROR (N' |-Starting Pending disk I/O Requests subsection (wait for a max of 5s)', 10, 1) WITH NOWAIT
  2577. DECLARE @IOCnt tinyint
  2578. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  2579. DROP TABLE #tblPendingIOReq;
  2580. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  2581. 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));
  2582. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  2583. DROP TABLE #tblPendingIO;
  2584. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  2585. CREATE TABLE #tblPendingIO (database_id int, [file_id] int, [DBName] sysname, [logical_file_name] NVARCHAR(255), [type_desc] NVARCHAR(60),
  2586. [physical_location] NVARCHAR(260), io_stall_min int, io_stall_read_min int, io_stall_write_min int, avg_read_latency_ms int,
  2587. avg_write_latency_ms int, io_stall_read_pct int, io_stall_write_pct int, sampled_HH int,
  2588. 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),
  2589. scheduler_id int, pending_disk_io_count int, work_queue_count bigint);
  2590. SET @IOCnt = 1
  2591. WHILE @IOCnt < 5
  2592. BEGIN
  2593. INSERT INTO #tblPendingIOReq
  2594. SELECT io_completion_request_address, io_handle, io_type, io_pending, io_pending_ms_ticks, scheduler_address
  2595. FROM sys.dm_io_pending_io_requests;
  2596. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 1
  2597. BREAK
  2598. WAITFOR DELAY '00:00:01' -- wait 1s between pooling
  2599. SET @IOCnt = @IOCnt + 1
  2600. END;
  2601. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 0
  2602. BEGIN
  2603. INSERT INTO #tblPendingIO
  2604. 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,
  2605. CAST (CASE
  2606. -- Handle UNC paths (e.g. '\\fileserver\readonlydbs\dept_dw.ndf')
  2607. WHEN LEFT (LTRIM (f.physical_name), 2) = '\\'
  2608. THEN LEFT (LTRIM (f.physical_name),CHARINDEX('\',LTRIM(f.physical_name),CHARINDEX('\',LTRIM(f.physical_name), 3) + 1) - 1)
  2609. -- Handle local paths (e.g. 'C:\Program Files\...\master.mdf')
  2610. WHEN CHARINDEX('\', LTRIM(f.physical_name), 3) > 0
  2611. THEN UPPER(LEFT(LTRIM(f.physical_name), CHARINDEX ('\', LTRIM(f.physical_name), 3) - 1))
  2612. ELSE f.physical_name
  2613. END AS NVARCHAR(255)) AS physical_location,
  2614. fs.io_stall/1000/60 AS io_stall_min,
  2615. fs.io_stall_read_ms/1000/60 AS io_stall_read_min,
  2616. fs.io_stall_write_ms/1000/60 AS io_stall_write_min,
  2617. (fs.io_stall_read_ms / (1.0 + fs.num_of_reads)) AS avg_read_latency_ms,
  2618. (fs.io_stall_write_ms / (1.0 + fs.num_of_writes)) AS avg_write_latency_ms,
  2619. ((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,
  2620. ((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,
  2621. ABS((fs.sample_ms/1000)/60/60) AS 'sample_HH',
  2622. ((fs.io_stall/1000/60)*100)/(ABS((fs.sample_ms/1000)/60))AS 'io_stall_pct_of_overall_sample',
  2623. pio.io_completion_request_address, pio.io_handle, pio.io_type, pio.io_pending,
  2624. pio.io_pending_ms_ticks, pio.scheduler_address, os.scheduler_id, os.pending_disk_io_count, os.work_queue_count
  2625. FROM #tblPendingIOReq AS pio
  2626. INNER JOIN sys.dm_io_virtual_file_stats (NULL,NULL) AS fs ON fs.file_handle = pio.io_handle
  2627. INNER JOIN sys.dm_os_schedulers AS os ON pio.scheduler_address = os.scheduler_address
  2628. INNER JOIN sys.master_files AS f ON fs.database_id = f.database_id AND fs.[file_id] = f.[file_id];
  2629. END;
  2630. IF (SELECT COUNT(io_pending) FROM #tblPendingIOReq WHERE io_type = 'disk') > 0
  2631. BEGIN
  2632. 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]
  2633. 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,
  2634. 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,
  2635. io_completion_request_address, io_type, CASE WHEN io_pending = 1 THEN 'Pending_Context_Switching' ELSE 'Pending_WindowsOS' END AS io_pending_type,
  2636. io_pending_ms_ticks, scheduler_address, scheduler_id, pending_disk_io_count, work_queue_count
  2637. FROM #tblPendingIO
  2638. ORDER BY scheduler_address, [DBName], [type_desc], [logical_file_name]
  2639. END
  2640. ELSE
  2641. BEGIN
  2642. SELECT 'IO_checks' AS [Category], 'Pending_IO' AS [Check], '[OK]' AS [Deviation]
  2643. END;
  2644. END;
  2645. RAISERROR (N'|-Starting Server Checks', 10, 1) WITH NOWAIT
  2646. --------------------------------------------------------------------------------------------------------------------------------
  2647. -- Power plan subsection
  2648. --------------------------------------------------------------------------------------------------------------------------------
  2649. RAISERROR (N' |-Starting Power plan', 10, 1) WITH NOWAIT
  2650. DECLARE @planguid NVARCHAR(64), @powerkey NVARCHAR(255)
  2651. --SELECT @powerkey = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel\NameSpace\{025A5937-A6BE-4686-A844-36FE4BEC8B6D}'
  2652. --SELECT @powerkey = 'SYSTEM\CurrentControlSet\Control\Power\User\Default\PowerSchemes'
  2653. SELECT @powerkey = 'SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes'
  2654. IF CONVERT(DECIMAL(3,1), @winver) >= 6.0
  2655. BEGIN
  2656. BEGIN TRY
  2657. --EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @powerkey, 'PreferredPlan', @planguid OUTPUT, NO_OUTPUT
  2658. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @powerkey, 'ActivePowerScheme', @planguid OUTPUT, NO_OUTPUT
  2659. END TRY
  2660. BEGIN CATCH
  2661. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  2662. SELECT @ErrorMessage = 'Power plan subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  2663. RAISERROR (@ErrorMessage, 16, 1);
  2664. END CATCH
  2665. END
  2666. -- http://support.microsoft.com/kb/935799/en-us
  2667. IF @winver IS NULL
  2668. BEGIN
  2669. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Check], '[WARNING: Could not determine Windows version for check]' AS [Deviation]
  2670. END
  2671. ELSE IF @planguid IS NOT NULL AND @planguid <> '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
  2672. BEGIN
  2673. 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]
  2674. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Information], CASE WHEN @planguid = '381b4222-f694-41f0-9685-ff5bb260df2e' THEN 'Balanced'
  2675. WHEN @planguid = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c' THEN 'High Performance'
  2676. WHEN @planguid = 'a1841308-3541-4fab-bc81-f71556f20b4a' THEN 'Power Saver'
  2677. ELSE 'Other' END AS [Power_Plan]
  2678. END
  2679. ELSE IF @planguid IS NOT NULL AND @planguid = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
  2680. BEGIN
  2681. SELECT 'Server_checks' AS [Category], 'Current_Power_Plan' AS [Check], '[OK]' AS [Deviation]
  2682. END;
  2683. --------------------------------------------------------------------------------------------------------------------------------
  2684. -- Disk Partition alignment offset < 64KB subsection
  2685. --------------------------------------------------------------------------------------------------------------------------------
  2686. RAISERROR (N' |-Starting Disk Partition alignment offset < 64KB', 10, 1) WITH NOWAIT
  2687. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  2688. BEGIN
  2689. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2690. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2691. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  2692. AND (SELECT COUNT(l.name)
  2693. FROM sys.server_permissions p JOIN sys.server_principals l
  2694. ON p.grantee_principal_id = l.principal_id
  2695. AND p.class = 100 -- Server
  2696. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  2697. AND l.is_disabled = 0
  2698. AND p.permission_name = 'ALTER SETTINGS'
  2699. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  2700. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2701. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  2702. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  2703. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  2704. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  2705. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  2706. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  2707. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  2708. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  2709. BEGIN
  2710. DECLARE @diskpart int
  2711. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  2712. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  2713. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  2714. RAISERROR (' |-Configuration options set for Disk partition alignment offset check', 10, 1) WITH NOWAIT
  2715. IF @sao = 0
  2716. BEGIN
  2717. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  2718. END
  2719. IF @xcmd = 0
  2720. BEGIN
  2721. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  2722. END
  2723. IF @ole = 0
  2724. BEGIN
  2725. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  2726. END
  2727. DECLARE @output_hw_tot_diskpart TABLE ([PS_OUTPUT] VARCHAR(2048));
  2728. DECLARE @output_hw_format_diskpart TABLE ([volid] smallint IDENTITY(1,1), [HD_Partition] VARCHAR(50) NULL, StartingOffset bigint NULL)
  2729. IF @custompath IS NULL
  2730. BEGIN
  2731. IF @sqlmajorver < 11
  2732. BEGIN
  2733. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  2734. SET @path = @path + '\LOG'
  2735. END
  2736. ELSE
  2737. BEGIN
  2738. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  2739. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  2740. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  2741. END
  2742. -- Create COM object with FSO
  2743. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  2744. IF @OLEResult <> 0
  2745. BEGIN
  2746. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2747. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2748. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2749. END
  2750. ELSE
  2751. BEGIN
  2752. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  2753. IF @OLEResult <> 0
  2754. BEGIN
  2755. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2756. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  2757. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2758. END
  2759. ELSE
  2760. BEGIN
  2761. IF @existout <> 1
  2762. BEGIN
  2763. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  2764. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  2765. END
  2766. END
  2767. EXEC @OLEResult = sp_OADestroy @FSO
  2768. END
  2769. END
  2770. ELSE
  2771. BEGIN
  2772. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  2773. END
  2774. SET @FileName = @path + '\checkbp_diskpart_' + RTRIM(@server) + '.ps1'
  2775. EXEC master.dbo.xp_fileexist @FileName, @existout out
  2776. IF @existout = 0
  2777. BEGIN -- Scan for local disks
  2778. SET @Text1 = '[string] $serverName = ''localhost''
  2779. $partitions = Get-WmiObject -computername $serverName -query "SELECT * FROM Win32_DiskPartition"
  2780. foreach ($partition in $partitions)
  2781. {
  2782. [string] $diskpart = "{0}_{1};{2}" -f $partition.DiskIndex,$partition.Index,$partition.StartingOffset
  2783. Write-Output $diskpart
  2784. }
  2785. '
  2786. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  2787. IF @OLEResult <> 0
  2788. BEGIN
  2789. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2790. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2791. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2792. END
  2793. --Open file
  2794. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  2795. IF @OLEResult <> 0
  2796. BEGIN
  2797. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2798. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  2799. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2800. END
  2801. ELSE
  2802. BEGIN
  2803. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  2804. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  2805. END
  2806. --Write Text1
  2807. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  2808. IF @OLEResult <> 0
  2809. BEGIN
  2810. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2811. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  2812. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2813. END
  2814. EXEC @OLEResult = sp_OADestroy @FileID
  2815. EXEC @OLEResult = sp_OADestroy @FS
  2816. END
  2817. ELSE
  2818. BEGIN
  2819. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  2820. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  2821. END
  2822. IF @psver = 1
  2823. BEGIN
  2824. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  2825. END
  2826. ELSE
  2827. BEGIN
  2828. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  2829. END;
  2830. INSERT INTO @output_hw_tot_diskpart
  2831. EXEC master.dbo.xp_cmdshell @CMD
  2832. SET @CMD = 'del /Q "' + @FileName + '"'
  2833. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  2834. INSERT INTO @output_hw_format_diskpart ([HD_Partition],StartingOffset)
  2835. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  2836. 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)
  2837. FROM @output_hw_tot_diskpart
  2838. WHERE [PS_OUTPUT] IS NOT NULL;
  2839. SET @CMD2 = 'del ' + @FileName
  2840. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  2841. IF @xcmd = 0
  2842. BEGIN
  2843. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  2844. END
  2845. IF @ole = 0
  2846. BEGIN
  2847. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  2848. END
  2849. IF @sao = 0
  2850. BEGIN
  2851. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  2852. END;
  2853. ;WITH diskpartcte (StartingOffset) AS (
  2854. SELECT StartingOffset
  2855. FROM @output_hw_format_diskpart
  2856. WHERE StartingOffset IS NOT NULL OR LEN(StartingOffset) > 0)
  2857. SELECT @diskpart = CASE WHEN (SELECT COUNT(*) FROM diskpartcte) = 0 THEN NULL ELSE COUNT(cte1.[StartingOffset]) END
  2858. FROM diskpartcte cte1
  2859. WHERE cte1.[StartingOffset] < 65536;
  2860. IF @diskpart > 0 AND @diskpart IS NOT NULL
  2861. BEGIN
  2862. 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]
  2863. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Information], LEFT(t1.[HD_Partition],LEN(t1.[HD_Partition])-CHARINDEX('_',t1.[HD_Partition])) AS HD_Volume,
  2864. RIGHT(t1.[HD_Partition],LEN(t1.[HD_Partition])-CHARINDEX('_',t1.[HD_Partition])) AS [HD_Partition],
  2865. (t1.StartingOffset/1024) AS [StartingOffset_KB]
  2866. FROM @output_hw_format_diskpart t1
  2867. WHERE t1.StartingOffset IS NOT NULL OR LEN(t1.StartingOffset) > 0
  2868. ORDER BY t1.[HD_Partition]
  2869. OPTION (RECOMPILE);
  2870. END
  2871. ELSE IF @diskpart IS NULL
  2872. BEGIN
  2873. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Check], '[WARNING: Could not gather information on disk partition offset size]' AS [Deviation]
  2874. END
  2875. ELSE
  2876. BEGIN
  2877. SELECT 'Server_checks' AS [Category], 'Partition_Alignment' AS [Check], '[OK]' AS [Deviation]
  2878. END;
  2879. END
  2880. ELSE
  2881. BEGIN
  2882. 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')
  2883. 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')
  2884. --RETURN
  2885. END
  2886. END
  2887. ELSE
  2888. BEGIN
  2889. 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')
  2890. --RETURN
  2891. END;
  2892. --------------------------------------------------------------------------------------------------------------------------------
  2893. -- NTFS block size in volumes that hold database files <> 64KB subsection
  2894. --------------------------------------------------------------------------------------------------------------------------------
  2895. RAISERROR (N' |-Starting NTFS block size in volumes that hold database files <> 64KB', 10, 1) WITH NOWAIT
  2896. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  2897. BEGIN
  2898. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  2899. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2900. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  2901. AND (SELECT COUNT(l.name)
  2902. FROM sys.server_permissions p JOIN sys.server_principals l
  2903. ON p.grantee_principal_id = l.principal_id
  2904. AND p.class = 100 -- Server
  2905. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  2906. AND l.is_disabled = 0
  2907. AND p.permission_name = 'ALTER SETTINGS'
  2908. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  2909. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  2910. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  2911. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  2912. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  2913. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  2914. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  2915. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  2916. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  2917. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  2918. BEGIN
  2919. DECLARE @ntfs int
  2920. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  2921. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  2922. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  2923. RAISERROR (' |-Configuration options set for NTFS Block size check', 10, 1) WITH NOWAIT
  2924. IF @sao = 0
  2925. BEGIN
  2926. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  2927. END
  2928. IF @xcmd = 0
  2929. BEGIN
  2930. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  2931. END
  2932. IF @ole = 0
  2933. BEGIN
  2934. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  2935. END
  2936. DECLARE @output_hw_tot_ntfs TABLE ([PS_OUTPUT] VARCHAR(2048));
  2937. DECLARE @output_hw_format_ntfs TABLE ([volid] smallint IDENTITY(1,1), [HD_Volume] NVARCHAR(2048) NULL, [NTFS_Block] NVARCHAR(8) NULL)
  2938. IF @custompath IS NULL
  2939. BEGIN
  2940. IF @sqlmajorver < 11
  2941. BEGIN
  2942. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  2943. SET @path = @path + '\LOG'
  2944. END
  2945. ELSE
  2946. BEGIN
  2947. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  2948. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  2949. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  2950. END
  2951. -- Create COM object with FSO
  2952. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  2953. IF @OLEResult <> 0
  2954. BEGIN
  2955. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2956. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2957. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2958. END
  2959. ELSE
  2960. BEGIN
  2961. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  2962. IF @OLEResult <> 0
  2963. BEGIN
  2964. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  2965. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  2966. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  2967. END
  2968. ELSE
  2969. BEGIN
  2970. IF @existout <> 1
  2971. BEGIN
  2972. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  2973. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  2974. END
  2975. END
  2976. EXEC @OLEResult = sp_OADestroy @FSO
  2977. END
  2978. END
  2979. ELSE
  2980. BEGIN
  2981. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  2982. END
  2983. SET @FileName = @path + '\checkbp_ntfs_' + RTRIM(@server) + '.ps1'
  2984. EXEC master.dbo.xp_fileexist @FileName, @existout out
  2985. IF @existout = 0
  2986. BEGIN -- Scan for local disks
  2987. SET @Text1 = '[string] $serverName = ''localhost''
  2988. $vols = Get-WmiObject -computername $serverName -query "select name, blocksize from Win32_Volume where Capacity <> NULL and DriveType = 3"
  2989. foreach($vol in $vols)
  2990. {
  2991. [string] $drive = "{0};{1}" -f $vol.name,$vol.blocksize
  2992. Write-Output $drive
  2993. } '
  2994. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  2995. IF @OLEResult <> 0
  2996. BEGIN
  2997. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  2998. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  2999. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3000. END
  3001. --Open file
  3002. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3003. IF @OLEResult <> 0
  3004. BEGIN
  3005. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3006. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3007. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3008. END
  3009. ELSE
  3010. BEGIN
  3011. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3012. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3013. END
  3014. --Write Text1
  3015. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3016. IF @OLEResult <> 0
  3017. BEGIN
  3018. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3019. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3020. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3021. END
  3022. EXEC @OLEResult = sp_OADestroy @FileID
  3023. EXEC @OLEResult = sp_OADestroy @FS
  3024. END
  3025. ELSE
  3026. BEGIN
  3027. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3028. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3029. END
  3030. IF @psver = 1
  3031. BEGIN
  3032. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3033. END
  3034. ELSE
  3035. BEGIN
  3036. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3037. END;
  3038. INSERT INTO @output_hw_tot_ntfs
  3039. EXEC master.dbo.xp_cmdshell @CMD
  3040. SET @CMD = 'del /Q "' + @FileName + '"'
  3041. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3042. INSERT INTO @output_hw_format_ntfs ([HD_Volume],[NTFS_Block])
  3043. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3044. 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)
  3045. FROM @output_hw_tot_ntfs
  3046. WHERE [PS_OUTPUT] IS NOT NULL;
  3047. SET @CMD2 = 'del ' + @FileName
  3048. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3049. IF @xcmd = 0
  3050. BEGIN
  3051. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3052. END
  3053. IF @ole = 0
  3054. BEGIN
  3055. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3056. END
  3057. IF @sao = 0
  3058. BEGIN
  3059. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3060. END;
  3061. WITH ntfscte (physical_name, ntfsblock) AS (
  3062. SELECT DISTINCT(LEFT(physical_name, LEN(t2.HD_Volume))), [NTFS_Block]
  3063. FROM sys.master_files t1 INNER JOIN @output_hw_format_ntfs t2
  3064. ON LEFT(physical_name, LEN(t2.HD_Volume)) = t2.HD_Volume
  3065. WHERE [database_id] <> 32767 AND (t2.[NTFS_Block] IS NOT NULL OR LEN(t2.[NTFS_Block]) > 0)
  3066. )
  3067. SELECT @ntfs = CASE WHEN (SELECT COUNT(*) FROM ntfscte) = 0 THEN NULL ELSE COUNT(cte1.[ntfsblock]) END
  3068. FROM ntfscte cte1
  3069. WHERE cte1.[ntfsblock] <> 65536;
  3070. IF @ntfs > 0 AND @ntfs IS NOT NULL
  3071. BEGIN
  3072. 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]
  3073. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Information], t1.HD_Volume, (t1.[NTFS_Block]/1024) AS [NTFS_Block_Size_KB]
  3074. FROM (SELECT DISTINCT(LEFT(physical_name, LEN(t2.HD_Volume))) AS [HD_Volume], [NTFS_Block]
  3075. FROM sys.master_files t1 (NOLOCK) 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)) t1
  3078. ORDER BY t1.HD_Volume OPTION (RECOMPILE);
  3079. END
  3080. ELSE IF @ntfs IS NULL
  3081. BEGIN
  3082. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Check], '[WARNING: Could not gather information on NTFS block size]' AS [Deviation]
  3083. END
  3084. ELSE
  3085. BEGIN
  3086. SELECT 'Server_checks' AS [Category], 'NTFS_Block_Size' AS [Check], '[OK]' AS [Deviation]
  3087. END;
  3088. END
  3089. ELSE
  3090. BEGIN
  3091. 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')
  3092. 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')
  3093. --RETURN
  3094. END
  3095. END
  3096. ELSE
  3097. BEGIN
  3098. 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')
  3099. --RETURN
  3100. END;
  3101. --------------------------------------------------------------------------------------------------------------------------------
  3102. -- Disk Fragmentation Analysis subsection
  3103. --------------------------------------------------------------------------------------------------------------------------------
  3104. IF @diskfrag = 1
  3105. BEGIN
  3106. RAISERROR (N' |-Starting Disk Fragmentation Analysis', 10, 1) WITH NOWAIT
  3107. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  3108. BEGIN
  3109. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3110. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3111. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  3112. AND (SELECT COUNT(l.name)
  3113. FROM sys.server_permissions p JOIN sys.server_principals l
  3114. ON p.grantee_principal_id = l.principal_id
  3115. AND p.class = 100 -- Server
  3116. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  3117. AND l.is_disabled = 0
  3118. AND p.permission_name = 'ALTER SETTINGS'
  3119. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  3120. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3121. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  3122. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  3123. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  3124. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  3125. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  3126. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  3127. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  3128. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  3129. BEGIN
  3130. DECLARE @frag int
  3131. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3132. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3133. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  3134. RAISERROR (' |-Configuration options set for Disk Fragmentation Analysis', 10, 1) WITH NOWAIT
  3135. IF @sao = 0
  3136. BEGIN
  3137. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3138. END
  3139. IF @xcmd = 0
  3140. BEGIN
  3141. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3142. END
  3143. IF @ole = 0
  3144. BEGIN
  3145. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  3146. END
  3147. DECLARE @output_hw_frag TABLE ([PS_OUTPUT] VARCHAR(2048));
  3148. DECLARE @output_hw_format_frag TABLE ([volid] smallint IDENTITY(1,1), [volfrag] VARCHAR(255), [fragrec] VARCHAR(10) NULL)
  3149. IF @custompath IS NULL
  3150. BEGIN
  3151. IF @sqlmajorver < 11
  3152. BEGIN
  3153. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  3154. SET @path = @path + '\LOG'
  3155. END
  3156. ELSE
  3157. BEGIN
  3158. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  3159. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  3160. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  3161. END
  3162. -- Create COM object with FSO
  3163. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  3164. IF @OLEResult <> 0
  3165. BEGIN
  3166. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3167. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3168. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3169. END
  3170. ELSE
  3171. BEGIN
  3172. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  3173. IF @OLEResult <> 0
  3174. BEGIN
  3175. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3176. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  3177. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3178. END
  3179. ELSE
  3180. BEGIN
  3181. IF @existout <> 1
  3182. BEGIN
  3183. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  3184. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  3185. END
  3186. END
  3187. EXEC @OLEResult = sp_OADestroy @FSO
  3188. END
  3189. END
  3190. ELSE
  3191. BEGIN
  3192. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  3193. END
  3194. SET @FileName = @path + '\checkbp_frag_' + RTRIM(@server) + '.ps1'
  3195. EXEC master.dbo.xp_fileexist @FileName, @existout out
  3196. IF @existout = 0
  3197. BEGIN -- Scan for frag
  3198. SET @Text1 = '$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
  3199. $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
  3200. $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
  3201. if ($myWindowsPrincipal.IsInRole($adminRole))
  3202. {
  3203. [string] $serverName = ''localhost''
  3204. $DiskResults = @()
  3205. $objDisks = Get-WmiObject -Computername $serverName -Class Win32_Volume | Where-Object { $_.DriveType -eq 3 -and $_.Name -like "*:\"}
  3206. ForEach( $disk in $objDisks)
  3207. {
  3208. $objDefrag = $disk.DefragAnalysis()
  3209. $rec = $objDefrag.DefragRecommended
  3210. $objDefragDetail = $objDefrag.DefragAnalysis
  3211. $diskFragmentation = $objDefragDetail.TotalPercentFragmentation
  3212. $FreeFragmentation = $objDefragDetail.FreeSpacePercentFragmentation
  3213. $FileFragmentation = $objDefragDetail.FilePercentFragmentation
  3214. [string] $ThisVolume = "{0}TotalFragPct {1} :: FreeSpaceFragPct {2} :: FileFragPct {3};{4}" -f $($disk.Name),$diskFragmentation,$FreeFragmentation,$FileFragmentation,$rec
  3215. $DiskResults += $ThisVolume
  3216. }
  3217. $DiskResults
  3218. }
  3219. else
  3220. {
  3221. Write-Host "NotAdmin"
  3222. }
  3223. '
  3224. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3225. IF @OLEResult <> 0
  3226. BEGIN
  3227. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3228. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3229. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3230. END
  3231. --Open file
  3232. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3233. IF @OLEResult <> 0
  3234. BEGIN
  3235. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3236. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3237. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3238. END
  3239. ELSE
  3240. BEGIN
  3241. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3242. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3243. END
  3244. --Write Text1
  3245. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3246. IF @OLEResult <> 0
  3247. BEGIN
  3248. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3249. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3250. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3251. END
  3252. EXEC @OLEResult = sp_OADestroy @FileID
  3253. EXEC @OLEResult = sp_OADestroy @FS
  3254. END
  3255. ELSE
  3256. BEGIN
  3257. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3258. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3259. END
  3260. RAISERROR (' |-Getting Disk(s) Fragmentation. This may take some time...', 10, 1) WITH NOWAIT
  3261. IF @psver = 1
  3262. BEGIN
  3263. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3264. END
  3265. ELSE
  3266. BEGIN
  3267. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3268. END;
  3269. INSERT INTO @output_hw_frag
  3270. EXEC master.dbo.xp_cmdshell @CMD
  3271. SET @CMD = 'del /Q "' + @FileName + '"'
  3272. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3273. IF (SELECT COUNT([PS_OUTPUT]) FROM @output_hw_frag WHERE [PS_OUTPUT] LIKE '%NotAdmin%') = 1
  3274. BEGIN
  3275. RAISERROR ('[WARNING: Powershell not running under Elevated Privileges. Bypassing Disk Fragmentation Analysis]',16,1);
  3276. END
  3277. ELSE
  3278. BEGIN
  3279. INSERT INTO @output_hw_format_frag ([volfrag],fragrec)
  3280. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3281. 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)
  3282. FROM @output_hw_frag
  3283. WHERE [PS_OUTPUT] IS NOT NULL
  3284. END
  3285. SET @CMD2 = 'del ' + @FileName
  3286. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3287. IF @xcmd = 0
  3288. BEGIN
  3289. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3290. END
  3291. IF @ole = 0
  3292. BEGIN
  3293. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3294. END
  3295. IF @sao = 0
  3296. BEGIN
  3297. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3298. END;
  3299. ;WITH fragcte (fragrec) AS (
  3300. SELECT fragrec
  3301. FROM @output_hw_format_frag
  3302. WHERE fragrec IS NOT NULL OR LEN(fragrec) > 0)
  3303. SELECT @frag = CASE WHEN (SELECT COUNT(*) FROM fragcte) = 0 THEN NULL ELSE COUNT(cte1.[fragrec]) END
  3304. FROM fragcte cte1
  3305. WHERE cte1.[fragrec] = 'True';
  3306. IF @frag > 0 AND @frag IS NOT NULL
  3307. BEGIN
  3308. 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]
  3309. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Information],
  3310. LEFT(t1.[volfrag],1) AS HD_Volume,
  3311. RIGHT(t1.[volfrag],(LEN(t1.[volfrag])-3)) AS [Fragmentation_Percent],
  3312. t1.fragrec AS [Defragmentation_Recommended]
  3313. FROM @output_hw_format_frag t1
  3314. WHERE t1.fragrec = 'True'
  3315. ORDER BY t1.[volfrag]
  3316. OPTION (RECOMPILE);
  3317. END
  3318. ELSE IF @frag IS NULL
  3319. BEGIN
  3320. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Check], '[WARNING: Could not gather information on Disk Fragmentation Analysis]' AS [Deviation]
  3321. END
  3322. ELSE
  3323. BEGIN
  3324. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Check], '[OK]' AS [Deviation]
  3325. SELECT 'Server_checks' AS [Category], 'Disk_Fragmentation' AS [Information],
  3326. LEFT(t1.[volfrag],1) AS HD_Volume,
  3327. RIGHT(t1.[volfrag],(LEN(t1.[volfrag])-3)) AS [Fragmentation_Percent],
  3328. t1.fragrec AS [Defragmentation_Recommended]
  3329. FROM @output_hw_format_frag t1
  3330. ORDER BY t1.[volfrag]
  3331. OPTION (RECOMPILE);
  3332. END;
  3333. END
  3334. ELSE
  3335. BEGIN
  3336. 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')
  3337. 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')
  3338. --RETURN
  3339. END
  3340. END
  3341. ELSE
  3342. BEGIN
  3343. 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')
  3344. --RETURN
  3345. END
  3346. END
  3347. ELSE
  3348. BEGIN
  3349. RAISERROR(' |- [INFORMATION: "Disk Fragmentation Analysis" check is disabled]', 10, 1, N'disallow_diskfrag')
  3350. --RETURN
  3351. END;
  3352. --------------------------------------------------------------------------------------------------------------------------------
  3353. -- Cluster Quorum Model subsection
  3354. --------------------------------------------------------------------------------------------------------------------------------
  3355. IF @clustered = 1 AND @winver <> '5.2'
  3356. BEGIN
  3357. RAISERROR (N' |-Starting Cluster Quorum Model', 10, 1) WITH NOWAIT
  3358. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted')) AND @psver > 1
  3359. BEGIN
  3360. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3361. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3362. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  3363. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3364. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  3365. BEGIN
  3366. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3367. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3368. RAISERROR (' |-Configuration options set for Cluster Quorum Model check', 10, 1) WITH NOWAIT
  3369. IF @sao = 0
  3370. BEGIN
  3371. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3372. END
  3373. IF @xcmd = 0
  3374. BEGIN
  3375. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3376. END
  3377. DECLARE /*@CMD NVARCHAR(4000), @line int, @linemax int, */ @CntNodes tinyint, @CntVotes tinyint
  3378. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  3379. DROP TABLE #xp_cmdshell_CluNodesOutput;
  3380. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  3381. CREATE TABLE #xp_cmdshell_CluNodesOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(50));
  3382. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  3383. DROP TABLE #xp_cmdshell_CluOutput;
  3384. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  3385. CREATE TABLE #xp_cmdshell_CluOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(50));
  3386. IF @winver <> '5.2'
  3387. BEGIN
  3388. SELECT @CMD = N'powershell -NoLogo -NoProfile "Import-Module FailoverClusters"; "Get-ClusterNode | Format-Table -Autosize -HideTableHeaders NodeWeight"'
  3389. INSERT INTO #xp_cmdshell_CluNodesOutput ([Output])
  3390. EXEC master.dbo.xp_cmdshell @CMD;
  3391. END
  3392. SELECT @CMD = N'powershell -NoLogo -NoProfile "Import-Module FailoverClusters"; "Get-ClusterQuorum | Format-Table -Autosize -HideTableHeaders QuorumType"'
  3393. INSERT INTO #xp_cmdshell_CluOutput ([Output])
  3394. EXEC master.dbo.xp_cmdshell @CMD;
  3395. IF (SELECT COUNT([Output]) FROM #xp_cmdshell_CluNodesOutput WHERE [Output] = '') > 0
  3396. BEGIN
  3397. SELECT @CntNodes = COUNT(NodeName) FROM sys.dm_os_cluster_nodes (NOLOCK)
  3398. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check],
  3399. CASE WHEN REPLACE([Output], CHAR(9), '') = 'DiskOnly' AND @winver <> '5.2' THEN '[WARNING: The current quorum model is not recommended since WS2003]'
  3400. 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]'
  3401. 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]'
  3402. WHEN REPLACE([Output], CHAR(9), '') = 'NodeAndFileShareMajority' THEN '[INFORMATION: The current quorum model is recommended for clusters with special configurations]'
  3403. ELSE '[OK]' END AS [Deviation],
  3404. QUOTENAME(REPLACE([Output], CHAR(9), '')) AS QuorumModel,
  3405. '[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
  3406. FROM #xp_cmdshell_CluOutput WHERE [Output] IS NOT NULL
  3407. END
  3408. ELSE
  3409. BEGIN
  3410. SELECT @CntVotes = SUM(CONVERT(int, [Output])) FROM #xp_cmdshell_CluNodesOutput WHERE [Output] IS NOT NULL
  3411. IF EXISTS (SELECT TOP 1 [Output] FROM #xp_cmdshell_CluOutput WHERE [Output] LIKE '%Majority%' OR [Output] LIKE '%Disk%')
  3412. BEGIN
  3413. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check],
  3414. CASE WHEN REPLACE([Output], CHAR(9), '') = 'DiskOnly' AND @winver <> '5.2' THEN '[WARNING: The current quorum model is not recommended since WS2003]'
  3415. 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]'
  3416. 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]'
  3417. WHEN REPLACE([Output], CHAR(9), '') = 'NodeAndFileShareMajority' THEN '[INFORMATION: The current quorum model is recommended for clusters with special configurations]'
  3418. ELSE '[OK]' END AS [Deviation],
  3419. QUOTENAME(REPLACE([Output], CHAR(9), '')) AS QuorumModel
  3420. FROM #xp_cmdshell_CluOutput WHERE [Output] IS NOT NULL
  3421. END
  3422. END
  3423. IF @xcmd = 0
  3424. BEGIN
  3425. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3426. END
  3427. IF @sao = 0
  3428. BEGIN
  3429. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3430. END
  3431. END
  3432. ELSE
  3433. BEGIN
  3434. 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')
  3435. 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')
  3436. --RETURN
  3437. END
  3438. END
  3439. ELSE IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted')) AND @psver = 1
  3440. BEGIN
  3441. RAISERROR(' |- [INFORMATION: "Cluster Quorum Model" check was skipped: cannot execute with PS v1]', 10, 1, N'disallow_ps')
  3442. --RETURN
  3443. END
  3444. ELSE
  3445. BEGIN
  3446. 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')
  3447. --RETURN
  3448. END
  3449. END
  3450. ELSE
  3451. BEGIN
  3452. SELECT 'Server_checks' AS [Category], 'Cluster_Quorum' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3453. END;
  3454. IF @IsHadrEnabled = 1
  3455. BEGIN
  3456. SET @sqlcmd = N'DECLARE @winver VARCHAR(5), @CntNodes tinyint
  3457. SELECT @winver = windows_release FROM sys.dm_os_windows_info (NOLOCK)
  3458. SELECT @CntNodes = SUM(number_of_quorum_votes) FROM sys.dm_hadr_cluster_members (NOLOCK)
  3459. SELECT ''Server_checks'' AS [Category], ''AlwaysOn_Cluster_Quorum'' AS [Check], cluster_name,
  3460. CASE WHEN quorum_type = 3 AND @winver <> ''5.2'' THEN ''[WARNING: The current quorum model is not recommended since WS2003]''
  3461. 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]''
  3462. 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]''
  3463. WHEN quorum_type = 2 THEN ''[INFORMATION: The current quorum model is recommended for clusters with special configurations]''
  3464. ELSE ''[OK]'' END AS [Deviation],
  3465. QUOTENAME(quorum_type_desc) AS QuorumModel
  3466. FROM sys.dm_hadr_cluster;'
  3467. EXECUTE sp_executesql @sqlcmd
  3468. END;
  3469. --------------------------------------------------------------------------------------------------------------------------------
  3470. -- Cluster NIC Binding order subsection
  3471. --------------------------------------------------------------------------------------------------------------------------------
  3472. IF @allow_xpcmdshell = 1 and @clustered = 1
  3473. BEGIN
  3474. RAISERROR (N' |-Starting Cluster NIC Binding order', 10, 1) WITH NOWAIT
  3475. IF @allow_xpcmdshell = 1 AND (@psavail IS NOT NULL AND @psavail IN ('RemoteSigned','Unrestricted'))
  3476. BEGIN
  3477. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3478. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3479. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  3480. AND (SELECT COUNT(l.name)
  3481. FROM sys.server_permissions p JOIN sys.server_principals l
  3482. ON p.grantee_principal_id = l.principal_id
  3483. AND p.class = 100 -- Server
  3484. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  3485. AND l.is_disabled = 0
  3486. AND p.permission_name = 'ALTER SETTINGS'
  3487. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  3488. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3489. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  3490. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  3491. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  3492. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  3493. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  3494. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  3495. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  3496. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  3497. BEGIN
  3498. DECLARE @clunic int, @maxnic int
  3499. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3500. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3501. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  3502. RAISERROR (' |-Configuration options set for Cluster NIC Binding Order check', 10, 1) WITH NOWAIT
  3503. IF @sao = 0
  3504. BEGIN
  3505. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3506. END
  3507. IF @xcmd = 0
  3508. BEGIN
  3509. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3510. END
  3511. IF @ole = 0
  3512. BEGIN
  3513. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  3514. END
  3515. DECLARE @output_hw_nics TABLE ([PS_OUTPUT] VARCHAR(2048));
  3516. DECLARE @output_hw_format_nics TABLE ([nicid] smallint, [nicname] VARCHAR(255) NULL)
  3517. IF @custompath IS NULL
  3518. BEGIN
  3519. IF @sqlmajorver < 11
  3520. BEGIN
  3521. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  3522. SET @path = @path + '\LOG'
  3523. END
  3524. ELSE
  3525. BEGIN
  3526. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  3527. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  3528. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  3529. END
  3530. -- Create COM object with FSO
  3531. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  3532. IF @OLEResult <> 0
  3533. BEGIN
  3534. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3535. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3536. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3537. END
  3538. ELSE
  3539. BEGIN
  3540. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  3541. IF @OLEResult <> 0
  3542. BEGIN
  3543. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  3544. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  3545. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3546. END
  3547. ELSE
  3548. BEGIN
  3549. IF @existout <> 1
  3550. BEGIN
  3551. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  3552. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  3553. END
  3554. END
  3555. EXEC @OLEResult = sp_OADestroy @FSO
  3556. END
  3557. END
  3558. ELSE
  3559. BEGIN
  3560. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  3561. END
  3562. SET @FileName = @path + '\checkbp_nics_' + RTRIM(@server) + '.ps1'
  3563. EXEC master.dbo.xp_fileexist @FileName, @existout out
  3564. IF @existout = 0
  3565. BEGIN -- Scan for nics
  3566. SET @Text1 = '[string] $serverName = ''localhost''
  3567. $nics = Get-WmiObject -Computername $serverName -query "SELECT Description, Index FROM Win32_NetworkAdapterConfiguration"
  3568. foreach ($nic in $nics)
  3569. {
  3570. [string] $allnics = "{0};{1}" -f $nic.Index,$nic.Description
  3571. Write-Output $allnics
  3572. }
  3573. '
  3574. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  3575. IF @OLEResult <> 0
  3576. BEGIN
  3577. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3578. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  3579. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3580. END
  3581. --Open file
  3582. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  3583. IF @OLEResult <> 0
  3584. BEGIN
  3585. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3586. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  3587. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3588. END
  3589. ELSE
  3590. BEGIN
  3591. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  3592. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3593. END
  3594. --Write Text1
  3595. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  3596. IF @OLEResult <> 0
  3597. BEGIN
  3598. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  3599. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  3600. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  3601. END
  3602. EXEC @OLEResult = sp_OADestroy @FileID
  3603. EXEC @OLEResult = sp_OADestroy @FS
  3604. END
  3605. ELSE
  3606. BEGIN
  3607. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  3608. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  3609. END
  3610. IF @psver = 1
  3611. BEGIN
  3612. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3613. END
  3614. ELSE
  3615. BEGIN
  3616. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  3617. END;
  3618. INSERT INTO @output_hw_nics
  3619. EXEC master.dbo.xp_cmdshell @CMD
  3620. SET @CMD = 'del /Q "' + @FileName + '"'
  3621. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  3622. INSERT INTO @output_hw_format_nics ([nicid],nicname)
  3623. SELECT LEFT(RTRIM([PS_OUTPUT]), CASE WHEN CHARINDEX(';', RTRIM([PS_OUTPUT])) = 0 THEN LEN(RTRIM([PS_OUTPUT])) ELSE CHARINDEX(';', RTRIM([PS_OUTPUT]))-1 END),
  3624. 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)
  3625. FROM @output_hw_nics
  3626. WHERE [PS_OUTPUT] IS NOT NULL;
  3627. SET @CMD2 = 'del ' + @FileName
  3628. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  3629. IF @xcmd = 0
  3630. BEGIN
  3631. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3632. END
  3633. IF @ole = 0
  3634. BEGIN
  3635. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  3636. END
  3637. IF @sao = 0
  3638. BEGIN
  3639. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3640. END;
  3641. SELECT @maxnic = MAX(nicid) FROM @output_hw_format_nics;
  3642. SELECT TOP 1 @clunic = nicid FROM @output_hw_format_nics WHERE nicname LIKE '%Cluster Virtual Adapter%';
  3643. IF @clunic < @maxnic OR @clunic IS NULL --http://support2.microsoft.com/kb/955963
  3644. BEGIN
  3645. 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]
  3646. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Information], nicid AS NIC_ID, nicname AS NIC_Name
  3647. FROM @output_hw_format_nics t1
  3648. ORDER BY t1.[nicid]
  3649. OPTION (RECOMPILE);
  3650. END
  3651. ELSE IF @clunic = @maxnic
  3652. BEGIN
  3653. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], '[OK]' AS [Deviation]
  3654. END
  3655. ELSE
  3656. BEGIN
  3657. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], '[WARNING: Could not gather information on NIC binding order]' AS [Deviation]
  3658. END;
  3659. END
  3660. ELSE
  3661. BEGIN
  3662. 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')
  3663. 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')
  3664. --RETURN
  3665. END
  3666. END
  3667. ELSE
  3668. BEGIN
  3669. 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')
  3670. --RETURN
  3671. END
  3672. END
  3673. ELSE
  3674. BEGIN
  3675. SELECT 'Server_checks' AS [Category], 'Cluster_NIC_Binding' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3676. END;
  3677. --------------------------------------------------------------------------------------------------------------------------------
  3678. -- Cluster QFE node equality subsection
  3679. --------------------------------------------------------------------------------------------------------------------------------
  3680. IF @clustered = 1
  3681. BEGIN
  3682. RAISERROR (N' |-Starting QFE node equality', 10, 1) WITH NOWAIT
  3683. IF @allow_xpcmdshell = 1
  3684. BEGIN
  3685. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  3686. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3687. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  3688. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  3689. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  3690. BEGIN
  3691. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  3692. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  3693. RAISERROR (' |-Configuration options set for QFE node equality check', 10, 1) WITH NOWAIT
  3694. IF @sao = 0
  3695. BEGIN
  3696. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  3697. END
  3698. IF @xcmd = 0
  3699. BEGIN
  3700. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  3701. END
  3702. DECLARE /* @CMD NVARCHAR(4000), @line int, @linemax int, */ @Node VARCHAR(50)
  3703. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  3704. DROP TABLE #xp_cmdshell_Nodes;
  3705. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  3706. CREATE TABLE #xp_cmdshell_Nodes (NodeName VARCHAR(50), isdone bit NOT NULL);
  3707. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  3708. DROP TABLE #xp_cmdshell_QFEOutput;
  3709. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  3710. CREATE TABLE #xp_cmdshell_QFEOutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR(150));
  3711. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  3712. DROP TABLE #xp_cmdshell_QFEFinal;
  3713. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  3714. CREATE TABLE #xp_cmdshell_QFEFinal (NodeName VARCHAR(50), [QFE] VARCHAR(150));
  3715. INSERT INTO #xp_cmdshell_Nodes
  3716. SELECT NodeName, 0 FROM sys.dm_os_cluster_nodes (NOLOCK);
  3717. WHILE (SELECT COUNT(NodeName) FROM #xp_cmdshell_Nodes WHERE isdone = 0) > 0
  3718. BEGIN
  3719. SELECT TOP 1 @Node = NodeName FROM #xp_cmdshell_Nodes WHERE isdone = 0;
  3720. SET @CMD = 'wmic /node:"' + @Node + '" qfe get hotfixid'
  3721. INSERT INTO #xp_cmdshell_QFEOutput ([Output])
  3722. EXEC master.dbo.xp_cmdshell @CMD;
  3723. IF (SELECT COUNT([Output]) FROM #xp_cmdshell_QFEOutput WHERE [Output] LIKE '%Access is denied%') = 0
  3724. BEGIN
  3725. INSERT INTO #xp_cmdshell_QFEFinal
  3726. SELECT @Node, RTRIM(REPLACE([Output],CHAR(13),'')) FROM #xp_cmdshell_QFEOutput WHERE RTRIM(REPLACE([Output],CHAR(13),'')) NOT IN ('','HotFixID');
  3727. END
  3728. ELSE
  3729. BEGIN
  3730. SET @ErrorMessage = '[WARNING: Access Denied error while trying to get updates from node ' + @Node + ']'
  3731. RAISERROR (@ErrorMessage,16,1);
  3732. END;
  3733. TRUNCATE TABLE #xp_cmdshell_QFEOutput;
  3734. UPDATE #xp_cmdshell_Nodes
  3735. SET isdone = 1
  3736. WHERE NodeName = @Node;
  3737. END;
  3738. IF (SELECT COUNT(DISTINCT NodeName) FROM #xp_cmdshell_QFEFinal) = (SELECT COUNT(DISTINCT NodeName) FROM #xp_cmdshell_Nodes)
  3739. BEGIN
  3740. 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
  3741. BEGIN
  3742. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], '[WARNING: Missing updates found in some of the nodes]' AS [Deviation]
  3743. SELECT t1.NodeName, t1.[QFE] AS MissingUpdates FROM #xp_cmdshell_QFEFinal t1
  3744. WHERE t1.[QFE] NOT IN (SELECT DISTINCT t2.[QFE] FROM #xp_cmdshell_QFEFinal t2 WHERE t2.NodeName <> t1.NodeName);
  3745. END
  3746. ELSE
  3747. BEGIN
  3748. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], '[OK]' AS [Deviation];
  3749. SELECT DISTINCT t1.[QFE] AS InstalledUpdates FROM #xp_cmdshell_QFEFinal t1;
  3750. END
  3751. END
  3752. ELSE
  3753. BEGIN
  3754. RAISERROR ('[WARNING: Could not collect data from all cluster nodes. Bypassing QFE node equality check]',16,1);
  3755. END
  3756. IF @xcmd = 0
  3757. BEGIN
  3758. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  3759. END
  3760. IF @sao = 0
  3761. BEGIN
  3762. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  3763. END
  3764. END
  3765. ELSE
  3766. BEGIN
  3767. 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')
  3768. 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')
  3769. --RETURN
  3770. END
  3771. END
  3772. ELSE
  3773. BEGIN
  3774. RAISERROR(' |- [INFORMATION: "QFE node equality" check was skipped because xp_cmdshell was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  3775. --RETURN
  3776. END
  3777. END
  3778. ELSE
  3779. BEGIN
  3780. SELECT 'Server_checks' AS [Category], 'Cluster_QFE_Equality' AS [Check], 'NOT_CLUSTERED' AS [Deviation]
  3781. END;
  3782. RAISERROR (N'|-Starting Service Accounts Checks', 10, 1) WITH NOWAIT
  3783. --------------------------------------------------------------------------------------------------------------------------------
  3784. -- Service Accounts Status subsection
  3785. --------------------------------------------------------------------------------------------------------------------------------
  3786. RAISERROR (N' |-Starting Service Accounts Status', 10, 1) WITH NOWAIT
  3787. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1)
  3788. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') = 1 AND
  3789. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_servicecontrol') = 1)
  3790. BEGIN
  3791. DECLARE @rc int, @profile NVARCHAR(128)
  3792. DECLARE @sqlservice NVARCHAR(128), @sqlagentservice NVARCHAR(128), @dtsservice NVARCHAR(128), @ftservice NVARCHAR(128)
  3793. DECLARE @browservice NVARCHAR(128), @olapservice NVARCHAR(128), @rsservice NVARCHAR(128)
  3794. DECLARE @statussqlservice NVARCHAR(20), @statussqlagentservice NVARCHAR(20), @statusdtsservice NVARCHAR(20), @statusftservice NVARCHAR(20)
  3795. DECLARE @statusbrowservice NVARCHAR(20), @statusolapservice NVARCHAR(20), @statusrsservice NVARCHAR(20)
  3796. DECLARE @regkeysqlservice NVARCHAR(256), @regkeysqlagentservice NVARCHAR(256), @regkeydtsservice NVARCHAR(256), @regkeyftservice NVARCHAR(256)
  3797. DECLARE @regkeybrowservice NVARCHAR(256), @regkeyolapservice NVARCHAR(256), @regkeyrsservice NVARCHAR(256)
  3798. DECLARE @accntsqlservice NVARCHAR(128), @accntsqlagentservice NVARCHAR(128), @accntdtsservice NVARCHAR(128), @accntftservice NVARCHAR(128)
  3799. DECLARE @accntbrowservice NVARCHAR(128), @accntolapservice NVARCHAR(128), @accntrsservice NVARCHAR(128)
  3800. -- Get service names
  3801. IF (@instancename IS NULL)
  3802. BEGIN
  3803. IF @sqlmajorver < 11
  3804. BEGIN
  3805. SELECT @sqlservice = N'MSSQLServer'
  3806. SELECT @sqlagentservice = N'SQLServerAgent'
  3807. END
  3808. SELECT @olapservice = N'MSSQLServerOLAPService'
  3809. SELECT @rsservice = N'ReportServer'
  3810. END
  3811. ELSE
  3812. BEGIN
  3813. IF @sqlmajorver < 11
  3814. BEGIN
  3815. SELECT @sqlservice = N'MSSQL$' + @instancename
  3816. SELECT @sqlagentservice = N'SQLAgent$' + @instancename
  3817. END
  3818. SELECT @olapservice = N'MSOLAP$' + @instancename
  3819. SELECT @rsservice = N'ReportServer$' + @instancename
  3820. END
  3821. IF @sqlmajorver = 9
  3822. BEGIN
  3823. SELECT @dtsservice = N'MsDtsServer'
  3824. END
  3825. ELSE
  3826. BEGIN
  3827. SELECT @dtsservice = N'MsDtsServer' + CONVERT(VARCHAR, @sqlmajorver) + '0'
  3828. END
  3829. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3830. BEGIN
  3831. IF (@instancename IS NULL) AND @sqlmajorver = 10
  3832. BEGIN
  3833. SELECT @ftservice = N'MSSQLFDLauncher'
  3834. END
  3835. ELSE IF (@instancename IS NOT NULL) AND @sqlmajorver = 10
  3836. BEGIN
  3837. SELECT @ftservice = N'MSSQLFDLauncher$' + @instancename
  3838. END
  3839. ELSE IF (@instancename IS NULL) AND @sqlmajorver = 9
  3840. BEGIN
  3841. SELECT @ftservice = N'msftesql'
  3842. END
  3843. ELSE IF (@instancename IS NOT NULL) AND @sqlmajorver = 9
  3844. BEGIN
  3845. SELECT @ftservice = N'msftesql$' + @instancename
  3846. END
  3847. END
  3848. SELECT @browservice = N'SQLBrowser'
  3849. IF @sqlmajorver < 11
  3850. BEGIN
  3851. SELECT @regkeysqlservice = N'SYSTEM\CurrentControlSet\Services\' + @sqlservice
  3852. SELECT @regkeysqlagentservice = N'SYSTEM\CurrentControlSet\Services\' + @sqlagentservice
  3853. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3854. BEGIN
  3855. SELECT @regkeyftservice = N'SYSTEM\CurrentControlSet\Services\' + @ftservice
  3856. END
  3857. END
  3858. SELECT @regkeyolapservice = N'SYSTEM\CurrentControlSet\Services\' + @olapservice
  3859. SELECT @regkeyrsservice = N'SYSTEM\CurrentControlSet\Services\' + @rsservice
  3860. SELECT @regkeydtsservice = N'SYSTEM\CurrentControlSet\Services\' + @dtsservice
  3861. SELECT @regkeybrowservice = N'SYSTEM\CurrentControlSet\Services\' + @browservice
  3862. -- Service status
  3863. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#RegResult'))
  3864. CREATE TABLE #RegResult (ResultValue bit)
  3865. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ServiceStatus'))
  3866. CREATE TABLE #ServiceStatus (ServiceStatus VARCHAR(128))
  3867. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3868. BEGIN
  3869. BEGIN TRY
  3870. INSERT INTO #RegResult (ResultValue)
  3871. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlservice
  3872. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3873. BEGIN
  3874. INSERT INTO #ServiceStatus (ServiceStatus)
  3875. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @sqlservice
  3876. SELECT @statussqlservice = ServiceStatus FROM #ServiceStatus
  3877. TRUNCATE TABLE #ServiceStatus;
  3878. END
  3879. ELSE
  3880. BEGIN
  3881. SET @statussqlservice = 'Not Installed'
  3882. END
  3883. TRUNCATE TABLE #RegResult;
  3884. END TRY
  3885. BEGIN CATCH
  3886. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3887. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  3888. RAISERROR (@ErrorMessage, 16, 1);
  3889. END CATCH
  3890. END
  3891. ELSE
  3892. BEGIN
  3893. SET @sqlcmd = N'SELECT @statussqlserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server%'' AND servicename NOT LIKE ''SQL Server Agent%''';
  3894. SET @params = N'@statussqlserviceOUT NVARCHAR(20) OUTPUT';
  3895. EXECUTE sp_executesql @sqlcmd, @params, @statussqlserviceOUT=@statussqlservice OUTPUT;
  3896. IF @statussqlservice IS NULL
  3897. BEGIN
  3898. SET @statussqlservice = 'Not Installed'
  3899. END
  3900. END
  3901. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3902. BEGIN
  3903. BEGIN TRY
  3904. INSERT INTO #RegResult (ResultValue)
  3905. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlagentservice
  3906. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3907. BEGIN
  3908. INSERT INTO #ServiceStatus (ServiceStatus)
  3909. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @sqlagentservice
  3910. SELECT @statussqlagentservice = ServiceStatus FROM #ServiceStatus
  3911. TRUNCATE TABLE #ServiceStatus;
  3912. END
  3913. ELSE
  3914. BEGIN
  3915. SET @statussqlagentservice = 'Not Installed'
  3916. END
  3917. TRUNCATE TABLE #RegResult;
  3918. END TRY
  3919. BEGIN CATCH
  3920. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3921. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  3922. RAISERROR (@ErrorMessage, 16, 1);
  3923. END CATCH
  3924. END
  3925. ELSE
  3926. BEGIN
  3927. SET @sqlcmd = N'SELECT @statussqlagentserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server Agent%''';
  3928. SET @params = N'@statussqlagentserviceOUT NVARCHAR(20) OUTPUT';
  3929. EXECUTE sp_executesql @sqlcmd, @params, @statussqlagentserviceOUT=@statussqlagentservice OUTPUT;
  3930. IF @statussqlagentservice IS NULL
  3931. BEGIN
  3932. SET @statussqlagentservice = 'Not Installed'
  3933. END
  3934. END
  3935. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  3936. BEGIN
  3937. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  3938. BEGIN
  3939. BEGIN TRY
  3940. INSERT INTO #RegResult (ResultValue)
  3941. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyftservice
  3942. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3943. BEGIN
  3944. INSERT INTO #ServiceStatus (ServiceStatus)
  3945. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @ftservice
  3946. SELECT @statusftservice = ServiceStatus FROM #ServiceStatus
  3947. TRUNCATE TABLE #ServiceStatus;
  3948. END
  3949. ELSE
  3950. BEGIN
  3951. SET @statusftservice = '[INFORMATION: Service is not installed]'
  3952. END
  3953. TRUNCATE TABLE #RegResult;
  3954. END TRY
  3955. BEGIN CATCH
  3956. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3957. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  3958. RAISERROR (@ErrorMessage, 16, 1);
  3959. END CATCH
  3960. END
  3961. END
  3962. ELSE
  3963. BEGIN
  3964. SET @sqlcmd = N'SELECT @statusftserviceOUT = status_desc FROM sys.dm_server_services WHERE servicename LIKE ''SQL Full-text Filter Daemon Launcher%''';
  3965. SET @params = N'@statusftserviceOUT NVARCHAR(20) OUTPUT';
  3966. EXECUTE sp_executesql @sqlcmd, @params, @statusftserviceOUT=@statusftservice OUTPUT;
  3967. IF @statusftservice IS NULL
  3968. BEGIN
  3969. SET @statusftservice = '[INFORMATION: Service is not installed]'
  3970. END
  3971. END
  3972. BEGIN TRY
  3973. INSERT INTO #RegResult (ResultValue)
  3974. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyolapservice
  3975. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3976. BEGIN
  3977. INSERT INTO #ServiceStatus (ServiceStatus)
  3978. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @olapservice
  3979. SELECT @statusolapservice = ServiceStatus FROM #ServiceStatus
  3980. TRUNCATE TABLE #ServiceStatus;
  3981. END
  3982. ELSE
  3983. BEGIN
  3984. SET @statusolapservice = 'Not Installed'
  3985. END
  3986. TRUNCATE TABLE #RegResult;
  3987. END TRY
  3988. BEGIN CATCH
  3989. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  3990. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 4. ' + ERROR_MESSAGE()
  3991. RAISERROR (@ErrorMessage, 16, 1);
  3992. END CATCH
  3993. BEGIN TRY
  3994. INSERT INTO #RegResult (ResultValue)
  3995. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyrsservice
  3996. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  3997. BEGIN
  3998. INSERT INTO #ServiceStatus (ServiceStatus)
  3999. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @rsservice
  4000. SELECT @statusrsservice = ServiceStatus FROM #ServiceStatus
  4001. TRUNCATE TABLE #ServiceStatus;
  4002. END
  4003. ELSE
  4004. BEGIN
  4005. SET @statusrsservice = 'Not Installed'
  4006. END
  4007. TRUNCATE TABLE #RegResult;
  4008. END TRY
  4009. BEGIN CATCH
  4010. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4011. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 5. ' + ERROR_MESSAGE()
  4012. RAISERROR (@ErrorMessage, 16, 1);
  4013. END CATCH
  4014. BEGIN TRY
  4015. INSERT INTO #RegResult (ResultValue)
  4016. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeydtsservice
  4017. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4018. BEGIN
  4019. INSERT INTO #ServiceStatus (ServiceStatus)
  4020. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @dtsservice
  4021. SELECT @statusdtsservice = ServiceStatus FROM #ServiceStatus
  4022. TRUNCATE TABLE #ServiceStatus;
  4023. END
  4024. ELSE
  4025. BEGIN
  4026. SET @statusdtsservice = 'Not Installed'
  4027. END
  4028. TRUNCATE TABLE #RegResult;
  4029. END TRY
  4030. BEGIN CATCH
  4031. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4032. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 6. ' + ERROR_MESSAGE()
  4033. RAISERROR (@ErrorMessage, 16, 1);
  4034. END CATCH
  4035. BEGIN TRY
  4036. INSERT INTO #RegResult (ResultValue)
  4037. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeybrowservice
  4038. IF (SELECT TOP 1 ResultValue FROM #RegResult) = 1
  4039. BEGIN
  4040. INSERT INTO #ServiceStatus (ServiceStatus)
  4041. EXEC master.sys.xp_servicecontrol N'QUERYSTATE', @browservice
  4042. SELECT @statusbrowservice = ServiceStatus FROM #ServiceStatus
  4043. TRUNCATE TABLE #ServiceStatus;
  4044. END
  4045. ELSE
  4046. BEGIN
  4047. SET @statusbrowservice = 'Not Installed'
  4048. END
  4049. END TRY
  4050. BEGIN CATCH
  4051. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4052. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 7. ' + ERROR_MESSAGE()
  4053. RAISERROR (@ErrorMessage, 16, 1);
  4054. END CATCH
  4055. DROP TABLE #RegResult;
  4056. DROP TABLE #ServiceStatus;
  4057. -- Accounts
  4058. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500)
  4059. BEGIN
  4060. BEGIN TRY
  4061. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlservice, N'ObjectName', @accntsqlservice OUTPUT, NO_OUTPUT
  4062. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeysqlagentservice, N'ObjectName', @accntsqlagentservice OUTPUT, NO_OUTPUT
  4063. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyftservice, N'ObjectName', @accntftservice OUTPUT, NO_OUTPUT
  4064. END TRY
  4065. BEGIN CATCH
  4066. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4067. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 8. ' + ERROR_MESSAGE()
  4068. RAISERROR (@ErrorMessage, 16, 1);
  4069. END CATCH
  4070. END
  4071. ELSE
  4072. BEGIN
  4073. BEGIN TRY
  4074. SET @sqlcmd = N'SELECT @accntsqlserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server%'' AND servicename NOT LIKE ''SQL Server Agent%''';
  4075. SET @params = N'@accntsqlserviceOUT NVARCHAR(128) OUTPUT';
  4076. EXECUTE sp_executesql @sqlcmd, @params, @accntsqlserviceOUT=@accntsqlservice OUTPUT;
  4077. SET @sqlcmd = N'SELECT @accntsqlagentserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Server Agent%''';
  4078. SET @params = N'@accntsqlagentserviceOUT NVARCHAR(128) OUTPUT';
  4079. EXECUTE sp_executesql @sqlcmd, @params, @accntsqlagentserviceOUT=@accntsqlagentservice OUTPUT;
  4080. SET @sqlcmd = N'SELECT @accntftserviceOUT = service_account FROM sys.dm_server_services WHERE servicename LIKE ''SQL Full-text Filter Daemon Launcher%''';
  4081. SET @params = N'@accntftserviceOUT NVARCHAR(128) OUTPUT';
  4082. EXECUTE sp_executesql @sqlcmd, @params, @accntftserviceOUT=@accntftservice OUTPUT;
  4083. END TRY
  4084. BEGIN CATCH
  4085. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4086. SELECT @ErrorMessage = 'Service Accounts and Status subsection - Error raised in TRY block 9. ' + ERROR_MESSAGE()
  4087. RAISERROR (@ErrorMessage, 16, 1);
  4088. END CATCH
  4089. END
  4090. BEGIN TRY
  4091. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyolapservice, N'ObjectName', @accntolapservice OUTPUT, NO_OUTPUT
  4092. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeyrsservice, N'ObjectName', @accntrsservice OUTPUT, NO_OUTPUT
  4093. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeydtsservice, N'ObjectName', @accntdtsservice OUTPUT, NO_OUTPUT
  4094. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', @regkeybrowservice, N'ObjectName', @accntbrowservice OUTPUT, NO_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 10. ' + ERROR_MESSAGE()
  4099. RAISERROR (@ErrorMessage, 16, 1);
  4100. END CATCH
  4101. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server' AS [Service], @statussqlservice AS [Status], @accntsqlservice AS [Account],
  4102. CASE WHEN @statussqlservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4103. WHEN @statussqlservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4104. WHEN @accntsqlservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4105. WHEN @accntsqlservice = 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4106. WHEN @clustered = 1 AND @accntsqlservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4107. WHEN @clustered = 1 AND @accntsqlservice = 'LocalSystem' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4108. WHEN @clustered = 1 AND @accntsqlservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server under this account is not supported]'
  4109. WHEN @clustered = 0 AND @accntsqlservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4110. WHEN @clustered = 0 AND @accntsqlservice = 'LocalSystem' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4111. WHEN @clustered = 0 AND @accntsqlservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server under this account is not recommended]'
  4112. -- 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)
  4113. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) >= 6.1 AND @accntsqlservice <> 'NT SERVICE\MSSQLSERVER' AND @accntsqlservice NOT LIKE 'NT SERVICE\MSSQL$%' THEN '[INFORMATION: SQL Server is not running with the default account]'
  4114. ELSE '[OK]'
  4115. END AS [Deviation]
  4116. UNION ALL
  4117. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Agent' AS [Service], @statussqlagentservice AS [Status], @accntsqlagentservice AS [Account],
  4118. CASE WHEN @statussqlagentservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4119. WHEN @statussqlagentservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4120. WHEN @accntsqlagentservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4121. WHEN @accntsqlagentservice = 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4122. WHEN @accntsqlagentservice = @accntsqlservice THEN '[WARNING: Running SQL Server Agent under the same account as SQL Server is not recommended]'
  4123. WHEN @clustered = 1 AND @accntsqlagentservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4124. WHEN @clustered = 1 AND @accntsqlagentservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not supported]'
  4125. WHEN @clustered = 0 AND @accntsqlagentservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running SQL Server Agent under this account is not recommended]'
  4126. WHEN @clustered = 0 AND @accntsqlagentservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running SQL Server Agent under this account is not recommended]'
  4127. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4128. -- 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)
  4129. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) >= 6.1 AND @accntsqlagentservice <> 'NT SERVICE\SQLSERVERAGENT' AND @accntsqlagentservice NOT LIKE 'NT SERVICE\SQLAGENT$%' THEN '[INFORMATION: SQL Server Agent is not running with the default account]'
  4130. ELSE '[OK]'
  4131. END AS [Deviation]
  4132. UNION ALL
  4133. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Analysis_Services' AS [Service], @statusolapservice AS [Status], @accntolapservice AS [Account],
  4134. CASE WHEN @statusolapservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4135. WHEN @statusolapservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4136. WHEN @accntolapservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4137. WHEN @accntolapservice = @accntsqlservice THEN '[WARNING: Running SQL Server Analysis Services under the same account as SQL Server is not recommended]'
  4138. 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]'
  4139. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4140. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) <= 6.0 AND @accntolapservice <> 'NT AUTHORITY\NETWORKSERVICE' THEN '[INFORMATION: SQL Server Analysis Services is not running with the default account]'
  4141. -- 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)
  4142. WHEN @clustered = 0 AND @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) >= 6.1 AND @accntolapservice <> 'NT SERVICE\MSSQLServerOLAPService' AND @accntolapservice NOT LIKE 'NT SERVICE\MSOLAP$%' THEN '[INFORMATION: SQL Server Analysis Services is not running with the default account]'
  4143. ELSE '[OK]'
  4144. END AS [Deviation]
  4145. UNION ALL
  4146. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Integration_Services' AS [Service], @statusdtsservice AS [Status], @accntdtsservice AS [Account],
  4147. CASE WHEN @statusdtsservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4148. WHEN @statusdtsservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4149. WHEN @accntdtsservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4150. WHEN @accntdtsservice = @accntsqlservice THEN '[WARNING: Running SQL Server Integration Services under the same account as SQL Server is not recommended]'
  4151. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4152. WHEN CONVERT(DECIMAL(3,1), @winver) <= 6.0 AND @accntdtsservice <> 'NT AUTHORITY\NETWORKSERVICE' AND @accntdtsservice <> 'NT AUTHORITY\LOCALSYSTEM' THEN '[INFORMATION: SQL Server Integration Services is not running with the default account]'
  4153. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4154. WHEN @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) >= 6.1 AND @accntdtsservice NOT IN ('NT SERVICE\MSDTSSERVER100', 'NT SERVICE\MSDTSSERVER110') THEN '[INFORMATION: SQL Server Integration Services is not running with the default account]'
  4155. ELSE '[OK]'
  4156. END AS [Deviation]
  4157. UNION ALL
  4158. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Reporting_Services' AS [Service], @statusrsservice AS [Status], @accntrsservice AS [Account],
  4159. CASE WHEN @statusrsservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4160. WHEN @statusrsservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4161. WHEN @accntrsservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4162. WHEN @accntrsservice = @accntsqlservice THEN '[WARNING: Running SQL Server Reporting Services under the same account as SQL Server is not recommended]'
  4163. 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]'
  4164. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4165. WHEN @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) <= 6.0 AND @accntrsservice <> 'NT AUTHORITY\NETWORKSERVICE' THEN '[INFORMATION: SQL Server Reporting Services is not running with the default account]'
  4166. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4167. WHEN @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) >= 6.1 AND @accntrsservice <> 'NT SERVICE\ReportServer' AND @accntrsservice NOT LIKE 'NT SERVICE\ReportServer$%' THEN '[INFORMATION: SQL Server Reporting Services is not running with the default account]'
  4168. ELSE '[OK]'
  4169. END AS [Deviation]
  4170. UNION ALL
  4171. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'Full-Text' AS [Service], ISNULL(@statusftservice, 'Not Installed') AS [Status], ISNULL(@accntftservice,'') AS [Account],
  4172. CASE WHEN (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1 THEN
  4173. CASE WHEN @statusftservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4174. WHEN @statusftservice LIKE 'Stopped%' THEN '[WARNING: Service is stopped]'
  4175. WHEN @accntftservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4176. WHEN @accntftservice = @accntsqlservice THEN '[WARNING: Running Full-Text Daemon under the same account as SQL Server is not recommended]'
  4177. WHEN @accntftservice = 'NT AUTHORITY\SYSTEM' THEN '[WARNING: Running Full-Text Service under this account is not recommended]'
  4178. WHEN @winver IS NULL THEN '[WARNING: Could not determine Windows version for check]'
  4179. WHEN @sqlmajorver <= 10 AND @accntftservice = 'NT AUTHORITY\NETWORKSERVICE' THEN '[WARNING: Running Full-Text Service under this account is not recommended]'
  4180. WHEN @sqlmajorver <= 10 AND @accntftservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4181. WHEN @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) <= 6.0 AND @accntftservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4182. -- MSA for WS2008R2 or higher, SQL Server 2012 or higher (http://msdn.microsoft.com/en-us/library/ms143504(v=SQL.110).aspx#Default_Accts)
  4183. WHEN @sqlmajorver >= 11 AND CONVERT(DECIMAL(3,1), @winver) >= 6.1 AND @accntftservice <> 'NT SERVICE\MSSQLFDLauncher' AND @accntftservice NOT LIKE 'NT SERVICE\MSSQLFDLauncher$%' THEN '[WARNING: Full-Text Daemon is not running with the default account]'
  4184. ELSE '[OK]' END
  4185. ELSE '[INFORMATION: Service is not installed]'
  4186. END AS [Deviation]
  4187. UNION ALL
  4188. SELECT 'Service_Account_checks' AS [Category], 'Service_Status' AS [Check], 'SQL_Server_Browser' AS [Service], @statusbrowservice AS [Status], @accntbrowservice AS [Account],
  4189. CASE WHEN @statusbrowservice = 'Not Installed' THEN '[INFORMATION: Service is not installed]'
  4190. WHEN @statusbrowservice LIKE 'Stopped%' AND @instancename IS NOT NULL THEN '[WARNING: Service is stopped on a named instance]'
  4191. WHEN @statusbrowservice LIKE 'Stopped%' AND @instancename IS NULL THEN '[WARNING: Service is stopped]'
  4192. WHEN @accntbrowservice IS NULL THEN '[WARNING: Could not detect account for check]'
  4193. WHEN @accntbrowservice = @accntsqlservice THEN '[WARNING: Running SQL Server Browser under the same account as SQL Server is not recommended]'
  4194. WHEN @accntbrowservice <> 'NT AUTHORITY\LOCALSERVICE' THEN '[WARNING: SQL Server Browser is not running with the default account]'
  4195. ELSE '[OK]'
  4196. END AS [Deviation];
  4197. END
  4198. ELSE
  4199. BEGIN
  4200. 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')
  4201. --RETURN
  4202. END;
  4203. --------------------------------------------------------------------------------------------------------------------------------
  4204. -- Service Accounts and SPN registration subsection
  4205. --------------------------------------------------------------------------------------------------------------------------------
  4206. RAISERROR (N' |-Starting Service Accounts and SPN registration', 10, 1) WITH NOWAIT
  4207. 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
  4208. BEGIN
  4209. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  4210. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  4211. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  4212. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  4213. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  4214. BEGIN
  4215. RAISERROR (' |-Configuration options set for SPN check', 10, 1) WITH NOWAIT
  4216. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  4217. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  4218. IF @sao = 0
  4219. BEGIN
  4220. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  4221. END
  4222. IF @xcmd = 0
  4223. BEGIN
  4224. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  4225. END
  4226. BEGIN TRY
  4227. DECLARE /*@CMD NVARCHAR(4000),*/ @line int, @linemax int, @SPN VARCHAR(8000), @SPNMachine VARCHAR(8000)
  4228. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  4229. DROP TABLE #xp_cmdshell_AcctSPNoutput;
  4230. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  4231. CREATE TABLE #xp_cmdshell_AcctSPNoutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR (8000));
  4232. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  4233. DROP TABLE #xp_cmdshell_DupSPNoutput;
  4234. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  4235. CREATE TABLE #xp_cmdshell_DupSPNoutput (line int IDENTITY(1,1) PRIMARY KEY, [Output] VARCHAR (8000));
  4236. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  4237. DROP TABLE #FinalDupSPN;
  4238. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  4239. CREATE TABLE #FinalDupSPN ([SPN] VARCHAR (8000), [Accounts] VARCHAR (8000));
  4240. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  4241. DROP TABLE #ScopedDupSPN;
  4242. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  4243. CREATE TABLE #ScopedDupSPN ([SPN] VARCHAR (8000), [Accounts] VARCHAR (8000));
  4244. SELECT @CMD = N'SETSPN -P -L ' + @accntsqlservice
  4245. INSERT INTO #xp_cmdshell_AcctSPNoutput ([Output])
  4246. EXEC master.dbo.xp_cmdshell @CMD;
  4247. SET @CMD = N'SETSPN -P -X'
  4248. INSERT INTO #xp_cmdshell_DupSPNoutput ([Output])
  4249. EXEC master.dbo.xp_cmdshell @CMD;
  4250. SELECT @SPNMachine = '%MSSQLSvc/' + CONVERT(NVARCHAR(100),SERVERPROPERTY('MachineName')) + '%';
  4251. 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]),' ', ''))))
  4252. BEGIN
  4253. 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%'
  4254. OPEN curSPN
  4255. FETCH NEXT FROM curSPN INTO @line, @SPN
  4256. WHILE @@FETCH_STATUS = 0
  4257. BEGIN
  4258. SELECT TOP 1 @linemax = line FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND [Output] IS NULL;
  4259. INSERT INTO #FinalDupSPN
  4260. SELECT QUOTENAME(@SPN), QUOTENAME(REPLACE([Output], CHAR(9), '')) FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND line < @linemax;
  4261. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_DupSPNoutput WHERE line = @line AND [Output] LIKE @SPNMachine)
  4262. BEGIN
  4263. INSERT INTO #ScopedDupSPN
  4264. SELECT QUOTENAME(@SPN), QUOTENAME(REPLACE([Output], CHAR(9), '')) FROM #xp_cmdshell_DupSPNoutput WHERE line > @line AND line < @linemax;
  4265. END
  4266. FETCH NEXT FROM curSPN INTO @line, @SPN
  4267. END
  4268. CLOSE curSPN
  4269. DEALLOCATE curSPN
  4270. END
  4271. IF EXISTS (SELECT TOP 1 [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%')
  4272. BEGIN
  4273. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%' AND [Output] LIKE @SPNMachine)
  4274. BEGIN
  4275. 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
  4276. END
  4277. ELSE
  4278. BEGIN
  4279. 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];
  4280. END
  4281. IF EXISTS (SELECT [Output] FROM #xp_cmdshell_AcctSPNoutput WHERE [Output] LIKE '%MSSQLSvc%' AND [Output] NOT LIKE @SPNMachine)
  4282. BEGIN
  4283. 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
  4284. END
  4285. END
  4286. ELSE
  4287. BEGIN
  4288. 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];
  4289. END
  4290. IF (SELECT COUNT(*) FROM #ScopedDupSPN) > 0
  4291. BEGIN
  4292. 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
  4293. END
  4294. ELSE
  4295. BEGIN
  4296. SELECT 'Service_Account_checks' AS [Category], 'Dup_MSSQLSvc_SPNs_Acct_CurrServer' AS [Check], '[OK]' AS [Deviation];
  4297. END
  4298. IF (SELECT COUNT(*) FROM #FinalDupSPN) > 0
  4299. BEGIN
  4300. 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
  4301. END
  4302. ELSE
  4303. BEGIN
  4304. SELECT 'Service_Account_checks' AS [Category], 'Dup_MSSQLSvc_SPNs_Acct' AS [Check], '[OK]' AS [Deviation];
  4305. END
  4306. END TRY
  4307. BEGIN CATCH
  4308. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4309. SELECT @ErrorMessage = 'Service Accounts and SPN registration subsection - Error raised in TRY block 9. ' + ERROR_MESSAGE()
  4310. RAISERROR (@ErrorMessage, 16, 1);
  4311. END CATCH
  4312. IF @xcmd = 0
  4313. BEGIN
  4314. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  4315. END
  4316. IF @sao = 0
  4317. BEGIN
  4318. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  4319. END
  4320. END
  4321. ELSE
  4322. BEGIN
  4323. 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')
  4324. 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')
  4325. --RETURN
  4326. END
  4327. END
  4328. ELSE
  4329. BEGIN
  4330. 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')
  4331. --RETURN
  4332. END;
  4333. RAISERROR (N'|-Starting Instance Checks', 10, 1) WITH NOWAIT
  4334. --------------------------------------------------------------------------------------------------------------------------------
  4335. -- Recommended build check subsection
  4336. --------------------------------------------------------------------------------------------------------------------------------
  4337. RAISERROR (N' |-Starting Recommended build check', 10, 1) WITH NOWAIT
  4338. SELECT 'Instance_checks' AS [Category], 'Recommended_Build' AS [Check],
  4339. CASE WHEN (@sqlmajorver = 9 AND @sqlbuild < 5000)
  4340. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild < 6000)
  4341. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild < 6000)
  4342. OR (@sqlmajorver = 11 AND @sqlbuild < 6020)
  4343. OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  4344. OR (@sqlmajorver = 13 AND @sqlbuild < 4000)
  4345. THEN '[WARNING: current service pack has been superseded in the current SQL Server version. Install the latest service pack as soon as possible.]'
  4346. ELSE '[OK]'
  4347. END AS [Deviation],
  4348. CASE WHEN @sqlmajorver = 9 THEN '2005'
  4349. WHEN @sqlmajorver = 10 AND @sqlminorver = 0 THEN '2008'
  4350. WHEN @sqlmajorver = 10 AND @sqlminorver = 50 THEN '2008R2'
  4351. WHEN @sqlmajorver = 11 THEN '2012'
  4352. WHEN @sqlmajorver = 12 THEN '2014'
  4353. WHEN @sqlmajorver = 13 THEN '2016'
  4354. END AS [Product_Major_Version],
  4355. CONVERT(VARCHAR(128), SERVERPROPERTY('ProductLevel')) AS Product_Level,
  4356. 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,
  4357. 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,
  4358. 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;
  4359. --------------------------------------------------------------------------------------------------------------------------------
  4360. -- Backup checks subsection
  4361. --------------------------------------------------------------------------------------------------------------------------------
  4362. RAISERROR (N' |-Starting Backup checks', 10, 1) WITH NOWAIT
  4363. DECLARE @nolog int, @nobck int, @nolog24h int, @neverlog int, @neverbck int
  4364. -- No Full backups
  4365. SELECT @neverbck = COUNT(DISTINCT d.name)
  4366. FROM master.sys.databases d (NOLOCK)
  4367. INNER JOIN #tmpdbs_userchoice tuc ON d.database_id = tuc.[dbid]
  4368. WHERE database_id NOT IN (2,3)
  4369. AND source_database_id IS NULL -- no snapshots
  4370. 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
  4371. -- No Full backups in last 7 days
  4372. ;WITH cteFullBcks (cnt) AS (SELECT DISTINCT database_name AS cnt
  4373. FROM msdb.dbo.backupset b (NOLOCK)
  4374. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4375. WHERE b.type = 'D' -- Full backup
  4376. AND b.is_copy_only = 0 -- No COPY_ONLY backups
  4377. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4378. WHERE database_id NOT IN (2,3)
  4379. AND source_database_id IS NULL) -- no snapshots
  4380. GROUP BY database_name
  4381. HAVING MAX(backup_finish_date) <= DATEADD(dd, -7, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) + 1, 0)))
  4382. SELECT @nobck = COUNT(cnt)
  4383. FROM cteFullBcks;
  4384. -- Last Log backup precedes last full or diff backup, and DB in Full or Bulk-logged RM
  4385. ;WITH cteLogBcks (cnt) AS (SELECT DISTINCT database_name
  4386. FROM msdb.dbo.backupset b (NOLOCK)
  4387. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4388. WHERE b.type = 'L' -- Log backup
  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. AND recovery_model < 3) -- not SIMPLE recovery model
  4393. GROUP BY [database_name]
  4394. 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
  4395. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4396. AND c.database_name = b.database_name))
  4397. SELECT @nolog = COUNT(cnt)
  4398. FROM cteLogBcks;
  4399. -- No Log backup since last full or diff backup, and DB in Full or Bulk-logged RM
  4400. SELECT @neverlog = COUNT(DISTINCT database_name)
  4401. FROM msdb.dbo.backupset b (NOLOCK)
  4402. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4403. WHERE database_name IN (SELECT name
  4404. FROM master.sys.databases (NOLOCK)
  4405. WHERE database_id NOT IN (2,3)
  4406. AND source_database_id IS NULL -- no snapshots
  4407. AND recovery_model < 3) -- not SIMPLE recovery model
  4408. AND EXISTS (SELECT DISTINCT database_name
  4409. FROM msdb.dbo.backupset c (NOLOCK)
  4410. WHERE c.type IN ('D','I') -- Full or Differential backup
  4411. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4412. AND c.database_name = b.database_name) -- Log backup
  4413. AND NOT EXISTS (SELECT DISTINCT database_name
  4414. FROM msdb.dbo.backupset c (NOLOCK)
  4415. WHERE c.type = 'L' -- Log Backup
  4416. AND c.database_name = b.database_name);
  4417. -- Log backup since last full or diff backup is older than 24h, and DB in Full ar Bulk-logged RM
  4418. ;WITH cteLogBcks2 (cnt) AS (SELECT DISTINCT database_name
  4419. FROM msdb.dbo.backupset b (NOLOCK)
  4420. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4421. WHERE b.type = 'L' -- Log backup
  4422. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4423. WHERE database_id NOT IN (2,3)
  4424. AND source_database_id IS NULL -- no snapshots
  4425. AND recovery_model < 3) -- not SIMPLE recovery model
  4426. GROUP BY database_name
  4427. 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
  4428. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4429. AND c.database_name = b.database_name)
  4430. AND MAX(backup_finish_date) <= DATEADD(hh, -24, GETDATE()))
  4431. SELECT @nolog24h = COUNT(cnt)
  4432. FROM cteLogBcks2;
  4433. IF @nobck > 0 OR @neverbck > 0
  4434. BEGIN
  4435. 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]
  4436. -- No full backups in last 7 days
  4437. SELECT DISTINCT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Information], database_name AS [Database_Name], MAX(backup_finish_date) AS Lst_Full_Backup
  4438. FROM msdb.dbo.backupset b (NOLOCK)
  4439. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4440. WHERE b.type = 'D' -- Full backup
  4441. AND b.is_copy_only = 0 -- No COPY_ONLY backups
  4442. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4443. WHERE database_id NOT IN (2,3)
  4444. AND source_database_id IS NULL) -- no snapshots
  4445. GROUP BY database_name
  4446. HAVING MAX(backup_finish_date) <= DATEADD(dd, -7, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) + 1, 0))
  4447. UNION ALL
  4448. -- No full backups in history
  4449. SELECT DISTINCT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Information], d.name AS [Database_Name], NULL AS Lst_Full_Backup
  4450. FROM master.sys.databases d (NOLOCK)
  4451. INNER JOIN #tmpdbs_userchoice tuc ON d.database_id = tuc.[dbid]
  4452. WHERE database_id NOT IN (2,3)
  4453. AND source_database_id IS NULL -- no snapshots
  4454. AND recovery_model < 3 -- not SIMPLE recovery model
  4455. 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
  4456. AND d.name NOT IN (SELECT b.database_name FROM msdb.dbo.backupset b WHERE b.type = 'L') -- Log backup
  4457. ORDER BY [Database_Name]
  4458. END
  4459. ELSE
  4460. BEGIN
  4461. SELECT 'Instance_checks' AS [Category], 'No_Full_Backups' AS [Check], '[OK]' AS [Deviation]
  4462. END;
  4463. IF @nolog > 0 OR @neverlog > 0
  4464. BEGIN
  4465. 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]
  4466. ;WITH Bck AS (SELECT database_name, MAX(backup_finish_date) AS backup_finish_date
  4467. FROM msdb.dbo.backupset (NOLOCK) b
  4468. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4469. WHERE [type] IN ('D','I') -- Full or Differential backup
  4470. GROUP BY database_name)
  4471. -- Log backups since last full or diff is older than 24h
  4472. 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,
  4473. (SELECT backup_finish_date FROM Bck c WHERE c.database_name = b.database_name) AS Lst_FullDiff_Backup
  4474. FROM msdb.dbo.backupset b (NOLOCK)
  4475. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4476. WHERE b.type = 'L' -- Log backup
  4477. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4478. WHERE database_id NOT IN (2,3)
  4479. AND source_database_id IS NULL -- no snapshots
  4480. AND recovery_model < 3) -- not SIMPLE recovery model
  4481. GROUP BY [database_name]
  4482. HAVING MAX(backup_finish_date) < (SELECT backup_finish_date FROM Bck c WHERE c.database_name = b.database_name)
  4483. UNION ALL
  4484. -- No log backup in history but full backup exists
  4485. 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
  4486. FROM msdb.dbo.backupset b (NOLOCK)
  4487. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4488. WHERE database_name IN (SELECT name
  4489. 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. AND EXISTS (SELECT DISTINCT database_name
  4494. FROM msdb.dbo.backupset c (NOLOCK)
  4495. WHERE c.type IN ('D','I') -- Full or Differential backup
  4496. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4497. AND c.database_name = b.database_name) -- Log backup
  4498. AND NOT EXISTS (SELECT DISTINCT database_name
  4499. FROM msdb.dbo.backupset c (NOLOCK)
  4500. WHERE c.type = 'L' -- Log Backup
  4501. AND c.database_name = b.database_name)
  4502. GROUP BY database_name
  4503. ORDER BY database_name;
  4504. END
  4505. ELSE
  4506. BEGIN
  4507. SELECT 'Instance_checks' AS [Category], 'No_Log_Bcks_since_LstFullorDiff' AS [Check], '[OK]' AS [Deviation]
  4508. END;
  4509. IF @nolog24h > 0
  4510. BEGIN
  4511. 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]
  4512. 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
  4513. FROM msdb.dbo.backupset b (NOLOCK)
  4514. INNER JOIN #tmpdbs_userchoice tuc ON b.database_name = tuc.[dbname]
  4515. WHERE b.type = 'L' -- Log backup
  4516. AND database_name IN (SELECT name FROM master.sys.databases (NOLOCK)
  4517. WHERE database_id NOT IN (2,3)
  4518. AND recovery_model < 3) -- not SIMPLE recovery model
  4519. GROUP BY database_name
  4520. 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
  4521. AND c.is_copy_only = 0 -- No COPY_ONLY backups
  4522. AND c.database_name = b.database_name)
  4523. AND MAX(backup_finish_date) <= DATEADD(hh, -24, GETDATE())
  4524. ORDER BY [database_name];
  4525. END
  4526. ELSE
  4527. BEGIN
  4528. SELECT 'Instance_checks' AS [Category], 'Log_Bcks_since_LstFullorDiff_are_older_than_24H' AS [Check], '[OK]' AS [Deviation]
  4529. END;
  4530. --------------------------------------------------------------------------------------------------------------------------------
  4531. -- Global trace flags subsection
  4532. --------------------------------------------------------------------------------------------------------------------------------
  4533. RAISERROR (N' |-Starting Global trace flags', 10, 1) WITH NOWAIT
  4534. DECLARE @tracestatus TABLE (TraceFlag NVARCHAR(40), [Status] tinyint, [Global] tinyint, [Session] tinyint);
  4535. INSERT INTO @tracestatus
  4536. EXEC ('DBCC TRACESTATUS WITH NO_INFOMSGS')
  4537. IF @sqlmajorver >= 11
  4538. BEGIN
  4539. DECLARE @dbname0 VARCHAR(1000), @dbid0 int, @sqlcmd0 NVARCHAR(4000), @has_colstrix int
  4540. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  4541. DROP TABLE #tblColStoreIXs;
  4542. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  4543. CREATE TABLE #tblColStoreIXs ([DBName] VARCHAR(1000), [Schema] VARCHAR(100), [Table] VARCHAR(255), [Object] VARCHAR(255));
  4544. UPDATE #tmpdbs0
  4545. SET isdone = 0;
  4546. UPDATE #tmpdbs0
  4547. SET isdone = 1
  4548. WHERE [state] <> 0 OR [dbid] < 5;
  4549. UPDATE #tmpdbs0
  4550. SET isdone = 1
  4551. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  4552. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  4553. BEGIN
  4554. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  4555. BEGIN
  4556. SELECT TOP 1 @dbname0 = [dbname], @dbid0 = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  4557. SET @sqlcmd0 = 'USE ' + QUOTENAME(@dbname0) + ';
  4558. SELECT ''' + @dbname0 + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), i.name
  4559. FROM sys.indexes AS i (NOLOCK)
  4560. INNER JOIN sys.objects AS o (NOLOCK) ON o.[object_id] = i.[object_id]
  4561. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = i.[object_id]
  4562. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  4563. WHERE i.[type] IN (5,6,7)' -- 5 = Clustered columnstore; 6 = Nonclustered columnstore; 7 = Nonclustered hash
  4564. BEGIN TRY
  4565. INSERT INTO #tblColStoreIXs
  4566. EXECUTE sp_executesql @sqlcmd0
  4567. END TRY
  4568. BEGIN CATCH
  4569. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  4570. SELECT @ErrorMessage = 'Global trace flags subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  4571. RAISERROR (@ErrorMessage, 16, 1);
  4572. END CATCH
  4573. UPDATE #tmpdbs0
  4574. SET isdone = 1
  4575. WHERE [dbid] = @dbid0
  4576. END
  4577. END;
  4578. SELECT @has_colstrix = COUNT(*) FROM #tblColStoreIXs
  4579. END;
  4580. IF (SELECT COUNT(TraceFlag) FROM @tracestatus WHERE [Global]=1) = 0
  4581. BEGIN
  4582. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check], '[There are no Global Trace Flags active]' AS [Deviation]
  4583. END;
  4584. -- Plan affecting TFs: http://support.microsoft.com/kb/2801413 and https://support.microsoft.com/en-us/kb/2964518
  4585. -- All supported TFs: http://msdn.microsoft.com/library/ms188396.aspx
  4586. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1)
  4587. BEGIN
  4588. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 634)
  4589. BEGIN
  4590. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4591. '[INFORMATION: TF634 disables the background columnstore compression task]'
  4592. AS [Deviation], TraceFlag
  4593. FROM @tracestatus
  4594. WHERE [Global] = 1 AND TraceFlag = 634
  4595. END;
  4596. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 652)
  4597. BEGIN
  4598. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4599. '[INFORMATION: TF652 disables read-aheads during scans]' --http://support.microsoft.com/en-us/kb/920093
  4600. AS [Deviation], TraceFlag
  4601. FROM @tracestatus
  4602. WHERE [Global] = 1 AND TraceFlag = 634
  4603. END;
  4604. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 661)
  4605. BEGIN
  4606. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4607. '[INFORMATION: TF661 disables the ghost cleanup background task]'
  4608. AS [Deviation], TraceFlag
  4609. FROM @tracestatus
  4610. WHERE [Global] = 1 AND TraceFlag = 661
  4611. END;
  4612. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 834)
  4613. BEGIN
  4614. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4615. CASE WHEN @sqlmajorver >= 11
  4616. AND @has_colstrix > 0
  4617. THEN '[WARNING: TF834 (Large Page Support for BP) is discouraged when Columnstore Indexes are used]'
  4618. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4619. END AS [Deviation], TraceFlag
  4620. FROM @tracestatus
  4621. WHERE [Global] = 1 AND TraceFlag = 834
  4622. END;
  4623. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 845)
  4624. BEGIN
  4625. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4626. CASE WHEN SERVERPROPERTY('EngineEdition') = 2 --Standard SKU
  4627. AND ((@sqlmajorver = 10 AND ((@sqlminorver = 0 AND @sqlbuild >= 2714) OR @sqlminorver = 50))
  4628. OR (@sqlmajorver = 9 AND @sqlbuild >= 4226))
  4629. THEN '[INFORMATION: TF845 supports locking pages in memory in SQL Server Standard Editions]'
  4630. WHEN SERVERPROPERTY('EngineEdition') = 2 --Standard SKU
  4631. AND @sqlmajorver = 11
  4632. THEN '[WARNING: TF845 is not needed in SQL 2012 and above]'
  4633. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4634. END AS [Deviation], TraceFlag
  4635. FROM @tracestatus
  4636. WHERE [Global] = 1 AND TraceFlag = 845
  4637. END;
  4638. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 902)
  4639. BEGIN
  4640. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4641. '[WARNING: TF902 Bypasses execution of database upgrade script when installing a Cumulative Update or Service Pack]'
  4642. AS [Deviation], TraceFlag
  4643. FROM @tracestatus
  4644. WHERE [Global] = 1 AND TraceFlag = 902
  4645. END;
  4646. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1117)
  4647. BEGIN
  4648. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4649. '[INFORMATION: TF1117 autogrows all files at the same time and affects all databases]'
  4650. AS [Deviation], TraceFlag
  4651. FROM @tracestatus
  4652. WHERE [Global] = 1 AND TraceFlag = 1117
  4653. END;
  4654. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1118)
  4655. BEGIN
  4656. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4657. '[INFORMATION: TF1118 forces uniform extent allocations instead of mixed page allocations]'
  4658. AS [Deviation], TraceFlag
  4659. FROM @tracestatus
  4660. WHERE [Global] = 1 AND TraceFlag = 1118
  4661. END;
  4662. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1204)
  4663. BEGIN
  4664. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4665. '[INFORMATION: TF1204 returns the resources and types of locks participating in a deadlock and also the current command affected]'
  4666. AS [Deviation], TraceFlag
  4667. FROM @tracestatus
  4668. WHERE [Global] = 1 AND TraceFlag = 1204
  4669. END;
  4670. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1211)
  4671. BEGIN
  4672. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4673. '[WARNING: TF1211 disables lock escalation based on memory pressure, or based on number of locks, increasing the amount of locks held]'
  4674. AS [Deviation], TraceFlag
  4675. FROM @tracestatus
  4676. WHERE [Global] = 1 AND TraceFlag = 1211
  4677. END;
  4678. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1222)
  4679. BEGIN
  4680. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4681. '[INFORMATION: TF1222 returns the resources and types of locks participating in a deadlock and also the current command affected]'
  4682. AS [Deviation], TraceFlag
  4683. FROM @tracestatus
  4684. WHERE [Global] = 1 AND TraceFlag = 1222
  4685. END;
  4686. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1224)
  4687. BEGIN
  4688. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4689. '[WARNING: TF1224 disables lock escalation based on the number of locks, and only escalates locks under memory pressure, increasing the amount of locks held]'
  4690. AS [Deviation], TraceFlag
  4691. FROM @tracestatus
  4692. WHERE [Global] = 1 AND TraceFlag = 1224
  4693. END;
  4694. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1229)
  4695. BEGIN
  4696. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4697. '[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
  4698. AS [Deviation], TraceFlag
  4699. FROM @tracestatus
  4700. WHERE [Global] = 1 AND TraceFlag = 1229
  4701. END;
  4702. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1236)
  4703. BEGIN
  4704. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4705. CASE WHEN @sqlmajorver = 9 OR @sqlmajorver = 10 OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 4100)
  4706. THEN '[INFORMATION: TF1236 enables database lock partitioning]'
  4707. WHEN (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 4100) OR @sqlmajorver = 13
  4708. THEN '[WARNING: TF1236 is not needed in SQL 2012 SP3, SQL Server 2014 SP1 and above]'
  4709. END AS [Deviation], TraceFlag
  4710. FROM @tracestatus
  4711. WHERE [Global] = 1 AND TraceFlag = 1236
  4712. END;
  4713. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 1462)
  4714. BEGIN
  4715. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4716. '[WARNING: TF1462 disables log stream compression for asynchronous availability groups]'
  4717. AS [Deviation], TraceFlag
  4718. FROM @tracestatus
  4719. WHERE [Global] = 1 AND TraceFlag = 1462
  4720. END;
  4721. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2312)
  4722. BEGIN
  4723. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4724. CASE WHEN @sqlmajorver = 12
  4725. THEN '[INFORMATION: TF2312 enables New CE model, SQL Server 2014 version]'
  4726. WHEN @sqlmajorver = 13
  4727. THEN '[INFORMATION: TF2312 enables New CE model to SQL Server 2014 or SQL Server 2016 versions, dependent of the compatibility level of the database]'
  4728. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4729. END AS [Deviation], TraceFlag
  4730. FROM @tracestatus
  4731. WHERE [Global] = 1 AND TraceFlag = 2312
  4732. END;
  4733. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2330)
  4734. BEGIN
  4735. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4736. CASE WHEN @sqlmajorver = 9
  4737. 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
  4738. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4739. END AS [Deviation], TraceFlag
  4740. FROM @tracestatus
  4741. WHERE [Global] = 1 AND TraceFlag = 2330
  4742. END;
  4743. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2335)
  4744. BEGIN
  4745. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4746. CASE WHEN @sqlmajorver >= 9
  4747. AND @maxservermem >= 100000 * 1024 -- 100GB
  4748. AND @maxservermem <> 2147483647
  4749. THEN '[INFORMATION: TF2335 assumes a fixed amount of memory is available during query optimization. Recommended when server has more than 100GB of memory]'
  4750. WHEN @sqlmajorver >= 9
  4751. AND @maxservermem < 100000 * 1024 -- 100GB
  4752. AND @maxservermem <> 2147483647
  4753. THEN '[WARNING: TF2335 should not be set on servers with less than 100GB of memory]'
  4754. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4755. END AS [Deviation], TraceFlag
  4756. FROM @tracestatus
  4757. WHERE [Global] = 1 AND TraceFlag = 2335
  4758. END;
  4759. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2335)
  4760. AND @sqlmajorver >= 9
  4761. AND @maxservermem >= 100000 * 1024 -- 100GB
  4762. AND @maxservermem <> 2147483647
  4763. BEGIN
  4764. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4765. '[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
  4766. AS [Deviation]
  4767. END;
  4768. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2340)
  4769. BEGIN
  4770. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4771. '[INFORMATION: TF2340 causes SQL Server not to use a sort operation (batch sort) for optimized nested loop joins when generating a plan]'
  4772. AS [Deviation], TraceFlag
  4773. FROM @tracestatus
  4774. WHERE [Global] = 1 AND TraceFlag = 2340
  4775. END;
  4776. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2371)
  4777. BEGIN
  4778. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4779. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500) OR @sqlmajorver >= 11
  4780. THEN '[INFORMATION: TF2371 changes the fixed rate of the 20pct threshold for update statistics into a dynamic percentage rate]'
  4781. WHEN @sqlmajorver = 13
  4782. THEN '[WARNING: TF2371 is not needed in SQL 2016 and above]'
  4783. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4784. END AS [Deviation], TraceFlag
  4785. FROM @tracestatus
  4786. WHERE [Global] = 1 AND TraceFlag = 2371
  4787. END;
  4788. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2371)
  4789. AND ((@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2500) OR @sqlmajorver >= 11)
  4790. BEGIN
  4791. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4792. '[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
  4793. AS [Deviation]
  4794. END;
  4795. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2389)
  4796. BEGIN
  4797. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4798. '[INFORMATION: TF2389 enables automatically generated quick statistics for ascending keys (histogram amendment)]'
  4799. AS [Deviation], TraceFlag
  4800. FROM @tracestatus
  4801. WHERE [Global] = 1 AND TraceFlag = 2389
  4802. END;
  4803. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2528)
  4804. BEGIN
  4805. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4806. '[INFORMATION: TF2528 disables parallel checking of objects by DBCC CHECKDB, DBCC CHECKFILEGROUP, and DBCC CHECKTABLE]'
  4807. AS [Deviation], TraceFlag
  4808. FROM @tracestatus
  4809. WHERE [Global] = 1 AND TraceFlag = 2528
  4810. END;
  4811. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2549)
  4812. BEGIN
  4813. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4814. '[INFORMATION: TF2549 runs the DBCC CHECKDB command assuming each database file is on a unique disk drive]'
  4815. AS [Deviation], TraceFlag
  4816. FROM @tracestatus
  4817. WHERE [Global] = 1 AND TraceFlag = 2549
  4818. END;
  4819. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2562)
  4820. BEGIN
  4821. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4822. '[INFORMATION: TF2562 runs the DBCC CHECKDB command in a single batch regardless of the number of indexes in the database]'
  4823. AS [Deviation], TraceFlag
  4824. FROM @tracestatus
  4825. WHERE [Global] = 1 AND TraceFlag = 2562
  4826. END;
  4827. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 2566)
  4828. BEGIN
  4829. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4830. '[INFORMATION: TF2566 runs the DBCC CHECKDB command without data purity check unless DATA_PURITY option is specified]'
  4831. AS [Deviation], TraceFlag
  4832. FROM @tracestatus
  4833. WHERE [Global] = 1 AND TraceFlag = 2566
  4834. END;
  4835. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3023)
  4836. BEGIN
  4837. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4838. '[INFORMATION: TF3023 enables CHECKSUM option as default for BACKUP command]'
  4839. AS [Deviation], TraceFlag
  4840. FROM @tracestatus
  4841. WHERE [Global] = 1 AND TraceFlag = 3023
  4842. END;
  4843. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3042)
  4844. BEGIN
  4845. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4846. '[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]'
  4847. AS [Deviation], TraceFlag
  4848. FROM @tracestatus
  4849. WHERE [Global] = 1 AND TraceFlag = 3042
  4850. END;
  4851. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 3226)
  4852. BEGIN
  4853. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4854. '[INFORMATION: TF3226 prevents SQL Server from recording an entry to Errorlog on every successful backup operation]'
  4855. AS [Deviation], TraceFlag
  4856. FROM @tracestatus
  4857. WHERE [Global] = 1 AND TraceFlag = 3226
  4858. END;
  4859. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4135)
  4860. BEGIN
  4861. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4862. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1818 AND 1835)
  4863. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1702)
  4864. THEN '[WARNING: TF4199 should be used instead of TF4135 in this SQL build]'
  4865. ELSE '[INFORMATION: TF4135 enables query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  4866. END AS [Deviation], TraceFlag
  4867. FROM @tracestatus
  4868. WHERE [Global] = 1 AND TraceFlag = 4135
  4869. END;
  4870. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4136)
  4871. BEGIN
  4872. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4873. CASE WHEN (@sqlmajorver = 9 AND @sqlbuild >= 4294)
  4874. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 2766)
  4875. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1720)
  4876. OR (@sqlmajorver = 11 AND @sqlbuild >= 2316)
  4877. OR @sqlmajorver >= 12
  4878. THEN '[INFORMATION: TF4136 disables parameter sniffing unless OPTION(RECOMPILE), WITH RECOMPILE or OPTIMIZE FOR value is used]'
  4879. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4880. END AS [Deviation], TraceFlag
  4881. FROM @tracestatus
  4882. WHERE [Global] = 1 AND TraceFlag = 4136
  4883. END;
  4884. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4137)
  4885. BEGIN
  4886. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4887. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 5794)
  4888. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 4326 AND 4371)
  4889. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 2806)
  4890. OR (@sqlmajorver = 11 AND @sqlbuild >= 2316)
  4891. OR @sqlmajorver >= 12
  4892. 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]'
  4893. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4894. END AS [Deviation], TraceFlag
  4895. FROM @tracestatus
  4896. WHERE [Global] = 1 AND TraceFlag = 4137
  4897. END;
  4898. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4138)
  4899. BEGIN
  4900. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4901. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4260)
  4902. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 2817 AND 2881)
  4903. OR (@sqlmajorver = 11 AND @sqlbuild >= 2325)
  4904. OR @sqlmajorver >= 12
  4905. 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]'
  4906. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4907. END AS [Deviation], TraceFlag
  4908. FROM @tracestatus
  4909. WHERE [Global] = 1 AND TraceFlag = 4138
  4910. END;
  4911. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4139)
  4912. BEGIN
  4913. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4914. CASE WHEN (@sqlmajorver = 11 AND @sqlbuild >= 5532)
  4915. OR (@sqlmajorver = 11 AND @sqlbuild >= 3431 AND @sqlbuild < 5058)
  4916. OR @sqlmajorver >= 12
  4917. THEN '[INFORMATION: TF4139 enables automatically generated quick statistics (histogram amendment) regardless of key column status]'
  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 = 4139
  4922. END;
  4923. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 4199)
  4924. BEGIN
  4925. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4926. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1787 AND 1812)
  4927. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 2531 AND 2757)
  4928. OR (@sqlmajorver >= 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 1600 AND 1617)
  4929. THEN '[WARNING: TF4135 should be used instead of TF4199 in this SQL build]'
  4930. ELSE '[INFORMATION: TF4199 enables query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  4931. END AS [Deviation], TraceFlag
  4932. FROM @tracestatus
  4933. WHERE [Global] = 1 AND TraceFlag = 4199
  4934. END;
  4935. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 6498)
  4936. BEGIN
  4937. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4938. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 4416)
  4939. OR (@sqlmajorver = 12 AND @sqlbuild BETWEEN 2480 AND 2474)
  4940. THEN '[INFORMATION: TF6498 enables more than one large query compilation to gain access to the big gateway when there is sufficient memory available]'
  4941. WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver >= 13
  4942. THEN '[WARNING: TF6498 is not needed in SQL 2014 SP2, SQL Server 2016 and above]'
  4943. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4944. END AS [Deviation], TraceFlag
  4945. FROM @tracestatus
  4946. WHERE [Global] = 1 AND TraceFlag = 6498
  4947. END;
  4948. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag IN (6532,6533))
  4949. BEGIN
  4950. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4951. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000)
  4952. OR (@sqlmajorver = 11 AND @sqlbuild >= 6020)
  4953. THEN '[INFORMATION: TF6532 and TF 6533 enable performance improvement of query operations with spatial data types]'
  4954. WHEN @sqlmajorver = 13
  4955. THEN '[WARNING: TF6532 and TF 6533 are not needed in SQL Server 2016 and above]'
  4956. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4957. END AS [Deviation], TraceFlag
  4958. FROM @tracestatus
  4959. WHERE [Global] = 1 AND TraceFlag IN (6532,6533)
  4960. END;
  4961. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 6534)
  4962. BEGIN
  4963. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4964. CASE WHEN (@sqlmajorver = 12 AND @sqlbuild >= 5000)
  4965. OR (@sqlmajorver = 11 AND @sqlbuild >= 6020)
  4966. OR @sqlmajorver = 13
  4967. THEN '[INFORMATION: TF6534 enables performance improvement of query operations with spatial data types]'
  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 = 6534
  4972. END;
  4973. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8015)
  4974. BEGIN
  4975. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4976. CASE WHEN (@sqlmajorver = 11 AND @sqlbuild >= 3349)
  4977. OR @sqlmajorver >= 12
  4978. 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
  4979. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4980. END AS [Deviation], TraceFlag
  4981. FROM @tracestatus
  4982. WHERE [Global] = 1 AND TraceFlag = 8015
  4983. END;
  4984. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8032)
  4985. BEGIN
  4986. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4987. CASE WHEN @sqlmajorver >= 10
  4988. 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]'
  4989. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  4990. END AS [Deviation], TraceFlag
  4991. FROM @tracestatus
  4992. WHERE [Global] = 1 AND TraceFlag = 8032
  4993. END;
  4994. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8048)
  4995. BEGIN
  4996. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  4997. CASE WHEN ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  4998. OR (@sqlmajorver BETWEEN 9 AND 11))
  4999. AND (@cpucount/@numa) > 8
  5000. 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
  5001. WHEN (@sqlmajorver = 12 AND @sqlbuild >= 4100) OR @sqlmajorver >= 13
  5002. THEN '[WARNING: TF8048 is not needed in SQL Server 2014 SP2, SQL Server 2016 and above]'
  5003. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5004. END AS [Deviation], TraceFlag
  5005. FROM @tracestatus
  5006. WHERE [Global] = 1 AND TraceFlag = 8048
  5007. END;
  5008. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8048)
  5009. AND ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5010. OR (@sqlmajorver BETWEEN 9 AND 11))
  5011. AND (@cpucount/@numa) > 8
  5012. BEGIN
  5013. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5014. '[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
  5015. AS [Deviation];
  5016. -- If the top consumers are partitioned by Node, then use startup trace flag 8048 to further partition by CPU.
  5017. IF @sqlmajorver < 11
  5018. BEGIN
  5019. SELECT 'Instance_checks' AS [Category], 'Is_TF8048_Applicable' AS [Check], [type],
  5020. SUM(page_size_in_bytes)/8192 AS [pages],
  5021. SUM(page_size_in_bytes)/1024 AS pages_in_KB,
  5022. CASE WHEN (0x20 = creation_options & 0x20) THEN 'Global PMO. Cannot be partitioned by CPU/NUMA Node. TF8048 not applicable.'
  5023. WHEN (0x40 = creation_options & 0x40) THEN 'Partitioned by CPU. TF8048 not applicable.'
  5024. WHEN (0x80 = creation_options & 0x80) THEN 'Partitioned by Node. Use TF8048 to further partition by CPU'
  5025. ELSE 'Unknown' END AS [Comment]
  5026. FROM sys.dm_os_memory_objects
  5027. GROUP BY [type], creation_options
  5028. ORDER BY SUM(page_size_in_bytes) DESC;
  5029. END
  5030. ELSE
  5031. BEGIN
  5032. SET @sqlcmd = N'SELECT ''Instance_checks'' AS [Category], ''Is_TF8048_Applicable'' AS [Check], [type],
  5033. SUM(pages_in_bytes)/8192 AS [pages],
  5034. SUM(pages_in_bytes)/1024 AS pages_in_KB,
  5035. CASE WHEN (0x20 = creation_options & 0x20) THEN ''Global PMO. Cannot be partitioned by CPU/NUMA Node. TF8048 not applicable.''
  5036. WHEN (0x40 = creation_options & 0x40) THEN ''Partitioned by CPU. TF8048 not applicable.''
  5037. WHEN (0x80 = creation_options & 0x80) THEN ''Partitioned by Node. Use TF8048 to further partition by CPU''
  5038. ELSE ''Unknown'' END AS [Comment]
  5039. FROM sys.dm_os_memory_objects
  5040. GROUP BY [type], creation_options
  5041. ORDER BY SUM(pages_in_bytes) DESC;'
  5042. EXECUTE sp_executesql @sqlcmd
  5043. END;
  5044. END;
  5045. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 8744)
  5046. BEGIN
  5047. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5048. CASE WHEN @sqlmajorver >= 12 THEN
  5049. '[INFORMATION: TF8744 disables pre-fetching for the Nested Loop operator]'
  5050. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5051. END AS [Deviation], TraceFlag
  5052. FROM @tracestatus
  5053. WHERE [Global] = 1 AND TraceFlag = 8744
  5054. END;
  5055. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9024)
  5056. BEGIN
  5057. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5058. CASE WHEN ((@sqlmajorver = 12 AND @sqlbuild < 4100)
  5059. OR (@sqlmajorver = 11 AND @sqlbuild >= 3349 AND @sqlbuild < 6020))
  5060. AND (@cpucount/@numa) > 8
  5061. THEN '[INFORMATION: TF9024 converts a global log pool memory object into NUMA node partitioned memory object]'
  5062. WHEN (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 4427) OR @sqlmajorver > 12
  5063. THEN '[WARNING: TF9024 is not needed in SQL Server 2012 SP3, SQL Server 2014 SP1 and above]'
  5064. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5065. END AS [Deviation], TraceFlag
  5066. FROM @tracestatus
  5067. WHERE [Global] = 1 AND TraceFlag = 9024
  5068. END;
  5069. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9347)
  5070. BEGIN
  5071. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5072. CASE WHEN @sqlmajorver >= 13 THEN
  5073. '[INFORMATION: TF9347 disables batch mode for sort operator]'
  5074. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5075. END AS [Deviation], TraceFlag
  5076. FROM @tracestatus
  5077. WHERE [Global] = 1 AND TraceFlag = 9347
  5078. END;
  5079. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9349)
  5080. BEGIN
  5081. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5082. CASE WHEN @sqlmajorver >= 13 THEN
  5083. '[INFORMATION: TF9349 disables batch mode for top N sort operator]'
  5084. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5085. END AS [Deviation], TraceFlag
  5086. FROM @tracestatus
  5087. WHERE [Global] = 1 AND TraceFlag = 9349
  5088. END;
  5089. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9389)
  5090. BEGIN
  5091. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5092. CASE WHEN @sqlmajorver >= 13 THEN
  5093. '[INFORMATION: TF9389 enables dynamic memory grant for batch mode operators]'
  5094. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5095. END AS [Deviation], TraceFlag
  5096. FROM @tracestatus
  5097. WHERE [Global] = 1 AND TraceFlag = 9389
  5098. END;
  5099. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9476)
  5100. BEGIN
  5101. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5102. CASE WHEN @sqlmajorver >= 13 THEN
  5103. '[INFORMATION: TF9476 causes SQL Server to generate a plan using the Simple Containment instead of the default Base Containment under New CE]'
  5104. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5105. END AS [Deviation], TraceFlag
  5106. FROM @tracestatus
  5107. WHERE [Global] = 1 AND TraceFlag = 9476
  5108. END;
  5109. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 9481)
  5110. BEGIN
  5111. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5112. CASE WHEN @sqlmajorver >= 12
  5113. THEN '[INFORMATION: TF9481 enables Legacy CE model, irrespective of the compatibility level of the database]'
  5114. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5115. END AS [Deviation], TraceFlag
  5116. FROM @tracestatus
  5117. WHERE [Global] = 1 AND TraceFlag = 9481
  5118. END;
  5119. IF EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag = 10204)
  5120. BEGIN
  5121. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5122. CASE WHEN @sqlmajorver >= 13
  5123. THEN '[INFORMATION: TF10204 disables merge/recompress during columnstore index reorganization]'
  5124. ELSE '[WARNING: Verify need to set a Non-default TF with current system build and configuration]'
  5125. END AS [Deviation], TraceFlag
  5126. FROM @tracestatus
  5127. WHERE [Global] = 1 AND TraceFlag = 10204
  5128. END;
  5129. END;
  5130. IF NOT EXISTS (SELECT TraceFlag FROM @tracestatus WHERE [Global] = 1 AND TraceFlag IN (4135,4199))
  5131. BEGIN
  5132. SELECT 'Instance_checks' AS [Category], 'Global_Trace_Flags' AS [Check],
  5133. CASE WHEN (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1787 AND 1812)
  5134. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 2531 AND 2757)
  5135. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild >= 2766)
  5136. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild BETWEEN 1600 AND 1617)
  5137. THEN '[INFORMATION: Consider enabling TF4135 to support fixes and enhancements on the query optimizer]'
  5138. WHEN (@sqlmajorver = 9 AND @sqlbuild >= 4266)
  5139. OR (@sqlmajorver = 10 AND @sqlminorver = 0 AND @sqlbuild BETWEEN 1818 AND 1835)
  5140. OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 1702) OR @sqlmajorver >= 11
  5141. THEN '[INFORMATION: Consider enabling TF4199 to enable query optimizer changes released in SQL Server Cumulative Updates and Service Packs]'
  5142. END AS [Deviation]
  5143. END;
  5144. --------------------------------------------------------------------------------------------------------------------------------
  5145. -- System configurations subsection
  5146. --------------------------------------------------------------------------------------------------------------------------------
  5147. RAISERROR (N' |-Starting System configurations', 10, 1) WITH NOWAIT
  5148. -- Focus on:
  5149. -- backup compression default
  5150. -- clr enabled (only enable if needed)
  5151. -- lightweight pooling (should be zero)
  5152. -- max degree of parallelism
  5153. -- cost threshold for parallelism
  5154. -- max server memory (MB) (set to an appropriate value)
  5155. -- priority boost (should be zero)
  5156. -- remote admin connections (should be enabled in a cluster configuration, to allow remote DAC)
  5157. -- scan for startup procs (should be disabled unless business requirement, like replication)
  5158. -- min memory per query (default is 1024KB)
  5159. -- allow updates (no effect in 2005 or above, but should be off)
  5160. -- max worker threads (should be zero in 2005 or above)
  5161. -- affinity mask and affinity I/O mask (must not overlap)
  5162. DECLARE @awe tinyint, @ssp bit, @bckcomp bit, @clr bit, @costparallel tinyint, @chain bit, @lpooling bit
  5163. DECLARE @adhoc smallint, @pboost bit, @qtimeout int, @cmdshell bit, @deftrace bit, @remote bit, @autoNUMA bit
  5164. DECLARE @minmemqry int, @allowupd bit, @mwthreads int, @recinterval int, @netsize smallint
  5165. DECLARE @ixmem smallint, @adhocqry bit, @locks int, @qrywait int--, @mwthreads_count int
  5166. DECLARE @affin int, @affinIO int, @affin64 int, @affin64IO int, @block_threshold int, @oleauto int
  5167. --SELECT @mwthreads_count = max_workers_count FROM sys.dm_os_sys_info;
  5168. SELECT @adhocqry = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'Ad Hoc Distributed Queries';
  5169. SELECT @affin = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity mask';
  5170. SELECT @affinIO = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity I/O mask';
  5171. SELECT @affin64 = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity64 mask';
  5172. SELECT @affin64IO = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'affinity64 I/O mask';
  5173. SELECT @allowupd = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'allow updates';
  5174. SELECT @block_threshold = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'blocked process threshold (s)';
  5175. SELECT @awe = CONVERT(tinyint, [value]) FROM sys.configurations WHERE [Name] = 'awe enabled';
  5176. SELECT @autoNUMA = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'automatic soft-NUMA disabled';
  5177. SELECT @bckcomp = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'backup compression default';
  5178. SELECT @clr = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'clr enabled';
  5179. SELECT @costparallel = CONVERT(tinyint, [value]) FROM sys.configurations WHERE [Name] = 'cost threshold for parallelism';
  5180. SELECT @chain = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'cross db ownership chaining';
  5181. SELECT @deftrace = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'default trace enabled';
  5182. SELECT @ixmem = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'index create memory (KB)';
  5183. SELECT @locks = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'locks';
  5184. SELECT @minmemqry = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'min memory per query (KB)';
  5185. SELECT @mwthreads = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'max worker threads';
  5186. SELECT @netsize = CONVERT(smallint, [value]) FROM sys.configurations WHERE [Name] = 'network packet size (B)';
  5187. SELECT @lpooling = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'lightweight pooling';
  5188. SELECT @recinterval = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'recovery interval (min)';
  5189. SELECT @remote = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'remote admin connections';
  5190. SELECT @qrywait = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'query wait (s)';
  5191. SELECT @adhoc = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'optimize for ad hoc workloads';
  5192. SELECT @oleauto = CONVERT(int, [value]) FROM sys.configurations (NOLOCK) WHERE name = 'Ole Automation Procedures';
  5193. SELECT @pboost = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'priority boost';
  5194. SELECT @qtimeout = CONVERT(int, [value]) FROM sys.configurations WHERE [Name] = 'remote query timeout (s)';
  5195. SELECT @ssp = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'scan for startup procs';
  5196. SELECT @cmdshell = CONVERT(bit, [value]) FROM sys.configurations WHERE [Name] = 'xp_cmdshell';
  5197. 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]
  5198. UNION ALL
  5199. 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]
  5200. UNION ALL
  5201. 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]
  5202. UNION ALL
  5203. 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]
  5204. UNION ALL
  5205. 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]
  5206. UNION ALL
  5207. 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]
  5208. UNION ALL
  5209. 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]
  5210. UNION ALL
  5211. 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]
  5212. UNION ALL
  5213. 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]
  5214. UNION ALL
  5215. 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]
  5216. UNION ALL
  5217. 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]
  5218. UNION ALL
  5219. 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]
  5220. UNION ALL
  5221. 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]
  5222. UNION ALL
  5223. 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]
  5224. UNION ALL
  5225. 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]
  5226. UNION ALL
  5227. 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]
  5228. UNION ALL
  5229. 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]
  5230. UNION ALL
  5231. 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]
  5232. UNION ALL
  5233. 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]
  5234. UNION ALL
  5235. 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]
  5236. UNION ALL
  5237. 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]
  5238. UNION ALL
  5239. 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]
  5240. UNION ALL
  5241. 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]
  5242. UNION ALL
  5243. 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]
  5244. UNION ALL
  5245. 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]
  5246. UNION ALL
  5247. 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]
  5248. UNION ALL
  5249. 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];
  5250. IF (SELECT COUNT([Name]) FROM master.sys.configurations WHERE [value] <> [value_in_use] AND [is_dynamic] = 0) > 0
  5251. BEGIN
  5252. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Check], '[WARNING: There are system configurations with differences between running and configured values]' AS [Deviation]
  5253. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Information], [Name] AS [Setting],
  5254. [value] AS 'Config_Value',
  5255. [value_in_use] AS 'Run_Value'
  5256. FROM master.sys.configurations (NOLOCK)
  5257. WHERE [value] <> [value_in_use] AND [is_dynamic] = 0;
  5258. END
  5259. ELSE
  5260. BEGIN
  5261. SELECT 'Instance_checks' AS [Category], 'System_Configurations_Pending'AS [Check], '[OK]' AS [Deviation]
  5262. END;
  5263. --------------------------------------------------------------------------------------------------------------------------------
  5264. -- IFI subsection
  5265. --------------------------------------------------------------------------------------------------------------------------------
  5266. RAISERROR (N' |-Starting IFI', 10, 1) WITH NOWAIT
  5267. DECLARE @ifi bit, @IFIStatus NVARCHAR(256)
  5268. IF ((@sqlmajorver = 13 AND @sqlbuild < 4000) OR @sqlmajorver < 13)
  5269. BEGIN
  5270. IF @allow_xpcmdshell = 1
  5271. BEGIN
  5272. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  5273. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5274. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0)) -- Is not sysadmin but proxy account exists
  5275. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5276. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0))
  5277. BEGIN
  5278. RAISERROR (' |-Configuration options set for IFI check', 10, 1) WITH NOWAIT
  5279. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  5280. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  5281. IF @sao = 0
  5282. BEGIN
  5283. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  5284. END
  5285. IF @xcmd = 0
  5286. BEGIN
  5287. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  5288. END
  5289. BEGIN TRY
  5290. DECLARE @xp_cmdshell_output2 TABLE ([Output] VARCHAR (8000));
  5291. SET @CMD = ('whoami /priv')
  5292. INSERT INTO @xp_cmdshell_output2
  5293. EXEC master.dbo.xp_cmdshell @CMD;
  5294. IF EXISTS (SELECT * FROM @xp_cmdshell_output2 WHERE [Output] LIKE '%SeManageVolumePrivilege%')
  5295. BEGIN
  5296. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[OK]' AS [Deviation];
  5297. SET @ifi = 1;
  5298. END
  5299. ELSE
  5300. BEGIN
  5301. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[WARNING: Instant File Initialization is disabled. This can impact data file autogrowth times]' AS [Deviation];
  5302. SET @ifi = 0
  5303. END
  5304. END TRY
  5305. BEGIN CATCH
  5306. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  5307. SELECT @ErrorMessage = 'IFI subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  5308. RAISERROR (@ErrorMessage, 16, 1);
  5309. END CATCH
  5310. IF @xcmd = 0
  5311. BEGIN
  5312. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  5313. END
  5314. IF @sao = 0
  5315. BEGIN
  5316. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  5317. END
  5318. END
  5319. ELSE
  5320. BEGIN
  5321. 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')
  5322. 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')
  5323. --RETURN
  5324. END
  5325. END
  5326. ELSE
  5327. BEGIN
  5328. RAISERROR(' |- [INFORMATION: "Instant Initialization" check was skipped because xp_cmdshell was not allowed.]', 10, 1, N'disallow_xp_cmdshell')
  5329. --RETURN
  5330. END
  5331. END
  5332. ELSE IF ((@sqlmajorver = 13 AND @sqlbuild >= 4000) OR @sqlmajorver > 13)
  5333. BEGIN
  5334. 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%''';
  5335. SET @params = N'@IFIStatusOUT NVARCHAR(256) OUTPUT';
  5336. EXECUTE sp_executesql @sqlcmd, @params, @IFIStatusOUT=@IFIStatus OUTPUT;
  5337. IF @IFIStatus = 'Y'
  5338. BEGIN
  5339. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[OK]' AS [Deviation];
  5340. SET @ifi = 1;
  5341. END
  5342. ELSE
  5343. BEGIN
  5344. SELECT 'Instance_checks' AS [Category], 'Instant_Initialization' AS [Check], '[WARNING: Instant File Initialization is disabled. This can impact data file autogrowth times]' AS [Deviation];
  5345. SET @ifi = 0
  5346. END
  5347. END;
  5348. --------------------------------------------------------------------------------------------------------------------------------
  5349. -- Full Text Configurations subsection
  5350. --------------------------------------------------------------------------------------------------------------------------------
  5351. RAISERROR (N' |-Starting Full Text Configurations', 10, 1) WITH NOWAIT
  5352. DECLARE @FullTextDefaultPath NVARCHAR(512), @fterr tinyint
  5353. DECLARE @fttbl TABLE ([KeyExist] int)
  5354. DECLARE @FullTextDetails TABLE (FullText_ResourceUsage tinyint,
  5355. [DefaultPath] NVARCHAR(512),
  5356. [ConnectTimeout] int,
  5357. [DataTimeout] int,
  5358. [AllowUnsignedBinaries] bit,
  5359. [LoadOSResourcesEnabled] bit,
  5360. [CatalogUpgradeOption] tinyint)
  5361. SET @fterr = 0
  5362. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 1
  5363. BEGIN
  5364. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1) OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') = 1)
  5365. BEGIN
  5366. BEGIN TRY
  5367. INSERT INTO @fttbl
  5368. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup' -- check if Full-Text path exists
  5369. IF (SELECT [KeyExist] FROM @fttbl) = 1
  5370. BEGIN
  5371. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup', N'FullTextDefaultPath', @FullTextDefaultPath OUTPUT, NO_OUTPUT;
  5372. END
  5373. END TRY
  5374. BEGIN CATCH
  5375. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  5376. SELECT @ErrorMessage = 'Full Text Configurations subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  5377. RAISERROR (@ErrorMessage, 16, 1);
  5378. END CATCH
  5379. END
  5380. ELSE
  5381. BEGIN
  5382. RAISERROR('[WARNING: Missing permissions for full "Full Text Configurations" checks. Bypassing Full Text path check]', 16, 1, N'sysadmin')
  5383. --RETURN
  5384. END
  5385. INSERT INTO @FullTextDetails
  5386. SELECT FULLTEXTSERVICEPROPERTY('ResourceUsage'), ISNULL(@FullTextDefaultPath, N'') AS [Default Path],
  5387. ISNULL(FULLTEXTSERVICEPROPERTY('ConnectTimeout'),0), ISNULL(FULLTEXTSERVICEPROPERTY('DataTimeout'),0),
  5388. CASE WHEN @sqlmajorver >= 9 THEN
  5389. FULLTEXTSERVICEPROPERTY('VerifySignature') ELSE NULL
  5390. END AS [AllowUnsignedBinaries],
  5391. CASE WHEN @sqlmajorver >= 9 THEN
  5392. FULLTEXTSERVICEPROPERTY('LoadOSResources') ELSE NULL
  5393. END AS [LoadOSResourcesEnabled],
  5394. CASE WHEN @sqlmajorver >= 10 THEN
  5395. FULLTEXTSERVICEPROPERTY('UpgradeOption') ELSE NULL
  5396. END AS [CatalogUpgradeOption];
  5397. IF @sqlmajorver <= 9 AND (SELECT FullText_ResourceUsage FROM @FullTextDetails) <> 3
  5398. BEGIN
  5399. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[INFORMATION: FullText Resource usage setting is not default]' AS [Deviation],
  5400. CASE WHEN FullText_ResourceUsage < 3 THEN '[Least Aggressive Usage Level]'
  5401. WHEN FullText_ResourceUsage = 4 THEN '[More Aggressive Usage Level]'
  5402. WHEN FullText_ResourceUsage = 5 THEN '[Most Aggressive Usage Level]'
  5403. END AS [Comment]
  5404. FROM @FullTextDetails;
  5405. SET @fterr = @fterr + 1
  5406. END
  5407. IF @sqlmajorver >= 9 AND (SELECT [AllowUnsignedBinaries] FROM @FullTextDetails) = 0
  5408. BEGIN
  5409. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[WARNING: FullText Binaries verification setting is not default]' AS [Deviation],
  5410. '[Do not verify whether or not binaries are signed]' AS [Comment];
  5411. SET @fterr = @fterr + 1
  5412. END
  5413. IF @sqlmajorver >= 9 AND (SELECT [LoadOSResourcesEnabled] FROM @FullTextDetails) = 1
  5414. BEGIN
  5415. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[WARNING: FullText OS Resource utilization setting is not default]' AS [Deviation],
  5416. '[Load OS filters and word breakers]' AS [Comment];
  5417. SET @fterr = @fterr + 1
  5418. END
  5419. IF @fterr = 0
  5420. BEGIN
  5421. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], '[OK]' AS [Deviation],
  5422. '[All FullText settings are aligned with defaults]' AS [Comment];
  5423. END
  5424. END;
  5425. IF (SELECT ISNULL(FULLTEXTSERVICEPROPERTY('IsFulltextInstalled'),0)) = 0
  5426. BEGIN
  5427. SELECT 'Instance_checks' AS [Category], 'Full_Text' AS [Check], NULL AS [Deviation], '[FullText search is not installed]' AS [Comment];
  5428. END;
  5429. --------------------------------------------------------------------------------------------------------------------------------
  5430. -- Deprecated features subsection
  5431. --------------------------------------------------------------------------------------------------------------------------------
  5432. IF @ptochecks = 1
  5433. BEGIN
  5434. RAISERROR (N' |-Starting Deprecated features', 10, 1) WITH NOWAIT
  5435. IF (SELECT COUNT(instance_name) FROM sys.dm_os_performance_counters WHERE [object_name] = 'SQLServer:Deprecated Features' AND cntr_value > 0) > 0
  5436. BEGIN
  5437. 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]
  5438. SELECT 'Instance_checks' AS [Category], 'Deprecated_features' AS [Information], instance_name, cntr_value AS [Times_used_since_startup]
  5439. FROM sys.dm_os_performance_counters (NOLOCK)
  5440. WHERE [object_name] LIKE '%Deprecated Features%' AND cntr_value > 0
  5441. ORDER BY instance_name;
  5442. END
  5443. ELSE
  5444. BEGIN
  5445. SELECT 'Instance_checks' AS [Category], 'Deprecated_features' AS [Check], '[OK]' AS [Deviation]
  5446. END;
  5447. END;
  5448. --------------------------------------------------------------------------------------------------------------------------------
  5449. -- Default data collections subsection
  5450. --------------------------------------------------------------------------------------------------------------------------------
  5451. RAISERROR (N' |-Starting default data collections', 10, 1) WITH NOWAIT
  5452. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE is_default = 1 AND status = 1)
  5453. BEGIN
  5454. SELECT 'Instance_checks' AS [Category], 'Default_Trace' AS [Check], '[OK]' AS [Deviation]
  5455. END
  5456. ELSE
  5457. BEGIN
  5458. 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]
  5459. END;
  5460. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE [path] LIKE '%blackbox%.trc' AND status = 1)
  5461. BEGIN
  5462. 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]
  5463. END
  5464. ELSE
  5465. BEGIN
  5466. SELECT 'Instance_checks' AS [Category], 'Blackbox_Trace' AS [Information], '[OK]' AS [Deviation]
  5467. END;
  5468. IF EXISTS (SELECT TOP 1 id FROM sys.traces WHERE (is_default = 1 OR [path] LIKE '%blackbox%.trc') AND status = 1)
  5469. BEGIN
  5470. 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
  5471. FROM sys.traces
  5472. WHERE (is_default = 1 OR [path] LIKE '%blackbox%.trc') AND status = 1
  5473. END;
  5474. IF @sqlmajorver > 10
  5475. BEGIN
  5476. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] = 'system_health')
  5477. BEGIN
  5478. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_SystemHealth' AS [Check], '[OK]' AS [Deviation]
  5479. END
  5480. ELSE
  5481. BEGIN
  5482. 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]
  5483. END;
  5484. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] = 'sp_server_diagnostics session')
  5485. BEGIN
  5486. SELECT 'Instance_checks' AS [Category], 'xEvent_Session_sp_server_diagnostics' AS [Check], '[OK]' AS [Deviation]
  5487. END
  5488. ELSE
  5489. BEGIN
  5490. 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]
  5491. END;
  5492. IF EXISTS (SELECT TOP 1 name FROM sys.dm_xe_sessions WHERE [name] IN ('system_health', 'sp_server_diagnostics session'))
  5493. BEGIN
  5494. 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,
  5495. dropped_event_count, dropped_buffer_count, blocked_event_fire_time, create_time, largest_event_dropped_size
  5496. FROM sys.dm_xe_sessions
  5497. WHERE [name] IN ('system_health', 'sp_server_diagnostics session')
  5498. END;
  5499. END;
  5500. RAISERROR (N'|-Starting Database and tempDB Checks', 10, 1) WITH NOWAIT
  5501. --------------------------------------------------------------------------------------------------------------------------------
  5502. -- User objects in master DB
  5503. --------------------------------------------------------------------------------------------------------------------------------
  5504. RAISERROR (N' |-Starting User Objects in master DB', 10, 1) WITH NOWAIT
  5505. 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
  5506. BEGIN
  5507. SELECT 'Database_checks' AS [Category], 'User_Objects_in_master' AS [Check], '[WARNING: User objects are created in the master database]' AS [Deviation]
  5508. 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
  5509. FROM master.sys.all_objects sao
  5510. INNER JOIN master.sys.schemas ss ON sao.[schema_id] = ss.[schema_id]
  5511. WHERE sao.is_ms_shipped = 0
  5512. AND sao.[type] IN ('AF','FN','P','IF','PC','TF','TR','T','V')
  5513. ORDER BY sao.name, sao.type_desc;
  5514. END
  5515. ELSE
  5516. BEGIN
  5517. SELECT 'Database_checks' AS [Category], 'User_Objects_in_master' AS [Check], '[OK]' AS [Deviation]
  5518. END;
  5519. --------------------------------------------------------------------------------------------------------------------------------
  5520. -- DBs with collation <> master subsection
  5521. --------------------------------------------------------------------------------------------------------------------------------
  5522. RAISERROR (N' |-Starting DBs with collation <> master', 10, 1) WITH NOWAIT
  5523. DECLARE @master_collate NVARCHAR(128), @dif_collate int
  5524. SELECT @master_collate = collation_name FROM master.sys.databases (NOLOCK) WHERE database_id = 1;
  5525. SELECT @dif_collate = COUNT(collation_name) FROM master.sys.databases (NOLOCK) WHERE collation_name <> @master_collate;
  5526. IF @dif_collate >= 1
  5527. BEGIN
  5528. SELECT 'Database_checks' AS [Category], 'Collations' AS [Check], '[WARNING: Some user databases collation differ from the master Database_Collation]' AS [Deviation]
  5529. SELECT 'Database_checks' AS [Category], 'Collations' AS [Information], name AS [Database_Name], collation_name AS [Database_Collation], @master_collate AS [Master_Collation]
  5530. FROM master.sys.databases (NOLOCK)
  5531. WHERE collation_name <> @master_collate;
  5532. END
  5533. ELSE
  5534. BEGIN
  5535. SELECT 'Database_checks' AS [Category], 'Collations' AS [Check], '[OK]' AS [Deviation]
  5536. END;
  5537. --------------------------------------------------------------------------------------------------------------------------------
  5538. -- DBs with skewed compatibility level subsection
  5539. --------------------------------------------------------------------------------------------------------------------------------
  5540. RAISERROR (N' |-Starting DBs with skewed compatibility level', 10, 1) WITH NOWAIT
  5541. DECLARE @dif_compat int
  5542. SELECT @dif_compat = COUNT([compatibility_level]) FROM master.sys.databases (NOLOCK) WHERE [compatibility_level] <> @sqlmajorver * 10;
  5543. IF @dif_compat >= 1
  5544. BEGIN
  5545. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Check], '[WARNING: Some user databases have a non-optimal compatibility level]' AS [Deviation]
  5546. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Information], name AS [Database_Name], [compatibility_level] AS [Compatibility_Level]
  5547. FROM master.sys.databases (NOLOCK)
  5548. WHERE [compatibility_level] <> @sqlmajorver * 10;
  5549. END
  5550. ELSE
  5551. BEGIN
  5552. SELECT 'Database_checks' AS [Category], 'Compatibility_Level' AS [Check], '[OK]' AS [Deviation]
  5553. END;
  5554. --------------------------------------------------------------------------------------------------------------------------------
  5555. -- User DBs with non-default options subsection
  5556. --------------------------------------------------------------------------------------------------------------------------------
  5557. RAISERROR (N' |-Starting User DBs with non-default options', 10, 1) WITH NOWAIT
  5558. DECLARE @cnt int, @cnt_i int
  5559. DECLARE @is_auto_close_on bit, @is_auto_shrink_on bit, @page_verify_option bit
  5560. DECLARE @is_auto_create_stats_on bit, @is_auto_update_stats_on bit
  5561. DECLARE @is_db_chaining_on bit, @is_auto_create_stats_incremental_on bit--, @is_indirect_checkpoint_on bit
  5562. DECLARE @is_trustworthy_on bit, @is_parameterization_forced bit
  5563. DECLARE @dbopterrtb TABLE (id int,
  5564. name sysname,
  5565. is_auto_close_on bit,
  5566. is_auto_shrink_on bit,
  5567. page_verify_option tinyint,
  5568. page_verify_option_desc NVARCHAR(60),
  5569. is_auto_create_stats_on bit,
  5570. is_auto_update_stats_on bit,
  5571. is_db_chaining_on bit,
  5572. --is_indirect_checkpoint_on bit,
  5573. is_auto_create_stats_incremental_on bit NULL,
  5574. is_trustworthy_on bit,
  5575. is_parameterization_forced bit)
  5576. IF @sqlmajorver < 12
  5577. BEGIN
  5578. SET @sqlcmd = 'SELECT ROW_NUMBER() OVER(ORDER BY name), name, is_auto_close_on,
  5579. is_auto_shrink_on, page_verify_option, page_verify_option_desc,
  5580. is_auto_create_stats_on, is_auto_update_stats_on, is_db_chaining_on,
  5581. --0 AS is_indirect_checkpoint_on,
  5582. NULL AS is_auto_create_stats_incremental_on,
  5583. is_trustworthy_on, is_parameterization_forced
  5584. FROM master.sys.databases (NOLOCK)
  5585. WHERE database_id > 4 OR name = ''model'''
  5586. END
  5587. ELSE
  5588. BEGIN
  5589. SET @sqlcmd = 'SELECT ROW_NUMBER() OVER(ORDER BY name), name, is_auto_close_on,
  5590. is_auto_shrink_on, page_verify_option, page_verify_option_desc,
  5591. is_auto_create_stats_on, is_auto_update_stats_on,
  5592. is_db_chaining_on,
  5593. --CASE WHEN target_recovery_time_in_seconds > 0 THEN 1 ELSE 0 END AS is_indirect_checkpoint_on,
  5594. 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. INSERT INTO @dbopterrtb
  5600. EXECUTE sp_executesql @sqlcmd;
  5601. SET @cnt = (SELECT COUNT(id) FROM @dbopterrtb)
  5602. SET @cnt_i = 1
  5603. 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
  5604. WHILE @cnt_i <> @cnt
  5605. BEGIN
  5606. 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,
  5607. @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,
  5608. @page_verify_option = CASE WHEN page_verify_option <> 2 AND @page_verify_option = 0 THEN 1 ELSE @page_verify_option END,
  5609. @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,
  5610. @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,
  5611. @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,
  5612. --@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,
  5613. @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,
  5614. @is_trustworthy_on = CASE WHEN is_trustworthy_on = 1 AND @is_trustworthy_on = 0 THEN 1 ELSE @is_trustworthy_on END,
  5615. @is_parameterization_forced = CASE WHEN is_parameterization_forced = 1 AND @is_parameterization_forced = 0 THEN 1 ELSE @is_parameterization_forced END
  5616. FROM @dbopterrtb
  5617. WHERE id = @cnt_i;
  5618. SET @cnt_i = @cnt_i + 1
  5619. END
  5620. 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
  5621. BEGIN
  5622. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Check], '[WARNING: Some user databases may have Non-optimal_Settings]' AS [Deviation]
  5623. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Information],
  5624. name AS [Database_Name],
  5625. RTRIM(
  5626. CASE WHEN is_auto_close_on = 1 THEN 'Auto_Close;' ELSE '' END +
  5627. CASE WHEN is_auto_shrink_on = 1 THEN 'Auto_Shrink;' ELSE '' END +
  5628. CASE WHEN page_verify_option <> 2 THEN 'Page_Verify;' ELSE '' END +
  5629. CASE WHEN is_auto_create_stats_on = 0 THEN 'Auto_Create_Stats;' ELSE '' END +
  5630. CASE WHEN is_auto_update_stats_on = 0 THEN 'Auto_Update_Stats;' ELSE '' END +
  5631. CASE WHEN is_db_chaining_on = 1 THEN 'DB_Chaining;' ELSE '' END +
  5632. --CASE WHEN is_indirect_checkpoint_on = 1 THEN 'Indirect_Checkpoint;' ELSE '' END +
  5633. CASE WHEN is_auto_create_stats_incremental_on = 0 THEN 'Incremental_Stats;' ELSE '' END +
  5634. CASE WHEN is_trustworthy_on = 1 THEN 'Trustworthy_bit;' ELSE '' END +
  5635. CASE WHEN is_parameterization_forced = 1 THEN 'Forced_Parameterization;' ELSE '' END
  5636. ) AS [Non-optimal_Settings],
  5637. CASE WHEN is_auto_close_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Close],
  5638. CASE WHEN is_auto_shrink_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Shrink],
  5639. page_verify_option_desc AS [Page_Verify],
  5640. CASE WHEN is_auto_create_stats_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Create_Stats],
  5641. CASE WHEN is_auto_update_stats_on = 1 THEN 'ON' ELSE 'OFF' END AS [Auto_Update_Stats],
  5642. CASE WHEN is_db_chaining_on = 1 THEN 'ON' ELSE 'OFF' END AS [DB_Chaining],
  5643. --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.
  5644. 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],
  5645. CASE WHEN is_trustworthy_on = 1 THEN 'ON' ELSE 'OFF' END AS [Trustworthy_bit],
  5646. CASE WHEN is_parameterization_forced = 1 THEN 'ON' ELSE 'OFF' END AS [Forced_Parameterization]
  5647. FROM @dbopterrtb
  5648. 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)
  5649. 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;
  5650. END
  5651. ELSE
  5652. BEGIN
  5653. SELECT 'Database_checks' AS [Category], 'Database_Options' AS [Check], '[OK]' AS [Deviation]
  5654. END;
  5655. IF (SELECT COUNT(*) FROM master.sys.databases (NOLOCK) WHERE is_auto_update_stats_on = 0 AND is_auto_update_stats_async_on = 1) > 0
  5656. BEGIN
  5657. 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]
  5658. 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
  5659. END
  5660. ELSE
  5661. BEGIN
  5662. SELECT 'Database_checks' AS [Category], 'Database_Options_Disabled_Async_AutoUpdate' AS [Check], '[OK]' AS [Deviation]
  5663. END;
  5664. --------------------------------------------------------------------------------------------------------------------------------
  5665. -- DBs with Sparse files subsection
  5666. --------------------------------------------------------------------------------------------------------------------------------
  5667. RAISERROR (N' |-Starting DBs with Sparse files', 10, 1) WITH NOWAIT
  5668. -- 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
  5669. -- http://blogs.msdn.com/b/jorgepc/archive/2010/11/25/what-are-sparse-files-and-why-should-i-care-as-sql-server-dba.aspx
  5670. 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
  5671. BEGIN
  5672. 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]
  5673. SELECT 'Database_checks' AS [Category], 'DB_nonSnap_Sparse' AS [Information], DB_NAME(sd.database_id) AS database_name, smf.name, smf.physical_name
  5674. FROM sys.databases sd
  5675. INNER JOIN sys.master_files smf ON sd.database_id = smf.database_id
  5676. WHERE sd.source_database_id IS NULL AND smf.is_sparse = 1
  5677. END
  5678. ELSE
  5679. BEGIN
  5680. SELECT 'Database_checks' AS [Category], 'DB_nonSnap_Sparse' AS [Check], '[OK]' AS [Deviation]
  5681. END;
  5682. --------------------------------------------------------------------------------------------------------------------------------
  5683. -- DBs Autogrow in percentage subsection
  5684. --------------------------------------------------------------------------------------------------------------------------------
  5685. RAISERROR (N' |-Starting DBs Autogrow in percentage', 10, 1) WITH NOWAIT
  5686. IF (SELECT COUNT(is_percent_growth) FROM sys.master_files WHERE is_percent_growth = 1) > 0
  5687. BEGIN
  5688. 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]
  5689. SELECT 'Database_checks' AS [Category], 'Percent_Autogrows' AS [Information], database_id,
  5690. DB_NAME(database_id) AS [Database_Name],
  5691. mf.name AS [Logical_Name],
  5692. mf.size*8 AS [Current_Size_KB],
  5693. mf.type_desc AS [File_Type],
  5694. mf.[state_desc] AS [File_State],
  5695. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  5696. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount_KB],
  5697. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((mf.size*8)*CONVERT(bigint, mf.growth))/100
  5698. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  5699. ELSE 0 END AS [Next_Growth_KB],
  5700. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  5701. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  5702. ELSE '' END AS [Comments],
  5703. mf.is_read_only
  5704. FROM sys.master_files mf (NOLOCK)
  5705. WHERE is_percent_growth = 1
  5706. 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
  5707. ORDER BY DB_NAME(mf.database_id), mf.name
  5708. END
  5709. ELSE
  5710. BEGIN
  5711. SELECT 'Database_checks' AS [Category], 'Percent_Autogrows' AS [Check], '[OK]' AS [Deviation]
  5712. END;
  5713. --------------------------------------------------------------------------------------------------------------------------------
  5714. -- DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled) subsection
  5715. --------------------------------------------------------------------------------------------------------------------------------
  5716. RAISERROR (N' |-Starting DBs Autogrowth > 1GB in Logs or Data (when IFI is disabled)', 10, 1) WITH NOWAIT
  5717. IF (SELECT COUNT(growth) FROM sys.master_files (NOLOCK)
  5718. WHERE [type] >= CASE WHEN @ifi = 1 THEN 1 ELSE 0 END
  5719. AND [type] < 2
  5720. AND ((is_percent_growth = 1 AND ((CONVERT(bigint,size)*8)*growth)/100 > 1048576)
  5721. OR (is_percent_growth = 0 AND growth*8 > 1048576))) > 0
  5722. BEGIN
  5723. 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]
  5724. SELECT 'Database_checks' AS [Category], 'Large_Autogrows' AS [Information], database_id,
  5725. DB_NAME(database_id) AS [Database_Name],
  5726. mf.name AS [Logical_Name],
  5727. mf.size*8 AS [Current_Size_KB],
  5728. mf.[type_desc] AS [File_Type],
  5729. mf.[state_desc] AS [File_State],
  5730. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  5731. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount],
  5732. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((CONVERT(bigint,mf.size)*8)*mf.growth)/100
  5733. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  5734. ELSE 0 END AS [Next_Growth_KB],
  5735. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  5736. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  5737. ELSE '' END AS [Comments],
  5738. mf.is_read_only
  5739. FROM sys.master_files mf (NOLOCK)
  5740. WHERE mf.[type] >= CASE WHEN @ifi = 1 THEN 1 ELSE 0 END
  5741. AND mf.[type] < 2
  5742. AND ((is_percent_growth = 1 AND ((CONVERT(bigint,mf.size)*8)*mf.growth)/100 > 1048576)
  5743. OR (is_percent_growth = 0 AND mf.growth*8 > 1048576))
  5744. 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
  5745. ORDER BY DB_NAME(mf.database_id), mf.name
  5746. END
  5747. ELSE
  5748. BEGIN
  5749. SELECT 'Database_checks' AS [Category], 'Large_Autogrows' AS [Check], '[OK]' AS [Deviation]
  5750. END;
  5751. --------------------------------------------------------------------------------------------------------------------------------
  5752. -- VLF subsection
  5753. --------------------------------------------------------------------------------------------------------------------------------
  5754. RAISERROR (N' |-Starting VLF', 10, 1) WITH NOWAIT
  5755. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1
  5756. BEGIN
  5757. 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)
  5758. DECLARE @potsize DECIMAL(20,1), @n_iter int, @n_iter_final int, @initgrow DECIMAL(20,1), @n_init_iter int
  5759. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  5760. DROP TABLE #log_info1;
  5761. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  5762. CREATE TABLE #log_info1 (dbname VARCHAR(100),
  5763. Current_log_size_MB DECIMAL(20,1),
  5764. Used_Log_size_MB DECIMAL(20,1),
  5765. Potential_log_size_MB DECIMAL(20,1),
  5766. Current_VLFs int,
  5767. Used_VLFs int,
  5768. Avg_VLF_size_KB DECIMAL(20,1),
  5769. Potential_VLFs int,
  5770. Growth_iterations int,
  5771. Log_Initial_size_MB DECIMAL(20,1),
  5772. File_autogrow_MB DECIMAL(20,1))
  5773. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  5774. DROP TABLE #log_info2;
  5775. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  5776. CREATE TABLE #log_info2 (dbname VARCHAR(100),
  5777. Current_VLFs int,
  5778. VLF_size_KB DECIMAL(20,1),
  5779. growth_iteration int)
  5780. UPDATE #tmpdbs0
  5781. SET isdone = 0;
  5782. UPDATE #tmpdbs0
  5783. SET isdone = 1
  5784. WHERE [state] <> 0;
  5785. UPDATE #tmpdbs0
  5786. SET isdone = 1
  5787. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  5788. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  5789. BEGIN
  5790. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  5791. BEGIN
  5792. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  5793. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info3'))
  5794. DROP TABLE #log_info3;
  5795. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info3'))
  5796. CREATE TABLE #log_info3 (recoveryunitid int NULL,
  5797. fileid tinyint,
  5798. file_size bigint,
  5799. start_offset bigint,
  5800. FSeqNo int,
  5801. [status] tinyint,
  5802. parity tinyint,
  5803. create_lsn numeric(25,0))
  5804. SET @query = 'DBCC LOGINFO (' + '''' + @dbname + ''') WITH NO_INFOMSGS'
  5805. IF @sqlmajorver < 11
  5806. BEGIN
  5807. INSERT INTO #log_info3 (fileid, file_size, start_offset, FSeqNo, [status], parity, create_lsn)
  5808. EXEC (@query)
  5809. END
  5810. ELSE
  5811. BEGIN
  5812. INSERT INTO #log_info3 (recoveryunitid, fileid, file_size, start_offset, FSeqNo, [status], parity, create_lsn)
  5813. EXEC (@query)
  5814. END
  5815. SET @count = @@ROWCOUNT
  5816. SET @count_used = (SELECT COUNT(fileid) FROM #log_info3 l WHERE l.[status] = 2)
  5817. SET @logsize = (SELECT (MIN(l.start_offset) + SUM(l.file_size))/1048576.00 FROM #log_info3 l)
  5818. 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)
  5819. SET @avgvlfsize = (SELECT AVG(l.file_size)/1024.00 FROM #log_info3 l)
  5820. INSERT INTO #log_info2
  5821. SELECT @dbname, COUNT(create_lsn), MIN(l.file_size)/1024.00,
  5822. ROW_NUMBER() OVER(ORDER BY l.create_lsn) FROM #log_info3 l
  5823. GROUP BY l.create_lsn
  5824. ORDER BY l.create_lsn
  5825. DROP TABLE #log_info3;
  5826. -- Grow logs in MB instead of GB because of known issue prior to SQL 2012.
  5827. -- More detail here: http://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx
  5828. -- and http://connect.microsoft.com/SQLServer/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately
  5829. -- or https://connect.microsoft.com/SQLServer/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb
  5830. IF @sqlmajorver >= 11
  5831. BEGIN
  5832. SET @n_iter = (SELECT CASE WHEN @logsize <= 64 THEN 1
  5833. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)
  5834. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)
  5835. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)
  5836. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)
  5837. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4096, 0)
  5838. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8192, 0)
  5839. END)
  5840. SET @potsize = (SELECT CASE WHEN @logsize <= 64 THEN 1*64
  5841. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)*256
  5842. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)*512
  5843. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)*1024
  5844. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)*2048
  5845. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4096, 0)*4096
  5846. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8192, 0)*8192
  5847. END)
  5848. END
  5849. ELSE
  5850. BEGIN
  5851. SET @n_iter = (SELECT CASE WHEN @logsize <= 64 THEN 1
  5852. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)
  5853. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)
  5854. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)
  5855. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)
  5856. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4000, 0)
  5857. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8000, 0)
  5858. END)
  5859. SET @potsize = (SELECT CASE WHEN @logsize <= 64 THEN 1*64
  5860. WHEN @logsize > 64 AND @logsize < 256 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/256, 0)*256
  5861. WHEN @logsize >= 256 AND @logsize < 1024 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/512, 0)*512
  5862. WHEN @logsize >= 1024 AND @logsize < 4096 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/1024, 0)*1024
  5863. WHEN @logsize >= 4096 AND @logsize < 8192 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/2048, 0)*2048
  5864. WHEN @logsize >= 8192 AND @logsize < 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/4000, 0)*4000
  5865. WHEN @logsize >= 16384 THEN ROUND(CONVERT(FLOAT, ROUND(@logsize, -2))/8000, 0)*8000
  5866. END)
  5867. END
  5868. -- If the proposed log size is smaller than current log, and also smaller than 4GB,
  5869. -- and there is less than 512MB of diff between the current size and proposed size, add 1 grow.
  5870. SET @n_iter_final = @n_iter
  5871. IF @logsize > @potsize AND @potsize <= 4096 AND ABS(@logsize - @potsize) < 512
  5872. BEGIN
  5873. SET @n_iter_final = @n_iter + 1
  5874. END
  5875. -- If the proposed log size is larger than current log, and also larger than 50GB,
  5876. -- and there is less than 1GB of diff between the current size and proposed size, take 1 grow.
  5877. ELSE IF @logsize < @potsize AND @potsize <= 51200 AND ABS(@logsize - @potsize) > 1024
  5878. BEGIN
  5879. SET @n_iter_final = @n_iter - 1
  5880. END
  5881. IF @potsize = 0
  5882. BEGIN
  5883. SET @potsize = 64
  5884. END
  5885. IF @n_iter = 0
  5886. BEGIN
  5887. SET @n_iter = 1
  5888. END
  5889. SET @potsize = (SELECT CASE WHEN @n_iter < @n_iter_final THEN @potsize + (@potsize/@n_iter)
  5890. WHEN @n_iter > @n_iter_final THEN @potsize - (@potsize/@n_iter)
  5891. ELSE @potsize END)
  5892. SET @n_init_iter = @n_iter_final
  5893. IF @potsize >= 8192
  5894. BEGIN
  5895. SET @initgrow = @potsize/@n_iter_final
  5896. END
  5897. IF @potsize >= 64 AND @potsize <= 512
  5898. BEGIN
  5899. SET @n_init_iter = 1
  5900. SET @initgrow = 512
  5901. END
  5902. IF @potsize > 512 AND @potsize <= 1024
  5903. BEGIN
  5904. SET @n_init_iter = 1
  5905. SET @initgrow = 1023
  5906. END
  5907. IF @potsize > 1024 AND @potsize < 8192
  5908. BEGIN
  5909. SET @n_init_iter = 1
  5910. SET @initgrow = @potsize
  5911. END
  5912. INSERT INTO #log_info1
  5913. VALUES(@dbname, @logsize, @usedlogsize, @potsize, @count, @count_used, @avgvlfsize,
  5914. CASE WHEN @potsize <= 64 THEN (@potsize/(@potsize/@n_init_iter))*4
  5915. WHEN @potsize > 64 AND @potsize < 1024 THEN (@potsize/(@potsize/@n_init_iter))*8
  5916. WHEN @potsize >= 1024 THEN (@potsize/(@potsize/@n_init_iter))*16
  5917. END,
  5918. @n_init_iter, @initgrow,
  5919. CASE WHEN (@potsize/@n_iter_final) <= 1024 THEN (@potsize/@n_iter_final) ELSE 1024 END
  5920. );
  5921. UPDATE #tmpdbs0
  5922. SET isdone = 1
  5923. WHERE [dbid] = @dbid
  5924. END
  5925. END;
  5926. IF (SELECT COUNT(dbname) FROM #log_info1 WHERE Current_VLFs >= 50) > 0
  5927. BEGIN
  5928. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Check], '[WARNING: Some user databases have many VLFs. Please review these]' AS [Deviation]
  5929. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Information], dbname AS [Database_Name], Current_log_size_MB, Used_Log_size_MB,
  5930. Potential_log_size_MB, Current_VLFs, Used_VLFs, Potential_VLFs, Growth_iterations, Log_Initial_size_MB, File_autogrow_MB
  5931. FROM #log_info1
  5932. WHERE Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5933. ORDER BY dbname;
  5934. 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
  5935. FROM #log_info2
  5936. INNER JOIN #log_info1 ON #log_info2.dbname = #log_info1.dbname
  5937. WHERE #log_info1.Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5938. ORDER BY #log_info2.dbname, growth_iteration
  5939. 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
  5940. FROM #log_info2
  5941. INNER JOIN #log_info1 ON #log_info2.dbname = #log_info1.dbname
  5942. WHERE #log_info1.Current_VLFs >= 50 -- My rule of thumb is 50 VLFs. Your mileage may vary.
  5943. GROUP BY #log_info2.dbname, VLF_size_KB
  5944. ORDER BY #log_info2.dbname, VLF_size_KB DESC
  5945. END
  5946. ELSE
  5947. BEGIN
  5948. SELECT 'Database_checks' AS [Category], 'Virtual_Log_Files' AS [Check], '[OK]' AS [Deviation]
  5949. /*
  5950. 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
  5951. FROM #log_info1
  5952. ORDER BY dbname;
  5953. 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
  5954. FROM #log_info2
  5955. ORDER BY dbname, growth_iteration
  5956. 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
  5957. FROM #log_info2
  5958. GROUP BY dbname, VLF_size_KB
  5959. ORDER BY dbname, VLF_size_KB DESC
  5960. */
  5961. END
  5962. END
  5963. ELSE
  5964. BEGIN
  5965. RAISERROR('[WARNING: Only a sysadmin can run the "VLF" check. Bypassing check]', 16, 1, N'sysadmin')
  5966. --RETURN
  5967. END;
  5968. --------------------------------------------------------------------------------------------------------------------------------
  5969. -- Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware) subsection
  5970. --------------------------------------------------------------------------------------------------------------------------------
  5971. RAISERROR (N' |-Starting Data files and Logs / tempDB and user Databases / Backups and Database files in same volume (Mountpoint aware)', 10, 1) WITH NOWAIT
  5972. IF @allow_xpcmdshell = 1
  5973. BEGIN
  5974. DECLARE /*@dbid int,*/ @ctr2 int, @ctr3 int, @ctr4 int, @pserr bit
  5975. SET @pserr = 0
  5976. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  5977. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5978. AND (SELECT COUNT(credential_id) FROM sys.credentials WHERE name = '##xp_cmdshell_proxy_account##') > 0) -- Is not sysadmin but proxy account exists
  5979. AND (SELECT COUNT(l.name)
  5980. FROM sys.server_permissions p (NOLOCK) INNER JOIN sys.server_principals l (NOLOCK)
  5981. ON p.grantee_principal_id = l.principal_id
  5982. AND p.class = 100 -- Server
  5983. AND p.state IN ('G', 'W') -- Granted or Granted with Grant
  5984. AND l.is_disabled = 0
  5985. AND p.permission_name = 'ALTER SETTINGS'
  5986. AND QUOTENAME(l.name) = QUOTENAME(USER_NAME())) = 0) -- Is not sysadmin but has alter settings permission
  5987. OR ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1
  5988. AND ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_fileexist') > 0 AND
  5989. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_instance_regread') > 0 AND
  5990. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regread') > 0 AND
  5991. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OAGetErrorInfo') > 0 AND
  5992. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OACreate') > 0 AND
  5993. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_OADestroy') > 0 AND
  5994. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_cmdshell') > 0 AND
  5995. (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_regenumvalues') > 0)))
  5996. BEGIN
  5997. IF @sqlmajorver < 11 OR (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild <= 2500)
  5998. BEGIN
  5999. DECLARE @pstbl TABLE ([KeyExist] int)
  6000. BEGIN TRY
  6001. INSERT INTO @pstbl
  6002. EXEC master.sys.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\PowerShell\1' -- check if Powershell is installed
  6003. END TRY
  6004. BEGIN CATCH
  6005. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  6006. SELECT @ErrorMessage = 'Data files and Logs in same volume (Mountpoint aware) subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  6007. RAISERROR (@ErrorMessage, 16, 1);
  6008. END CATCH
  6009. SELECT @sao = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'show advanced options'
  6010. SELECT @xcmd = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'xp_cmdshell'
  6011. SELECT @ole = CAST([value] AS smallint) FROM sys.configurations (NOLOCK) WHERE [name] = 'Ole Automation Procedures'
  6012. RAISERROR (' |-Configuration options set for Data and Log location check', 10, 1) WITH NOWAIT
  6013. IF @sao = 0
  6014. BEGIN
  6015. EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE;
  6016. END
  6017. IF @xcmd = 0
  6018. BEGIN
  6019. EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;
  6020. END
  6021. IF @ole = 0
  6022. BEGIN
  6023. EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
  6024. END
  6025. IF (SELECT [KeyExist] FROM @pstbl) = 1
  6026. BEGIN
  6027. DECLARE @ctr int
  6028. DECLARE @output_hw_tot TABLE ([PS_OUTPUT] NVARCHAR(2048));
  6029. DECLARE @output_hw_format TABLE ([volid] smallint IDENTITY(1,1), [HD_Volume] NVARCHAR(2048) NULL)
  6030. IF @custompath IS NULL
  6031. BEGIN
  6032. IF @sqlmajorver < 11
  6033. BEGIN
  6034. EXEC master..xp_instance_regread N'HKEY_LOCAL_MACHINE',N'Software\Microsoft\MSSQLServer\Setup',N'SQLPath', @path OUTPUT
  6035. SET @path = @path + '\LOG'
  6036. END
  6037. ELSE
  6038. BEGIN
  6039. SET @sqlcmd = N'SELECT @pathOUT = LEFT([path], LEN([path])-1) FROM sys.dm_os_server_diagnostics_log_configurations';
  6040. SET @params = N'@pathOUT NVARCHAR(2048) OUTPUT';
  6041. EXECUTE sp_executesql @sqlcmd, @params, @pathOUT=@path OUTPUT;
  6042. END
  6043. -- Create COM object with FSO
  6044. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
  6045. IF @OLEResult <> 0
  6046. BEGIN
  6047. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  6048. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  6049. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6050. END
  6051. ELSE
  6052. BEGIN
  6053. EXEC @OLEResult = master.dbo.sp_OAMethod @FSO, 'FolderExists', @existout OUT, @path
  6054. IF @OLEResult <> 0
  6055. BEGIN
  6056. EXEC sp_OAGetErrorInfo @FSO, @src OUT, @desc OUT
  6057. SELECT @ErrorMessage = 'Error Calling FolderExists Method 0x%x, %s, %s'
  6058. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6059. END
  6060. ELSE
  6061. BEGIN
  6062. IF @existout <> 1
  6063. BEGIN
  6064. SET @path = CONVERT(NVARCHAR(500), SERVERPROPERTY('ErrorLogFileName'))
  6065. SET @path = LEFT(@path,LEN(@path)-CHARINDEX('\', REVERSE(@path)))
  6066. END
  6067. END
  6068. EXEC @OLEResult = sp_OADestroy @FSO
  6069. END
  6070. END
  6071. ELSE
  6072. BEGIN
  6073. SELECT @path = CASE WHEN @custompath LIKE '%\' THEN LEFT(@custompath, LEN(@custompath)-1) ELSE @custompath END
  6074. END
  6075. SET @FileName = @path + '\checkbp_' + RTRIM(@server) + '.ps1'
  6076. EXEC master.dbo.xp_fileexist @FileName, @existout out
  6077. IF @existout = 0
  6078. BEGIN
  6079. -- Scan for local disks
  6080. SET @Text1 = '[string] $serverName = ''localhost''
  6081. $vols = Get-WmiObject -computername $serverName -query "select Name from Win32_Volume where Capacity <> NULL and DriveType = 3"
  6082. foreach($vol in $vols)
  6083. {
  6084. [string] $drive = "{0}" -f $vol.name
  6085. Write-Output $drive
  6086. }'
  6087. -- Create COM object with FSO
  6088. EXEC @OLEResult = master.dbo.sp_OACreate 'Scripting.FileSystemObject', @FS OUT
  6089. IF @OLEResult <> 0
  6090. BEGIN
  6091. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6092. SELECT @ErrorMessage = 'Error Creating COM Component 0x%x, %s, %s'
  6093. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6094. END
  6095. --Open file
  6096. EXEC @OLEResult = master.dbo.sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FileName, 2, 1
  6097. IF @OLEResult <> 0
  6098. BEGIN
  6099. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6100. SELECT @ErrorMessage = 'Error Calling OpenTextFile Method 0x%x, %s, %s' + CHAR(10) + 'Could not create file ' + @FileName
  6101. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6102. END
  6103. ELSE
  6104. BEGIN
  6105. SELECT @ErrorMessage = ' |-Created file ' + @FileName
  6106. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6107. END
  6108. --Write Text1
  6109. EXEC @OLEResult = master.dbo.sp_OAMethod @FileID, 'WriteLine', NULL, @Text1
  6110. IF @OLEResult <> 0
  6111. BEGIN
  6112. EXEC sp_OAGetErrorInfo @FS, @src OUT, @desc OUT
  6113. SELECT @ErrorMessage = 'Error Calling WriteLine Method 0x%x, %s, %s' + CHAR(10) + 'Could not write to file ' + @FileName
  6114. RAISERROR (@ErrorMessage, 16, 1, @OLEResult, @src, @desc);
  6115. END
  6116. EXEC @OLEResult = sp_OADestroy @FileID
  6117. EXEC @OLEResult = sp_OADestroy @FS
  6118. END;
  6119. ELSE
  6120. BEGIN
  6121. SELECT @ErrorMessage = ' |-Reusing file ' + @FileName
  6122. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6123. END
  6124. IF @psver = 1
  6125. BEGIN
  6126. SET @CMD = 'powershell -NoLogo -NoProfile "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  6127. END
  6128. ELSE
  6129. BEGIN
  6130. SET @CMD = 'powershell -NoLogo -NoProfile -File "' + @FileName + '" -ExecutionPolicy RemoteSigned'
  6131. END;
  6132. INSERT INTO @output_hw_tot
  6133. EXEC master.dbo.xp_cmdshell @CMD
  6134. SET @CMD = 'del /Q "' + @FileName + '"'
  6135. EXEC master.dbo.xp_cmdshell @CMD, NO_OUTPUT
  6136. IF (SELECT COUNT([PS_OUTPUT])
  6137. FROM @output_hw_tot WHERE [PS_OUTPUT] LIKE '%cannot be loaded because%'
  6138. OR [PS_OUTPUT] LIKE '%scripts is disabled%'
  6139. OR [PS_OUTPUT] LIKE '%scripts est désactivée%') = 0
  6140. BEGIN
  6141. INSERT INTO @output_hw_format ([HD_Volume])
  6142. SELECT RTRIM([PS_OUTPUT])
  6143. FROM @output_hw_tot
  6144. WHERE [PS_OUTPUT] IS NOT NULL
  6145. END
  6146. ELSE
  6147. BEGIN
  6148. SET @pserr = 1
  6149. RAISERROR ('[WARNING: Powershell script cannot be loaded because the execution of scripts is disabled on this system.
  6150. To change the execution policy, type the following command in Powershell console: Set-ExecutionPolicy RemoteSigned
  6151. The Set-ExecutionPolicy cmdlet enables you to determine which Windows PowerShell scripts (if any) will be allowed to run on your computer.
  6152. Windows PowerShell has four different execution policies:
  6153. Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  6154. AllSigned - Only scripts signed by a trusted publisher can be run.
  6155. RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  6156. |- REQUIRED by BP Check
  6157. Unrestricted - No restrictions; all Windows PowerShell scripts can be run.]
  6158. ',16,1);
  6159. END
  6160. SET @CMD2 = 'del ' + @FileName
  6161. EXEC master.dbo.xp_cmdshell @CMD2, NO_OUTPUT;
  6162. END
  6163. ELSE
  6164. BEGIN
  6165. SET @pserr = 1
  6166. RAISERROR ('[WARNING: Powershell is not present. Bypassing Data files and Logs in same volume check]',16,1);
  6167. END
  6168. IF @xcmd = 0
  6169. BEGIN
  6170. EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE WITH OVERRIDE;
  6171. END
  6172. IF @ole = 0
  6173. BEGIN
  6174. EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE WITH OVERRIDE;
  6175. END
  6176. IF @sao = 0
  6177. BEGIN
  6178. EXEC sp_configure 'show advanced options', 0; RECONFIGURE WITH OVERRIDE;
  6179. END
  6180. END
  6181. ELSE
  6182. BEGIN
  6183. INSERT INTO @output_hw_format ([HD_Volume])
  6184. 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')
  6185. END;
  6186. IF @pserr = 0
  6187. BEGIN
  6188. -- select mountpoints only
  6189. DECLARE @intertbl TABLE (physical_name nvarchar(260))
  6190. INSERT INTO @intertbl
  6191. SELECT physical_name
  6192. FROM sys.master_files t1 (NOLOCK)
  6193. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6194. WHERE ([database_id] > 4 OR [database_id] = 2)
  6195. AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3
  6196. -- select database files in mountpoints
  6197. DECLARE @filetbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6198. INSERT INTO @filetbl
  6199. SELECT database_id, type, file_id, physical_name, volid
  6200. FROM sys.master_files t1 (NOLOCK)
  6201. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6202. WHERE ([database_id] > 4 OR [database_id] = 2) AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3
  6203. UNION ALL
  6204. -- select database files not in mountpoints
  6205. SELECT database_id, type, file_id, physical_name, volid
  6206. FROM sys.master_files t1 (NOLOCK)
  6207. INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6208. WHERE ([database_id] > 4 OR [database_id] = 2) AND [database_id] <> 32767 AND physical_name NOT IN (SELECT physical_name FROM @intertbl)
  6209. SELECT @ctr = COUNT(DISTINCT(t1.[database_id])) FROM @filetbl t1
  6210. INNER JOIN @filetbl t2 ON t1.database_id = t2.database_id
  6211. AND t1.[type] <> t2.[type]
  6212. AND ((t1.[type] = 1 AND t2.[type] <> 1) OR (t2.[type] = 1 AND t1.[type] <> 1))
  6213. AND t1.volid = t2.volid;
  6214. IF @ctr > 0
  6215. BEGIN
  6216. 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]
  6217. 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
  6218. FROM sys.master_files mf (NOLOCK) INNER JOIN @filetbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6219. INNER JOIN @filetbl t2 ON t1.database_id = t2.database_id
  6220. AND t1.[type] <> t2.[type]
  6221. AND ((t1.[type] = 1 AND t2.[type] <> 1) OR (t2.[type] = 1 AND t1.[type] <> 1))
  6222. AND t1.volid = t2.volid
  6223. ORDER BY mf.physical_name OPTION (RECOMPILE);
  6224. END
  6225. ELSE
  6226. BEGIN
  6227. SELECT 'Database_checks' AS [Category], 'Data_and_Log_locations' AS [Check], '[OK]' AS [Deviation]
  6228. END;
  6229. -- select backup mountpoints only
  6230. DECLARE @interbcktbl TABLE (physical_device_name nvarchar(260))
  6231. INSERT INTO @interbcktbl
  6232. SELECT physical_device_name
  6233. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6234. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6235. WHERE LEN(t2.HD_Volume) > 3
  6236. -- select backups in mountpoints only
  6237. DECLARE @bcktbl TABLE (physical_device_name nvarchar(260), HD_Volume nvarchar(260))
  6238. INSERT INTO @bcktbl
  6239. SELECT physical_device_name, RTRIM(t2.HD_Volume)
  6240. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6241. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6242. WHERE LEN(t2.HD_Volume) > 3
  6243. -- select backups not in mountpoints
  6244. UNION ALL
  6245. SELECT physical_device_name, RTRIM(t2.HD_Volume)
  6246. FROM msdb.dbo.backupmediafamily t1 (NOLOCK)
  6247. INNER JOIN @output_hw_format t2 ON LEFT(physical_device_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6248. WHERE physical_device_name NOT IN (SELECT physical_device_name FROM @interbcktbl);
  6249. SELECT @ctr4 = COUNT(DISTINCT(physical_device_name)) FROM @bcktbl;
  6250. IF @ctr4 > 0
  6251. BEGIN
  6252. 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]
  6253. 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]
  6254. FROM @bcktbl
  6255. OPTION (RECOMPILE);
  6256. END
  6257. ELSE
  6258. BEGIN
  6259. SELECT 'Database_checks' AS [Category], 'Backup_and_Database_locations' AS [Check], '[OK]' AS [Deviation]
  6260. END;
  6261. -- select tempDB mountpoints only
  6262. DECLARE @intertbl2 TABLE (physical_name nvarchar(260))
  6263. INSERT INTO @intertbl2
  6264. SELECT physical_name
  6265. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2
  6266. ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6267. WHERE [database_id] = 2 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6268. -- select user DBs mountpoints only
  6269. DECLARE @intertbl3 TABLE (physical_name nvarchar(260))
  6270. INSERT INTO @intertbl3
  6271. SELECT physical_name
  6272. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2
  6273. ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6274. WHERE [database_id] > 4 AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6275. -- select tempDB files in mountpoints
  6276. DECLARE @tempDBtbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6277. INSERT INTO @tempDBtbl
  6278. SELECT database_id, type, file_id, physical_name, volid
  6279. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6280. WHERE [database_id] = 2 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6281. UNION ALL
  6282. SELECT database_id, type, file_id, physical_name, volid
  6283. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6284. WHERE [database_id] = 2 AND [type] = 0 AND physical_name NOT IN (SELECT physical_name FROM @intertbl2)
  6285. -- select user DBs files in mountpoints
  6286. DECLARE @otherstbl TABLE (database_id int, type tinyint, file_id int, physical_name nvarchar(260), volid smallint)
  6287. INSERT INTO @otherstbl
  6288. SELECT database_id, type, file_id, physical_name, volid
  6289. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6290. WHERE [database_id] > 4 AND [database_id] <> 32767 AND LEN(t2.HD_Volume) > 3 AND [type] = 0
  6291. UNION ALL
  6292. SELECT database_id, type, file_id, physical_name, volid
  6293. FROM sys.master_files t1 (NOLOCK) INNER JOIN @output_hw_format t2 ON LEFT(physical_name, LEN(t2.HD_Volume)) = RTRIM(t2.HD_Volume)
  6294. WHERE [database_id] > 4 AND [database_id] <> 32767 AND [type] = 0 AND physical_name NOT IN (SELECT physical_name FROM @intertbl3)
  6295. SELECT @ctr2 = COUNT(*) FROM @tempDBtbl WHERE LEFT(physical_name, 1) = 'C'
  6296. SELECT @ctr3 = COUNT(DISTINCT(t1.[database_id])) FROM @otherstbl t1 INNER JOIN @tempDBtbl t2 ON t1.volid = t2.volid;
  6297. IF @ctr3 > 0
  6298. BEGIN
  6299. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: tempDB is on the same physical volume as user databases]' AS [Deviation];
  6300. END
  6301. ELSE IF @ctr2 > 0
  6302. BEGIN
  6303. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: tempDB is on C: drive]' AS [Deviation]
  6304. END
  6305. ELSE
  6306. BEGIN
  6307. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[OK]' AS [Deviation]
  6308. END;
  6309. IF @ctr2 > 0 OR @ctr3 > 0
  6310. BEGIN
  6311. 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
  6312. FROM sys.master_files mf (NOLOCK) INNER JOIN @otherstbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6313. INNER JOIN @tempDBtbl t2 ON t1.volid = t2.volid
  6314. UNION ALL
  6315. 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
  6316. FROM sys.master_files mf (NOLOCK) INNER JOIN @tempDBtbl t1 ON mf.database_id = t1.database_id AND mf.physical_name = t1.physical_name
  6317. ORDER BY DB_NAME(mf.[database_id]) OPTION (RECOMPILE);
  6318. END
  6319. END
  6320. ELSE
  6321. BEGIN
  6322. SELECT 'Database_checks' AS [Category], 'Data_and_Log_locations' AS [Check], '[WARNING: Could not gather information on file locations]' AS [Deviation]
  6323. SELECT 'tempDB_checks' AS [Category], 'tempDB_location' AS [Check], '[WARNING: Could not gather information on file locations]' AS [Deviation]
  6324. END
  6325. END
  6326. ELSE
  6327. BEGIN
  6328. 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')
  6329. 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')
  6330. --RETURN
  6331. END
  6332. END
  6333. ELSE
  6334. BEGIN
  6335. 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')
  6336. --RETURN
  6337. END;
  6338. --------------------------------------------------------------------------------------------------------------------------------
  6339. -- tempDB data file configurations subsection
  6340. --------------------------------------------------------------------------------------------------------------------------------
  6341. RAISERROR (N' |-Starting tempDB data file configurations', 10, 1) WITH NOWAIT
  6342. DECLARE @tdb_files int, @online_count int, @filesizes smallint
  6343. SELECT @tdb_files = COUNT(physical_name) FROM sys.master_files (NOLOCK) WHERE database_id = 2 AND [type] = 0;
  6344. SELECT @online_count = COUNT(cpu_id) FROM sys.dm_os_schedulers WHERE is_online = 1 AND scheduler_id < 255 AND parent_node_id < 64;
  6345. SELECT @filesizes = COUNT(DISTINCT size) FROM tempdb.sys.database_files WHERE [type] = 0;
  6346. 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)*/
  6347. OR (@tdb_files >= (@online_count / 2) AND @tdb_files >= 8 AND @tdb_files % 4 = 0)) THEN 0 ELSE 1 END) = 0
  6348. BEGIN
  6349. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Check], '[OK]' AS [Deviation]
  6350. 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]
  6351. FROM tempdb.sys.database_files (NOLOCK)
  6352. WHERE type = 0;
  6353. END
  6354. ELSE
  6355. BEGIN
  6356. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Check],
  6357. 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]'
  6358. 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]'
  6359. 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]'
  6360. WHEN @filesizes = 1 AND @tdb_files >= 4 AND @tdb_files % 4 > 0 THEN '[WARNING: Number of data files is not multiple of 4]'
  6361. WHEN @filesizes > 1 AND @tdb_files >= 4 AND @tdb_files % 4 = 0 THEN '[WARNING: Data file sizes do not match]'
  6362. ELSE '[OK]' END AS [Deviation];
  6363. SELECT 'tempDB_checks' AS [Category], 'tempDB_files' AS [Information], physical_name AS [tempDB_Files], CAST((size*8)/1024.0 AS DECIMAL(18,2)) AS [File_Size_MB]
  6364. FROM tempdb.sys.database_files (NOLOCK)
  6365. WHERE type = 0;
  6366. END;
  6367. --------------------------------------------------------------------------------------------------------------------------------
  6368. -- tempDB data files autogrow of equal size subsection
  6369. --------------------------------------------------------------------------------------------------------------------------------
  6370. RAISERROR (N' |-Starting tempDB Files autogrow of equal size', 10, 1) WITH NOWAIT
  6371. IF (SELECT COUNT(DISTINCT growth) FROM sys.master_files WHERE [database_id] = 2 AND [type] = 0) > 1
  6372. OR (SELECT COUNT(DISTINCT is_percent_growth) FROM sys.master_files WHERE [database_id] = 2 AND [type] = 0) > 1
  6373. BEGIN
  6374. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Check], '[WARNING: Some tempDB data files have different growth settings]' AS [Deviation]
  6375. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Information],
  6376. DB_NAME(2) AS [Database_Name],
  6377. mf.name AS [Logical_Name],
  6378. mf.[size]*8 AS [Current_Size_KB],
  6379. mf.type_desc AS [File_Type],
  6380. CASE WHEN is_percent_growth = 1 THEN 'pct' ELSE 'pages' END AS [Growth_Type],
  6381. CASE WHEN is_percent_growth = 1 THEN mf.growth ELSE mf.growth*8 END AS [Growth_Amount],
  6382. CASE WHEN is_percent_growth = 1 AND mf.growth > 0 THEN ((mf.size*8)*CONVERT(bigint, mf.growth))/100
  6383. WHEN is_percent_growth = 0 AND mf.growth > 0 THEN mf.growth*8
  6384. ELSE 0 END AS [Next_Growth_KB],
  6385. CASE WHEN @ifi = 0 AND mf.type = 0 THEN 'Instant File Initialization is disabled'
  6386. WHEN @ifi = 1 AND mf.type = 0 THEN 'Instant File Initialization is enabled'
  6387. ELSE '' END AS [Comments]
  6388. FROM tempdb.sys.database_files mf (NOLOCK)
  6389. WHERE [type] = 0
  6390. GROUP BY mf.name, mf.[size], is_percent_growth, mf.growth, mf.type_desc, mf.[type]
  6391. ORDER BY 3, 4
  6392. END
  6393. ELSE
  6394. BEGIN
  6395. SELECT 'tempDB_checks' AS [Category], 'tempDB_files_Autogrow' AS [Check], '[OK]' AS [Deviation]
  6396. END;
  6397. IF @ptochecks = 1
  6398. RAISERROR (N'|-Starting Performance Checks', 10, 1) WITH NOWAIT
  6399. --------------------------------------------------------------------------------------------------------------------------------
  6400. -- Perf counters, Waits, Latches and Spinlocks subsection
  6401. --------------------------------------------------------------------------------------------------------------------------------
  6402. IF @ptochecks = 1
  6403. BEGIN
  6404. SELECT @ErrorMessage = ' |-Starting Perf counters, Waits and Latches (wait for ' + CONVERT(VARCHAR(3), @duration) + 's)'
  6405. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT
  6406. DECLARE @minctr DATETIME, @maxctr DATETIME, @durationstr NVARCHAR(24)
  6407. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  6408. DROP TABLE #tblPerfCount;
  6409. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  6410. CREATE TABLE #tblPerfCount (
  6411. [retrieval_time] [datetime],
  6412. [object_name] [NVARCHAR](128),
  6413. [counter_name] [NVARCHAR](128),
  6414. [instance_name] [NVARCHAR](128),
  6415. [counter_name_type] int,
  6416. [cntr_value] float NULL
  6417. );
  6418. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  6419. DROP TABLE tempdb.dbo.tblPerfThresholds;
  6420. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  6421. CREATE TABLE tempdb.dbo.tblPerfThresholds (
  6422. [counter_family] [NVARCHAR](128),
  6423. [counter_name] [NVARCHAR](128),
  6424. [counter_instance] [NVARCHAR](128),
  6425. [counter_name_type] int,
  6426. [counter_value] float NULL
  6427. );
  6428. -- Create the helper function
  6429. 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')
  6430. EXEC ('USE tempdb; EXEC(''
  6431. CREATE FUNCTION dbo.fn_perfctr (@ctr1Fam NVARCHAR(128), @ctr1 NVARCHAR(128))
  6432. RETURNS float
  6433. AS
  6434. BEGIN
  6435. DECLARE @ReturnVals float, @ctr1Val float, @ctr2Val float, @ctr2Fam NVARCHAR(128), @ctr2 NVARCHAR(128), @type tinyint
  6436. -- ctr1Fam = source counter object; ctr1 = source counter; ctr2Fam = counter object to compare with; ctr2 = counter to compare with
  6437. -- 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
  6438. IF @ctr1 IN (''''Forwarded Records/sec'''',''''FreeSpace Scans/sec'''',''''Page Splits/sec'''',''''Workfiles Created/sec'''',''''Page lookups/sec'''',''''SQL Compilations/sec'''')
  6439. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''Batch Requests/sec'''', @type = 1
  6440. ELSE IF @ctr1 = ''''Lock Requests/sec''''
  6441. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''Batch Requests/sec'''', @type = 0
  6442. ELSE IF @ctr1 = ''''Full Scans/sec''''
  6443. SELECT @ctr2Fam = ''''SQLServer:Access Methods'''', @ctr2 = ''''Index Searches/sec'''', @type = 1
  6444. ELSE IF @ctr1 = ''''Index Searches/sec''''
  6445. SELECT @ctr2Fam = ''''SQLServer:Access Methods'''', @ctr2 = ''''Full Scans/sec'''', @type = 3
  6446. ELSE IF @ctr1 = ''''Readahead pages/sec''''
  6447. SELECT @ctr2Fam = ''''SQLServer:Buffer Manager'''', @ctr2 = ''''Page reads/sec'''', @type = 1
  6448. ELSE IF @ctr1 = ''''Target Server Memory (KB)''''
  6449. SELECT @ctr2Fam = ''''SQLServer:Memory Manager'''', @ctr2 = ''''Total Server Memory (KB)'''', @type = 2
  6450. ELSE IF @ctr1 = ''''SQL Re-Compilations/sec''''
  6451. SELECT @ctr2Fam = ''''SQLServer:SQL Statistics'''', @ctr2 = ''''SQL Compilations/sec'''', @type = 1
  6452. ELSE IF @ctr1 = ''''Page writes/sec''''
  6453. SELECT @ctr2Fam = ''''SQLServer:Buffer Manager'''', @ctr2 = ''''Page reads/sec'''', @type = 3
  6454. SELECT @ctr1Val = [counter_value] FROM tempdb.dbo.tblPerfThresholds WHERE [counter_family] = @ctr1Fam AND [counter_name] = @ctr1
  6455. SELECT @ctr2Val = [counter_value] FROM tempdb.dbo.tblPerfThresholds WHERE [counter_family] = @ctr2Fam AND [counter_name] = @ctr2
  6456. IF @ctr1 = ''''Target Server Memory (KB)''''
  6457. SELECT @ctr1Val = @ctr1Val / 1024, @ctr2Val = @ctr2Val / 1024
  6458. --Find ratio between counter 1 and 2
  6459. IF @ctr1Val IS NULL OR @ctr2Val IS NULL
  6460. BEGIN
  6461. SELECT @ReturnVals = NULL
  6462. END
  6463. ELSE IF @ctr1Val > 1 AND @ctr2Val > 1
  6464. BEGIN
  6465. IF @type = 0
  6466. SELECT @ReturnVals = (@ctr1Val / @ctr2Val)
  6467. IF @type = 1
  6468. SELECT @ReturnVals = (@ctr1Val / @ctr2Val) * 100
  6469. If @type = 2
  6470. SELECT @ReturnVals = (@ctr1Val - @ctr2Val)
  6471. IF @type = 3
  6472. SELECT @ReturnVals = (@ctr2Val / @ctr1Val) * 100
  6473. END
  6474. ELSE
  6475. BEGIN
  6476. SELECT @ReturnVals = 0
  6477. END
  6478. RETURN (@ReturnVals)
  6479. END'')
  6480. ')
  6481. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  6482. DROP TABLE #tblWaits;
  6483. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  6484. CREATE TABLE [dbo].[#tblWaits](
  6485. [retrieval_time] [datetime],
  6486. [wait_type] [nvarchar](60) NOT NULL,
  6487. [wait_time_ms] bigint NULL,
  6488. [signal_wait_time_ms] bigint NULL,
  6489. [resource_wait_time_ms] bigint NULL
  6490. );
  6491. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  6492. DROP TABLE #tblFinalWaits;
  6493. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  6494. CREATE TABLE [dbo].[#tblFinalWaits](
  6495. [wait_type] [nvarchar](60) NOT NULL,
  6496. [wait_time_s] [numeric](16, 6) NULL,
  6497. [signal_wait_time_s] [numeric](16, 6) NULL,
  6498. [resource_wait_time_s] [numeric](16, 6) NULL,
  6499. [pct] [numeric](12, 2) NULL,
  6500. [rn] [bigint] NULL,
  6501. [signal_wait_pct] [numeric](12, 2) NULL,
  6502. [resource_wait_pct] [numeric](12, 2) NULL
  6503. );
  6504. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  6505. DROP TABLE #tblLatches;
  6506. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  6507. CREATE TABLE [dbo].[#tblLatches](
  6508. [retrieval_time] [datetime],
  6509. [latch_class] [nvarchar](60) NOT NULL,
  6510. [wait_time_ms] bigint NULL,
  6511. [waiting_requests_count] [bigint] NULL
  6512. );
  6513. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  6514. DROP TABLE #tblFinalLatches;
  6515. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  6516. CREATE TABLE [dbo].[#tblFinalLatches](
  6517. [latch_class] [nvarchar](60) NOT NULL,
  6518. [wait_time_s] [decimal](16, 6) NULL,
  6519. [waiting_requests_count] [bigint] NULL,
  6520. [pct] [decimal](12, 2) NULL,
  6521. [rn] [bigint] NULL
  6522. );
  6523. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  6524. DROP TABLE #tblSpinlocksBefore;
  6525. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  6526. CREATE TABLE [dbo].[#tblSpinlocksBefore](
  6527. [name] NVARCHAR(512) NOT NULL,
  6528. [collisions] bigint NULL,
  6529. [spins] bigint NULL,
  6530. [spins_per_collision] real NULL,
  6531. [sleep_time] bigint NULL,
  6532. [backoffs] int NULL
  6533. );
  6534. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  6535. DROP TABLE #tblSpinlocksAfter;
  6536. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  6537. CREATE TABLE [dbo].[#tblSpinlocksAfter](
  6538. [name] NVARCHAR(512) NOT NULL,
  6539. [collisions] bigint NULL,
  6540. [spins] bigint NULL,
  6541. [spins_per_collision] real NULL,
  6542. [sleep_time] bigint NULL,
  6543. [backoffs] int NULL
  6544. );
  6545. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  6546. DROP TABLE #tblFinalSpinlocks;
  6547. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  6548. CREATE TABLE [dbo].[#tblFinalSpinlocks](
  6549. [name] NVARCHAR(512) NOT NULL,
  6550. [collisions] bigint NULL,
  6551. [spins] bigint NULL,
  6552. [spins_per_collision] real NULL,
  6553. [sleep_time] bigint NULL,
  6554. [backoffs] int NULL,
  6555. [spins_pct] [decimal](12, 2) NULL,
  6556. [rn] [bigint] NULL
  6557. );
  6558. SELECT @minctr = GETDATE()
  6559. -- When counter type = 272696576 (find delta from two collection points)
  6560. -- When counter type = 65792 (face value)
  6561. -- When counter type = 1073939712 (base value, check next counter types)
  6562. -- When counter type = 1073874176 (find delta from current value and base value between two collection points). Base value is counter with type 1073939712.
  6563. -- When counter type = 537003264 (find delta from current value and base value). Base value is counter with type 1073939712.
  6564. INSERT INTO #tblPerfCount
  6565. SELECT @minctr, [object_name], counter_name, instance_name, cntr_type AS counter_name_type, cntr_value
  6566. FROM sys.dm_os_performance_counters pc0 (NOLOCK)
  6567. WHERE ([object_name] LIKE '%:Access Methods%'
  6568. OR [object_name] LIKE '%:Buffer Manager%'
  6569. OR [object_name] LIKE '%:Buffer Node%'
  6570. OR [object_name] LIKE '%:Latches%'
  6571. OR [object_name] LIKE '%:Locks%'
  6572. OR [object_name] LIKE '%:Memory Manager%'
  6573. OR [object_name] LIKE '%:Memory Node%'
  6574. OR [object_name] LIKE '%:Plan Cache%'
  6575. OR [object_name] LIKE '%:SQL Statistics%'
  6576. OR [object_name] LIKE '%:Wait Statistics%'
  6577. OR [object_name] LIKE '%:Workload Group Stats%'
  6578. OR [object_name] LIKE '%:Memory Broker Clerks%'
  6579. OR [object_name] LIKE '%:Databases%'
  6580. OR [object_name] LIKE '%:Database Replica%')
  6581. AND (counter_name LIKE '%FreeSpace Scans/sec%'
  6582. OR counter_name LIKE '%Forwarded Records/sec%'
  6583. OR counter_name LIKE '%Full Scans/sec%'
  6584. OR counter_name LIKE '%Index Searches/sec%'
  6585. OR counter_name LIKE '%Page Splits/sec%'
  6586. OR counter_name LIKE '%Scan Point Revalidations/sec%'
  6587. OR counter_name LIKE '%Table Lock Escalations/sec%'
  6588. OR counter_name LIKE '%Workfiles Created/sec%'
  6589. OR counter_name LIKE '%Worktables Created/sec%'
  6590. OR counter_name LIKE '%Worktables From Cache%'
  6591. OR counter_name LIKE '%Buffer cache hit ratio%'
  6592. OR counter_name LIKE '%Buffer cache hit ratio base%'
  6593. OR counter_name LIKE '%Checkpoint pages/sec%'
  6594. OR counter_name LIKE '%Background writer pages/sec%'
  6595. OR counter_name LIKE '%Lazy writes/sec%'
  6596. OR counter_name LIKE '%Free pages%'
  6597. OR counter_name LIKE '%Page life expectancy%'
  6598. OR counter_name LIKE '%Page lookups/sec%'
  6599. OR counter_name LIKE '%Page reads/sec%'
  6600. OR counter_name LIKE '%Page writes/sec%'
  6601. OR counter_name LIKE '%Readahead pages/sec%'
  6602. OR counter_name LIKE '%Average Latch Wait Time (ms)%'
  6603. OR counter_name LIKE '%Average Latch Wait Time Base%'
  6604. OR counter_name LIKE '%Total Latch Wait Time (ms)%'
  6605. OR counter_name LIKE '%Average Wait Time (ms)%'
  6606. OR counter_name LIKE '%Average Wait Time Base%'
  6607. OR counter_name LIKE '%Number of Deadlocks/sec%'
  6608. OR counter_name LIKE '%Free Memory (KB)%'
  6609. OR counter_name LIKE '%Stolen Server Memory (KB)%'
  6610. OR counter_name LIKE '%Target Server Memory (KB)%'
  6611. OR counter_name LIKE '%Total Server Memory (KB)%'
  6612. OR counter_name LIKE '%Free Node Memory (KB)%'
  6613. OR counter_name LIKE '%Foreign Node Memory (KB)%'
  6614. OR counter_name LIKE '%Stolen Node Memory (KB)%'
  6615. OR counter_name LIKE '%Target Node Memory (KB)%'
  6616. OR counter_name LIKE '%Total Node Memory (KB)%'
  6617. OR counter_name LIKE '%Batch Requests/sec%'
  6618. OR counter_name LIKE '%SQL Compilations/sec%'
  6619. OR counter_name LIKE '%SQL Re-Compilations/sec%'
  6620. OR counter_name LIKE '%Lock waits%'
  6621. OR counter_name LIKE '%Log buffer waits%'
  6622. OR counter_name LIKE '%Log write waits%'
  6623. OR counter_name LIKE '%Memory grant queue waits%'
  6624. OR counter_name LIKE '%Network IO waits%'
  6625. OR counter_name LIKE '%Non-Page latch waits%'
  6626. OR counter_name LIKE '%Page IO latch waits%'
  6627. OR counter_name LIKE '%Page latch waits%'
  6628. OR counter_name LIKE '%Active parallel threads%'
  6629. OR counter_name LIKE '%Blocked tasks%'
  6630. OR counter_name LIKE '%CPU usage %'
  6631. OR counter_name LIKE '%CPU usage % base%'
  6632. OR counter_name LIKE '%Query optimizations/sec%'
  6633. OR counter_name LIKE '%Requests completed/sec%'
  6634. OR counter_name LIKE '%Suboptimal plans/sec%'
  6635. OR counter_name LIKE '%Temporary Tables & Table Variables%'
  6636. OR counter_name LIKE '%Extended Stored Procedures%'
  6637. OR counter_name LIKE '%Bound Trees%'
  6638. OR counter_name LIKE '%SQL Plans%'
  6639. OR counter_name LIKE '%Object Plans%'
  6640. OR counter_name LIKE '%_Total%'
  6641. OR counter_name LIKE 'Transactions/sec%'
  6642. OR counter_name LIKE '%Log Flush Wait Time%'
  6643. OR counter_name LIKE '%Log Flush Waits/sec%'
  6644. OR counter_name LIKE '%Recovery Queue%'
  6645. OR counter_name LIKE '%Log Send Queue%'
  6646. OR counter_name LIKE '%Transaction Delay%'
  6647. OR counter_name LIKE '%Redo blocked/sec%'
  6648. OR counter_name LIKE '%Resent Messages/sec%'
  6649. OR instance_name LIKE '%Buffer Pool%'
  6650. OR instance_name LIKE '%Column store object pool%');
  6651. INSERT INTO #tblWaits
  6652. SELECT @minctr, wait_type, wait_time_ms, signal_wait_time_ms,(wait_time_ms-signal_wait_time_ms) AS resource_wait_time_ms
  6653. FROM sys.dm_os_wait_stats (NOLOCK)
  6654. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
  6655. 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT',
  6656. 'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH',
  6657. 'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6658. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6659. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6660. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6661. AND wait_type NOT LIKE N'SLEEP_%'
  6662. AND wait_time_ms > 0;
  6663. INSERT INTO #tblLatches
  6664. SELECT @minctr, latch_class, wait_time_ms, waiting_requests_count
  6665. FROM sys.dm_os_latch_stats (NOLOCK)
  6666. WHERE /*latch_class NOT IN ('BUFFER')
  6667. AND*/ wait_time_ms > 0;
  6668. IF @sqlmajorver > 9
  6669. BEGIN
  6670. INSERT INTO #tblSpinlocksBefore
  6671. SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs
  6672. FROM sys.dm_os_spinlock_stats;
  6673. END
  6674. ELSE IF @sqlmajorver = 9
  6675. BEGIN
  6676. INSERT INTO #tblSpinlocksBefore
  6677. EXEC ('DBCC SQLPERF(''spinlockstats'')');
  6678. END;
  6679. IF @duration > 255
  6680. SET @duration = 255;
  6681. IF @duration < 10
  6682. SET @duration = 10;
  6683. SELECT @durationstr = 'WAITFOR DELAY ''00:' + CASE WHEN LEN(CONVERT(VARCHAR(3),@duration/60%60)) = 1
  6684. THEN '0' + CONVERT(VARCHAR(3),@duration/60%60)
  6685. ELSE CONVERT(VARCHAR(3),@duration/60%60) END
  6686. + ':' + CONVERT(VARCHAR(3),@duration-(@duration/60)*60) + ''''
  6687. EXECUTE sp_executesql @durationstr;
  6688. SELECT @maxctr = GETDATE()
  6689. INSERT INTO #tblPerfCount
  6690. SELECT @maxctr, [object_name], counter_name, instance_name, cntr_type AS counter_name_type, cntr_value
  6691. FROM sys.dm_os_performance_counters pc0 (NOLOCK)
  6692. WHERE (cntr_type = 272696576 OR cntr_type = 1073874176 OR cntr_type = 1073939712) -- Get only counters whose delta between collection points matters
  6693. AND ([object_name] LIKE '%:Access Methods%'
  6694. OR [object_name] LIKE '%:Buffer Manager%'
  6695. OR [object_name] LIKE '%:Buffer Node%'
  6696. OR [object_name] LIKE '%:Latches%'
  6697. OR [object_name] LIKE '%:Locks%'
  6698. OR [object_name] LIKE '%:Memory Manager%'
  6699. OR [object_name] LIKE '%:Memory Node%'
  6700. OR [object_name] LIKE '%:Plan Cache%'
  6701. OR [object_name] LIKE '%:SQL Statistics%'
  6702. OR [object_name] LIKE '%:Wait Statistics%'
  6703. OR [object_name] LIKE '%:Workload Group Stats%'
  6704. OR [object_name] LIKE '%:Memory Broker Clerks%'
  6705. OR [object_name] LIKE '%:Databases%'
  6706. OR [object_name] LIKE '%:Database Replica%')
  6707. AND (counter_name LIKE '%FreeSpace Scans/sec%'
  6708. OR counter_name LIKE '%Forwarded Records/sec%'
  6709. OR counter_name LIKE '%Full Scans/sec%'
  6710. OR counter_name LIKE '%Index Searches/sec%'
  6711. OR counter_name LIKE '%Page Splits/sec%'
  6712. OR counter_name LIKE '%Scan Point Revalidations/sec%'
  6713. OR counter_name LIKE '%Table Lock Escalations/sec%'
  6714. OR counter_name LIKE '%Workfiles Created/sec%'
  6715. OR counter_name LIKE '%Worktables Created/sec%'
  6716. OR counter_name LIKE '%Worktables From Cache%'
  6717. OR counter_name LIKE '%Buffer cache hit ratio%'
  6718. OR counter_name LIKE '%Buffer cache hit ratio base%'
  6719. OR counter_name LIKE '%Checkpoint pages/sec%'
  6720. OR counter_name LIKE '%Background writer pages/sec%'
  6721. OR counter_name LIKE '%Lazy writes/sec%'
  6722. OR counter_name LIKE '%Free pages%'
  6723. OR counter_name LIKE '%Page life expectancy%'
  6724. OR counter_name LIKE '%Page lookups/sec%'
  6725. OR counter_name LIKE '%Page reads/sec%'
  6726. OR counter_name LIKE '%Page writes/sec%'
  6727. OR counter_name LIKE '%Readahead pages/sec%'
  6728. OR counter_name LIKE '%Average Latch Wait Time (ms)%'
  6729. OR counter_name LIKE '%Average Latch Wait Time Base%'
  6730. OR counter_name LIKE '%Total Latch Wait Time (ms)%'
  6731. OR counter_name LIKE '%Average Wait Time (ms)%'
  6732. OR counter_name LIKE '%Average Wait Time Base%'
  6733. OR counter_name LIKE '%Number of Deadlocks/sec%'
  6734. OR counter_name LIKE '%Free Memory (KB)%'
  6735. OR counter_name LIKE '%Stolen Server Memory (KB)%'
  6736. OR counter_name LIKE '%Target Server Memory (KB)%'
  6737. OR counter_name LIKE '%Total Server Memory (KB)%'
  6738. OR counter_name LIKE '%Free Node Memory (KB)%'
  6739. OR counter_name LIKE '%Foreign Node Memory (KB)%'
  6740. OR counter_name LIKE '%Stolen Node Memory (KB)%'
  6741. OR counter_name LIKE '%Target Node Memory (KB)%'
  6742. OR counter_name LIKE '%Total Node Memory (KB)%'
  6743. OR counter_name LIKE '%Batch Requests/sec%'
  6744. OR counter_name LIKE '%SQL Compilations/sec%'
  6745. OR counter_name LIKE '%SQL Re-Compilations/sec%'
  6746. OR counter_name LIKE '%Lock waits%'
  6747. OR counter_name LIKE '%Log buffer waits%'
  6748. OR counter_name LIKE '%Log write waits%'
  6749. OR counter_name LIKE '%Memory grant queue waits%'
  6750. OR counter_name LIKE '%Network IO waits%'
  6751. OR counter_name LIKE '%Non-Page latch waits%'
  6752. OR counter_name LIKE '%Page IO latch waits%'
  6753. OR counter_name LIKE '%Page latch waits%'
  6754. OR counter_name LIKE '%Active parallel threads%'
  6755. OR counter_name LIKE '%Blocked tasks%'
  6756. OR counter_name LIKE '%CPU usage %'
  6757. OR counter_name LIKE '%CPU usage % base%'
  6758. OR counter_name LIKE '%Query optimizations/sec%'
  6759. OR counter_name LIKE '%Requests completed/sec%'
  6760. OR counter_name LIKE '%Suboptimal plans/sec%'
  6761. OR counter_name LIKE '%Temporary Tables & Table Variables%'
  6762. OR counter_name LIKE '%Extended Stored Procedures%'
  6763. OR counter_name LIKE '%Bound Trees%'
  6764. OR counter_name LIKE '%SQL Plans%'
  6765. OR counter_name LIKE '%Object Plans%'
  6766. OR counter_name LIKE '%_Total%'
  6767. OR counter_name LIKE 'Transactions/sec%'
  6768. OR counter_name LIKE '%Log Flush Wait Time%'
  6769. OR counter_name LIKE '%Log Flush Waits/sec%'
  6770. OR counter_name LIKE '%Recovery Queue%'
  6771. OR counter_name LIKE '%Log Send Queue%'
  6772. OR counter_name LIKE '%Transaction Delay%'
  6773. OR counter_name LIKE '%Redo blocked/sec%'
  6774. OR counter_name LIKE '%Resent Messages/sec%'
  6775. OR instance_name LIKE '%Buffer Pool%'
  6776. OR instance_name LIKE '%Column store object pool%');
  6777. INSERT INTO #tblWaits
  6778. SELECT @maxctr, wait_type, wait_time_ms, signal_wait_time_ms,(wait_time_ms-signal_wait_time_ms) AS resource_wait_time_ms
  6779. FROM sys.dm_os_wait_stats (NOLOCK)
  6780. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
  6781. 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT',
  6782. 'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH',
  6783. 'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6784. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6785. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6786. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6787. AND wait_type NOT LIKE N'SLEEP_%'
  6788. AND wait_time_ms > 0;
  6789. INSERT INTO #tblLatches
  6790. SELECT @maxctr, latch_class, wait_time_ms, waiting_requests_count
  6791. FROM sys.dm_os_latch_stats (NOLOCK)
  6792. WHERE /*latch_class NOT IN ('BUFFER')
  6793. AND*/ wait_time_ms > 0;
  6794. IF @sqlmajorver > 9
  6795. BEGIN
  6796. INSERT INTO #tblSpinlocksAfter
  6797. SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs
  6798. FROM sys.dm_os_spinlock_stats;
  6799. END
  6800. ELSE IF @sqlmajorver = 9
  6801. BEGIN
  6802. INSERT INTO #tblSpinlocksAfter
  6803. EXEC ('DBCC SQLPERF(''spinlockstats'')');
  6804. END;
  6805. INSERT INTO tempdb.dbo.tblPerfThresholds
  6806. SELECT DISTINCT t1.[object_name], t1.counter_name, t1.instance_name, t1.[counter_name_type],
  6807. CASE WHEN t1.counter_name_type = 272696576
  6808. THEN CONVERT(float,(
  6809. (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) -
  6810. (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)
  6811. ) / DATEDIFF(ss,@minctr,@maxctr)) -- Get value per s over last xx s
  6812. WHEN t1.counter_name_type = 537003264
  6813. THEN (SELECT CONVERT(float,(t2.cntr_value / CASE WHEN t3.cntr_value <= 0 THEN 1 ELSE t3.cntr_value END) * 100.0)
  6814. 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')
  6815. 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
  6816. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6817. WHEN t1.counter_name_type = 1073874176 AND t1.counter_name = 'Average Latch Wait Time (ms)'
  6818. THEN CONVERT(float,(
  6819. (
  6820. (SELECT t2.cntr_value - t3.cntr_value
  6821. FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.counter_name = t3.counter_name
  6822. 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
  6823. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6824. /
  6825. (SELECT CASE WHEN t2.cntr_value - t3.cntr_value <= 0 THEN 1 ELSE t2.cntr_value - t3.cntr_value END
  6826. FROM #tblPerfCount t2 INNER JOIN #tblPerfCount t3 ON t2.[object_name] = t3.[object_name] AND t2.counter_name = t3.counter_name
  6827. 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
  6828. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name)
  6829. )
  6830. / DATEDIFF(ss,@minctr,@maxctr))) -- Get value per s over last xx s
  6831. WHEN t1.counter_name_type = 1073874176 AND t1.counter_name = 'Average Wait Time (ms)'
  6832. THEN CONVERT(float,(
  6833. (
  6834. SELECT (t4.cntr_value / CASE WHEN t5.cntr_value <= 0 THEN 1 ELSE t5.cntr_value END) / DATEDIFF(ss,@minctr,@maxctr)
  6835. FROM
  6836. (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
  6837. 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
  6838. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name, t2.instance_name) AS t4
  6839. INNER JOIN
  6840. (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
  6841. 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
  6842. GROUP BY t2.[retrieval_time], t2.cntr_value, t3.cntr_value, t2.counter_name, t2.instance_name) AS t5
  6843. ON t4.instance_name = t5.instance_name
  6844. ))) -- Get value per s over last xx s
  6845. ELSE CONVERT(float,t1.cntr_value)
  6846. END
  6847. FROM #tblPerfCount t1
  6848. WHERE (t1.counter_name_type <> 1073939712)
  6849. GROUP BY t1.[object_name], t1.[counter_name], t1.instance_name, t1.counter_name_type, t1.cntr_value
  6850. ORDER BY t1.[object_name], t1.[counter_name], t1.instance_name;
  6851. ;WITH ctectr AS (SELECT [counter_family],[counter_name],[counter_instance],[counter_value],
  6852. CASE WHEN [counter_name] IN ('Worktables Created/sec','Worktables From Cache Ratio','Buffer cache hit ratio',
  6853. 'Free list stalls/sec','Free pages','Free Memory (KB)','Lazy writes/sec','Page life expectancy',
  6854. 'Page reads/sec','Log Flush Wait Time','Log Flush Waits/sec','Average Latch Wait Time (ms)',
  6855. 'Total Latch Wait Time (ms)','Lock Waits/sec','Number of Deadlocks/sec','Batch Requests/sec') THEN [counter_value]
  6856. ELSE tempdb.dbo.fn_perfctr([counter_family],[counter_name]) END AS [counter_calculated_threshold_value]
  6857. FROM tempdb.dbo.tblPerfThresholds)
  6858. SELECT 'Performance_checks' AS [Category], 'Perf_Counters' AS [Check],[counter_family],[counter_name],[counter_instance],[counter_value],[counter_calculated_threshold_value],
  6859. 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]'
  6860. 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]'
  6861. 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]'
  6862. 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]'
  6863. 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]'
  6864. WHEN [counter_name] = 'Worktables Created/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: Greater than 20 Worktables created per second]'
  6865. WHEN [counter_name] = 'Worktables From Cache Ratio' AND [counter_calculated_threshold_value] < 90 THEN '[WARNING: Less than 90 percent Worktables from Cache Ratio]'
  6866. WHEN [counter_name] = 'Buffer cache hit ratio' AND [counter_calculated_threshold_value] < 97 THEN '[WARNING: Less than 97 percent buffer cache hit ratio]'
  6867. WHEN [counter_name] = 'Buffer cache hit ratio' AND [counter_calculated_threshold_value] < 90 THEN '[WARNING: Less than 90 percent buffer cache hit ratio]'
  6868. WHEN [counter_name] = 'Free list stalls/sec' AND [counter_calculated_threshold_value] < 2 THEN '[WARNING: Free list stalls per second is less than 2]'
  6869. WHEN [counter_name] = 'Free pages' AND [counter_calculated_threshold_value] < 640 THEN '[WARNING: Less than 640 Free Pages]'
  6870. WHEN [counter_name] = 'Free Memory (KB)' AND [counter_calculated_threshold_value] < 5 THEN '[WARNING: Less than 5MB]'
  6871. WHEN [counter_name] = 'Lazy writes/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: Greater than 20 Lazy Writes per second]'
  6872. WHEN [counter_name] = 'Page life expectancy' AND [counter_calculated_threshold_value] < 300 THEN '[WARNING: Less than 300 seconds of Page Life Expectancy]'
  6873. WHEN [counter_name] = 'Page life expectancy' AND [counter_calculated_threshold_value] < 700 THEN '[WARNING: Less than 700 seconds of Page Life Expectancy]'
  6874. 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]'
  6875. WHEN [counter_name] = 'Page reads/sec' AND [counter_calculated_threshold_value] > 90 THEN '[WARNING: Greater than 90 page reads per second]'
  6876. 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]'
  6877. WHEN [counter_name] = 'Page writes/sec' AND [counter_value] > 90 THEN '[WARNING: Greater than 90 page writes per second]'
  6878. WHEN [counter_name] = 'Readahead pages/sec' AND [counter_calculated_threshold_value] > 20 THEN '[WARNING: More than 20 percent of page reads per second]'
  6879. 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]'
  6880. 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]'
  6881. 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]'
  6882. 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]'
  6883. 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]'
  6884. 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]'
  6885. WHEN [counter_name] = 'Batch Requests/sec' AND [counter_calculated_threshold_value] > 1000 THEN '[WARNING: Greater than 1000 batch requests per second]'
  6886. 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]'
  6887. 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]'
  6888. WHEN [counter_calculated_threshold_value] IS NULL THEN NULL
  6889. ELSE '[OK]' END AS [Deviation]
  6890. FROM ctectr
  6891. ORDER BY [counter_family],[counter_name],[counter_instance];
  6892. IF @sqlmajorver >= 11
  6893. BEGIN
  6894. 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"
  6895. FROM (SELECT [counter_name],[instance_name],[cntr_value] FROM #tblPerfCount WHERE [object_name] LIKE '%Batch Resp Statistics%') AS pc
  6896. PIVOT(AVG([cntr_value]) FOR [instance_name]
  6897. IN ("CPU Time:Total(ms)", "CPU Time:Requests", "Elapsed Time:Total(ms)", "Elapsed Time:Requests")
  6898. ) AS Pvt;
  6899. END
  6900. ;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),
  6901. 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)
  6902. INSERT INTO #tblFinalWaits
  6903. SELECT DISTINCT t1.wait_type, (t2.wait_time_ms-t1.wait_time_ms) / 1000. AS wait_time_s,
  6904. (t2.signal_wait_time_ms-t1.signal_wait_time_ms) / 1000. AS signal_wait_time_s,
  6905. ((t2.wait_time_ms-t2.signal_wait_time_ms)-(t1.wait_time_ms-t1.signal_wait_time_ms)) / 1000. AS resource_wait_time_s,
  6906. 100.0 * (t2.wait_time_ms-t1.wait_time_ms) / SUM(t2.wait_time_ms-t1.wait_time_ms) OVER() AS pct,
  6907. ROW_NUMBER() OVER(ORDER BY (t2.wait_time_ms-t1.wait_time_ms) DESC) AS rn,
  6908. 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,
  6909. (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
  6910. FROM cteWaits1 t1 INNER JOIN cteWaits2 t2 ON t1.wait_type = t2.wait_type
  6911. 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
  6912. HAVING (t2.wait_time_ms-t1.wait_time_ms) > 0
  6913. ORDER BY wait_time_s DESC;
  6914. SELECT 'Performance_checks' AS [Category], 'Waits_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], W1.wait_type,
  6915. CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s,
  6916. CAST(W1.signal_wait_time_s AS DECIMAL(12, 2)) AS signal_wait_time_s,
  6917. CAST(W1.resource_wait_time_s AS DECIMAL(12, 2)) AS resource_wait_time_s,
  6918. CAST(W1.pct AS DECIMAL(12, 2)) AS pct,
  6919. CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  6920. CAST(W1.signal_wait_pct AS DECIMAL(12, 2)) AS signal_wait_pct,
  6921. CAST(W1.resource_wait_pct AS DECIMAL(12, 2)) AS resource_wait_pct,
  6922. CASE WHEN W1.wait_type LIKE N'LCK_%' OR W1.wait_type = N'LOCK' THEN N'Lock'
  6923. WHEN W1.wait_type LIKE N'LATCH_%' THEN N'Latch'
  6924. WHEN W1.wait_type LIKE N'PAGELATCH_%' THEN N'Buffer Latch'
  6925. WHEN W1.wait_type LIKE N'PAGEIOLATCH_%' THEN N'Buffer IO'
  6926. WHEN W1.wait_type LIKE N'HADR_SYNC_COMMIT' THEN N'AlwaysOn - Secondary Synch'
  6927. WHEN W1.wait_type LIKE N'HADR_%' THEN N'AlwaysOn'
  6928. WHEN W1.wait_type LIKE N'FFT_%' THEN N'FileTable'
  6929. 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;
  6930. WHEN W1.wait_type IN (N'IO_COMPLETION', N'ASYNC_IO_COMPLETION', /*N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',*/ N'DISKIO_SUSPEND') THEN N'Other IO'
  6931. WHEN W1.wait_type IN(N'BACKUPIO', N'BACKUPBUFFER') THEN 'Backup IO'
  6932. WHEN W1.wait_type = N'THREADPOOL' THEN 'CPU - Unavailable Worker Threads'
  6933. WHEN W1.wait_type = N'SOS_SCHEDULER_YIELD' THEN N'CPU - Scheduler Yielding'
  6934. WHEN W1.wait_type IN (N'CXPACKET', N'EXCHANGE') THEN N'CPU - Parallelism'
  6935. WHEN W1.wait_type IN (N'LOGMGR', N'LOGBUFFER', N'LOGMGR_RESERVE_APPEND', N'LOGMGR_FLUSH', N'WRITELOG') THEN N'Logging'
  6936. WHEN W1.wait_type IN (N'NET_WAITFOR_PACKET',N'NETWORK_IO') THEN N'Network IO'
  6937. WHEN W1.wait_type = N'ASYNC_NETWORK_IO' THEN N'Client Network IO'
  6938. WHEN W1.wait_type IN (N'UTIL_PAGE_ALLOC',N'SOS_VIRTUALMEMORY_LOW',N'CMEMTHREAD', N'SOS_RESERVEDMEMBLOCKLIST') THEN N'Memory'
  6939. WHEN W1.wait_type IN (N'RESOURCE_SEMAPHORE_SMALL_QUERY', N'RESOURCE_SEMAPHORE') THEN N'Memory - Hash or Sort'
  6940. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Memory - Compilation'
  6941. WHEN W1.wait_type LIKE N'CLR_%' OR W1.wait_type LIKE N'SQLCLR%' THEN N'CLR'
  6942. WHEN W1.wait_type LIKE N'DBMIRROR%' OR W1.wait_type = N'MIRROR_SEND_MESSAGE' THEN N'Mirroring'
  6943. 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'
  6944. -- 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'
  6945. WHEN W1.wait_type LIKE N'FT_%' THEN N'Full Text'
  6946. WHEN W1.wait_type = N'REPLICA_WRITE' THEN 'Snapshots'
  6947. ELSE N'Other' END AS 'wait_category'
  6948. FROM #tblFinalWaits AS W1 INNER JOIN #tblFinalWaits AS W2 ON W2.rn <= W1.rn
  6949. 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
  6950. HAVING W1.wait_time_s >= 0.01 AND (SUM(W2.pct)-W1.pct) < 100 -- percentage threshold
  6951. ORDER BY W1.rn;
  6952. ;WITH Waits AS
  6953. (SELECT wait_type, wait_time_ms / 1000. AS wait_time_s,
  6954. signal_wait_time_ms / 1000. AS signal_wait_time_s,
  6955. (wait_time_ms-signal_wait_time_ms) / 1000. AS resource_wait_time_s,
  6956. SUM(signal_wait_time_ms) * 1.0 / SUM(wait_time_ms) * 100 AS signal_wait_pct,
  6957. SUM(wait_time_ms-signal_wait_time_ms) * 1.0 / SUM(wait_time_ms) * 100 AS resource_wait_pct,
  6958. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  6959. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  6960. FROM sys.dm_os_wait_stats
  6961. WHERE wait_type NOT IN ('RESOURCE_QUEUE', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP'
  6962. , 'LOGMGR_QUEUE','CHECKPOINT_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TASK_STOP','CLR_MANUAL_EVENT'
  6963. ,'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT','BROKER_TO_FLUSH'
  6964. ,'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'MSQL_XP', 'WAIT_FOR_RESULTS', 'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'SLEEP_TASK',
  6965. 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'BROKER_EVENTHANDLER', 'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'BROKER_RECEIVE_WAITFOR',
  6966. 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE', 'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES', 'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK',
  6967. 'DIRTY_PAGE_POLL', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 'SP_SERVER_DIAGNOSTICS_SLEEP')
  6968. AND wait_type NOT LIKE N'SLEEP_%'
  6969. GROUP BY wait_type, wait_time_ms, signal_wait_time_ms)
  6970. SELECT 'Performance_checks' AS [Category], 'Cumulative_Waits' AS [Information], W1.wait_type,
  6971. CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s,
  6972. CAST(W1.signal_wait_time_s AS DECIMAL(12, 2)) AS signal_wait_time_s,
  6973. CAST(W1.resource_wait_time_s AS DECIMAL(12, 2)) AS resource_wait_time_s,
  6974. CAST(W1.pct AS DECIMAL(12, 2)) AS pct,
  6975. CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  6976. CAST(W1.signal_wait_pct AS DECIMAL(12, 2)) AS signal_wait_pct,
  6977. CAST(W1.resource_wait_pct AS DECIMAL(12, 2)) AS resource_wait_pct,
  6978. CASE WHEN W1.wait_type LIKE N'LCK_%' OR W1.wait_type = N'LOCK' THEN N'Lock'
  6979. -- 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;
  6980. WHEN W1.wait_type LIKE N'LATCH_%' THEN N'Latch'
  6981. -- PAGELATCH = indicates contention for access to in-memory copies of pages, like PFS, SGAM and GAM;
  6982. -- PAGELATCH_UP = Does the filegroup have enough files? Contention in PFS?
  6983. -- PAGELATCH_EX = Contention while doing many UPDATE statements against small tables?
  6984. -- 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
  6985. WHEN W1.wait_type LIKE N'PAGELATCH_%' THEN N'Buffer Latch'
  6986. -- PAGEIOLATCH = indicates IO problems, or BP pressure.
  6987. WHEN W1.wait_type LIKE N'PAGEIOLATCH_%' THEN N'Buffer IO'
  6988. WHEN W1.wait_type LIKE N'HADR_SYNC_COMMIT' THEN N'AlwaysOn - Secondary Synch'
  6989. WHEN W1.wait_type LIKE N'HADR_%' THEN N'AlwaysOn'
  6990. WHEN W1.wait_type LIKE N'FFT_%' THEN N'FileTable'
  6991. -- PREEMPTIVE_OS_WRITEFILEGATHERER (2008+) = usually autogrow scenarios, usually together with WRITELOG;
  6992. 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;
  6993. -- IO_COMPLETION = usually TempDB spilling;
  6994. -- ASYNC_IO_COMPLETION = usually when not using IFI, or waiting on backups.
  6995. -- 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;
  6996. WHEN W1.wait_type IN (N'IO_COMPLETION', N'ASYNC_IO_COMPLETION', /*N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',*/ N'DISKIO_SUSPEND') THEN N'Other IO'
  6997. -- BACKUPIO = check for slow backup media slow, like Tapes or Disks;
  6998. -- BACKUPBUFFER = usually when backing up to Tape;
  6999. WHEN W1.wait_type IN(N'BACKUPIO', N'BACKUPBUFFER') THEN 'Backup IO'
  7000. -- THREADPOOL = Look for high blocking or contention problems with workers. This will not show up in sys.dm_exec_requests;
  7001. WHEN W1.wait_type = N'THREADPOOL' THEN 'CPU - Unavailable Worker Threads'
  7002. -- 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
  7003. WHEN W1.wait_type = N'SOS_SCHEDULER_YIELD' THEN N'CPU - Scheduler Yielding'
  7004. -- Check sys.dm_os_waiting_tasks for Exchange wait types in http://technet.microsoft.com/en-us/library/ms188743.aspx;
  7005. -- Wait Resource e_waitPipeNewRow in CXPACKET waits Producer waiting on consumer for a packet to fill;
  7006. -- Wait Resource e_waitPipeGetRow in CXPACKET waits Consumer waiting on producer to fill a packet;
  7007. -- 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;
  7008. WHEN W1.wait_type IN (N'CXPACKET', N'EXCHANGE') THEN N'CPU - Parallelism'
  7009. -- WRITELOG = log management system waiting for a log flush to disk. Examine the IO latency for the log file
  7010. WHEN W1.wait_type IN (N'LOGMGR', N'LOGBUFFER', N'LOGMGR_RESERVE_APPEND', N'LOGMGR_FLUSH', N'WRITELOG') THEN N'Logging'
  7011. WHEN W1.wait_type IN (N'NET_WAITFOR_PACKET',N'NETWORK_IO') THEN N'Network IO'
  7012. WHEN W1.wait_type = N'ASYNC_NETWORK_IO' THEN N'Client Network IO'
  7013. -- 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
  7014. -- 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
  7015. WHEN W1.wait_type IN (N'UTIL_PAGE_ALLOC',N'SOS_VIRTUALMEMORY_LOW',N'CMEMTHREAD', N'SOS_RESERVEDMEMBLOCKLIST') THEN N'Memory'
  7016. -- RESOURCE_SEMAPHORE_SMALL_QUERY or RESOURCE_SEMAPHORE = queries are waiting for execution memory. Look for plans with excessive hashing or sorts.
  7017. WHEN W1.wait_type IN (N'RESOURCE_SEMAPHORE_SMALL_QUERY', N'RESOURCE_SEMAPHORE') THEN N'Memory - Hash or Sort'
  7018. -- 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
  7019. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Memory - Compilation'
  7020. WHEN W1.wait_type LIKE N'CLR_%' OR W1.wait_type LIKE N'SQLCLR%' THEN N'CLR'
  7021. -- DBMIRROR_DBM_MUTEX = indicates contention for the send buffer that database mirroring shares between all the mirroring sessions.
  7022. WHEN W1.wait_type LIKE N'DBMIRROR%' OR W1.wait_type = N'MIRROR_SEND_MESSAGE' THEN N'Mirroring'
  7023. -- 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.
  7024. WHEN W1.wait_type LIKE N'RESOURCE_SEMAPHORE_%' OR W1.wait_type LIKE N'RESOURCE_SEMAPHORE_QUERY_COMPILE' THEN N'Compilation'
  7025. 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'
  7026. -- 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'
  7027. WHEN W1.wait_type LIKE N'FT_%' THEN N'Full Text'
  7028. WHEN W1.wait_type = N'REPLICA_WRITE' THEN 'Snapshots'
  7029. ELSE N'Other' END AS 'wait_category'
  7030. FROM Waits AS W1 INNER JOIN Waits AS W2 ON W2.rn <= W1.rn
  7031. 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
  7032. HAVING W1.wait_time_s >= 0.01 AND (SUM(W2.pct)-W1.pct) < 100 -- percentage threshold
  7033. ORDER BY W1.rn;
  7034. ;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),
  7035. 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)
  7036. INSERT INTO #tblFinalLatches
  7037. SELECT DISTINCT t1.latch_class,
  7038. (t2.wait_time_ms-t1.wait_time_ms) / 1000.0 AS wait_time_s,
  7039. (t2.waiting_requests_count-t1.waiting_requests_count) AS waiting_requests_count,
  7040. 100.0 * (t2.wait_time_ms-t1.wait_time_ms) / SUM(t2.wait_time_ms-t1.wait_time_ms) OVER() AS pct,
  7041. ROW_NUMBER() OVER(ORDER BY t1.wait_time_ms DESC) AS rn
  7042. FROM cteLatches1 t1 INNER JOIN cteLatches2 t2 ON t1.latch_class = t2.latch_class
  7043. GROUP BY t1.latch_class, t1.wait_time_ms, t2.wait_time_ms, t1.waiting_requests_count, t2.waiting_requests_count
  7044. HAVING (t2.wait_time_ms-t1.wait_time_ms) > 0
  7045. ORDER BY wait_time_s DESC;
  7046. SELECT 'Performance_checks' AS [Category], 'Latches_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], W1.latch_class,
  7047. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7048. W1.waiting_requests_count,
  7049. CAST (W1.pct AS DECIMAL(14, 2)) AS pct,
  7050. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7051. CAST ((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7052. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7053. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7054. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7055. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7056. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7057. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7058. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7059. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER' THEN N'[Parallelism - DBCC CHECK_]'
  7060. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7061. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION' THEN N'[Mirroring - Busy]'
  7062. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7063. ELSE N'[Other]' END AS 'latch_category'
  7064. FROM #tblFinalLatches AS W1 INNER JOIN #tblFinalLatches AS W2 ON W2.rn <= W1.rn
  7065. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7066. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7067. ;WITH Latches AS
  7068. (SELECT latch_class,
  7069. wait_time_ms / 1000.0 AS wait_time_s,
  7070. waiting_requests_count,
  7071. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  7072. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  7073. FROM sys.dm_os_latch_stats
  7074. WHERE /*latch_class NOT IN ('BUFFER')
  7075. AND*/ wait_time_ms > 0
  7076. )
  7077. SELECT 'Performance_checks' AS [Category], 'Cumulative_Latches' AS [Information], W1.latch_class,
  7078. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7079. W1.waiting_requests_count,
  7080. CAST(W1.pct AS DECIMAL(14, 2)) AS pct,
  7081. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7082. CAST((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7083. -- 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).
  7084. -- 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.
  7085. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7086. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7087. -- 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.);
  7088. -- 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.
  7089. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7090. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7091. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7092. -- 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.
  7093. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7094. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7095. -- 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.
  7096. -- http://blogs.msdn.com/b/psssql/archive/2012/02/23/a-faster-checkdb-part-ii.aspx
  7097. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER ' THEN N'[Parallelism - DBCC CHECK_]'
  7098. -- 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.
  7099. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7100. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION ' THEN N'[Mirroring - Busy]'
  7101. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7102. ELSE N'Other' END AS 'latch_category'
  7103. FROM Latches AS W1
  7104. INNER JOIN Latches AS W2
  7105. ON W2.rn <= W1.rn
  7106. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7107. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7108. ;WITH Latches AS
  7109. (SELECT latch_class,
  7110. wait_time_ms / 1000.0 AS wait_time_s,
  7111. waiting_requests_count,
  7112. 100.0 * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
  7113. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
  7114. FROM sys.dm_os_latch_stats (NOLOCK)
  7115. WHERE latch_class NOT IN ('BUFFER')
  7116. AND wait_time_ms > 0
  7117. )
  7118. SELECT 'Performance_checks' AS [Category], 'Cumulative_Latches_wo_BUFFER' AS [Information], W1.latch_class,
  7119. CAST(W1.wait_time_s AS DECIMAL(14, 2)) AS wait_time_s,
  7120. W1.waiting_requests_count,
  7121. CAST(W1.pct AS DECIMAL(14, 2)) AS pct,
  7122. CAST(SUM(W1.pct) AS DECIMAL(12, 2)) AS overall_running_pct,
  7123. CAST((W1.wait_time_s / W1.waiting_requests_count) AS DECIMAL (14, 4)) AS avg_wait_s,
  7124. -- 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).
  7125. -- 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.
  7126. CASE WHEN W1.latch_class LIKE N'ACCESS_METHODS_HOBT_COUNT'
  7127. OR W1.latch_class LIKE N'ACCESS_METHODS_HOBT_VIRTUAL_ROOT' THEN N'[HoBT - Metadata]'
  7128. -- 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.);
  7129. -- 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.
  7130. WHEN W1.latch_class LIKE N'ACCESS_METHODS_DATASET_PARENT'
  7131. OR W1.latch_class LIKE N'ACCESS_METHODS_SCAN_RANGE_GENERATOR'
  7132. OR W1.latch_class LIKE N'NESTING_TRANSACTION_FULL' THEN N'[Parallelism]'
  7133. -- 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.
  7134. WHEN W1.latch_class LIKE N'LOG_MANAGER' THEN N'[IO - Log]'
  7135. WHEN W1.latch_class LIKE N'TRACE_CONTROLLER' THEN N'[Trace]'
  7136. -- 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.
  7137. -- http://blogs.msdn.com/b/psssql/archive/2012/02/23/a-faster-checkdb-part-ii.aspx
  7138. WHEN W1.latch_class LIKE N'DBCC_MULTIOBJECT_SCANNER ' THEN N'[Parallelism - DBCC CHECK_]'
  7139. -- 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.
  7140. WHEN W1.latch_class LIKE N'FGCB_ADD_REMOVE' THEN N'[IO Operations]'
  7141. WHEN W1.latch_class LIKE N'DATABASE_MIRRORING_CONNECTION ' THEN N'[Mirroring - Busy]'
  7142. WHEN W1.latch_class LIKE N'BUFFER' THEN N'[Buffer Pool - PAGELATCH or PAGEIOLATCH]'
  7143. ELSE N'Other' END AS 'latch_category'
  7144. FROM Latches AS W1
  7145. INNER JOIN Latches AS W2
  7146. ON W2.rn <= W1.rn
  7147. GROUP BY W1.rn, W1.latch_class, W1.wait_time_s, W1.waiting_requests_count, W1.pct
  7148. HAVING SUM (W2.pct) - W1.pct < 100; -- percentage threshold
  7149. ;WITH cteSpinlocks1 AS (SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs FROM #tblSpinlocksBefore),
  7150. cteSpinlocks2 AS (SELECT name, collisions, spins, spins_per_collision, sleep_time, backoffs FROM #tblSpinlocksAfter)
  7151. INSERT INTO #tblFinalSpinlocks
  7152. SELECT DISTINCT t1.name,
  7153. (t2.collisions-t1.collisions) AS collisions,
  7154. (t2.spins-t1.spins) AS spins,
  7155. (t2.spins_per_collision-t1.spins_per_collision) AS spins_per_collision,
  7156. (t2.sleep_time-t1.sleep_time) AS sleep_time,
  7157. (t2.backoffs-t1.backoffs) AS backoffs,
  7158. 100.0 * (t2.spins-t1.spins) / SUM(t2.spins-t1.spins) OVER() AS spins_pct,
  7159. ROW_NUMBER() OVER(ORDER BY t2.spins DESC) AS rn
  7160. FROM cteSpinlocks1 t1 INNER JOIN cteSpinlocks2 t2 ON t1.name = t2.name
  7161. 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
  7162. HAVING (t2.spins-t1.spins) > 0
  7163. ORDER BY spins DESC;
  7164. SELECT 'Performance_checks' AS [Category], 'Spinlocks_Last_' + CONVERT(VARCHAR(3), @duration) + 's' AS [Information], S1.name,
  7165. S1.collisions, S1.spins, S1.spins_per_collision, S1.sleep_time, S1.backoffs,
  7166. CAST(S1.spins_pct AS DECIMAL(14, 2)) AS spins_pct,
  7167. CAST(SUM(S1.spins_pct) AS DECIMAL(12, 2)) AS overall_running_spins_pct
  7168. FROM #tblFinalSpinlocks AS S1 INNER JOIN #tblFinalSpinlocks AS S2 ON S2.rn <= S1.rn
  7169. GROUP BY S1.rn, S1.name, S1.collisions, S1.spins, S1.spins_per_collision, S1.sleep_time, S1.backoffs, S1.spins_pct
  7170. HAVING SUM(S2.spins_pct) - S1.spins_pct < 100 -- percentage threshold
  7171. ORDER BY spins DESC;
  7172. END;
  7173. --------------------------------------------------------------------------------------------------------------------------------
  7174. -- Worker thread exhaustion subsection
  7175. --------------------------------------------------------------------------------------------------------------------------------
  7176. IF @ptochecks = 1
  7177. BEGIN
  7178. RAISERROR (N' |-Starting Worker thread exhaustion', 10, 1) WITH NOWAIT
  7179. DECLARE @avgtskcnt int, @workqcnt int
  7180. SELECT @avgtskcnt = SUM(runnable_tasks_count)/COUNT(scheduler_id), @workqcnt = SUM(work_queue_count) FROM sys.dm_os_schedulers
  7181. WHERE parent_node_id < 64 AND scheduler_id < 255
  7182. IF @avgtskcnt <= 2 AND @workqcnt > 1
  7183. BEGIN
  7184. 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]
  7185. END
  7186. ELSE IF @avgtskcnt > 2 AND @workqcnt > 1
  7187. BEGIN
  7188. 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]
  7189. END
  7190. ELSE
  7191. BEGIN
  7192. SELECT 'Performance_checks' AS [Category], 'Worker_thread_exhaustion' AS [Check], '[OK]' AS [Deviation], '' AS [Comment]
  7193. END
  7194. END;
  7195. --------------------------------------------------------------------------------------------------------------------------------
  7196. -- Blocking Chains subsection
  7197. -- Checks for blocking chains taking over 5s.
  7198. --------------------------------------------------------------------------------------------------------------------------------
  7199. IF @ptochecks = 1
  7200. BEGIN
  7201. RAISERROR (N' |-Starting Blocking Chains', 10, 1) WITH NOWAIT
  7202. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  7203. DROP TABLE #tblBlkChains;
  7204. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  7205. CREATE TABLE #tblBlkChains ([blocked_spid] [smallint], [blocked_spid_status] NVARCHAR(30), [blocked_task_status] NVARCHAR(60),
  7206. [blocked_spid_wait_type] NVARCHAR(60), [blocked_spid_wait_time_ms] [bigint], [blocked_spid_res_desc] NVARCHAR(1024),
  7207. [blocked_pageid] [int], [blocked_spid_res_type] VARCHAR(24), [blocked_batch] [xml], [blocked_statement] [xml],
  7208. [blocked_last_start] [datetime], [blocked_tran_isolation_level] VARCHAR(30), [blocker_spid] [smallint],
  7209. [is_head_blocker] [int], [blocker_batch] [xml], [blocker_statement] [xml], [blocker_last_start] [datetime],
  7210. [blocker_tran_isolation_level] VARCHAR(30), [blocked_database] NVARCHAR(128), [blocked_host] NVARCHAR(128),
  7211. [blocked_program] NVARCHAR(128), [blocked_login] NVARCHAR(128), [blocked_session_comment] VARCHAR(25),
  7212. [blocked_is_user_process] [bit], [blocker_database] NVARCHAR(128), [blocker_host] NVARCHAR(128),
  7213. [blocker_program] NVARCHAR(128), [blocker_login] NVARCHAR(128), [blocker_session_comment] VARCHAR(25), [blocker_is_user_process] [bit])
  7214. INSERT INTO #tblBlkChains
  7215. SELECT
  7216. -- blocked
  7217. es.session_id AS blocked_spid,
  7218. es.[status] AS [blocked_spid_status],
  7219. ot.task_state AS [blocked_task_status],
  7220. owt.wait_type AS blocked_spid_wait_type,
  7221. COALESCE(owt.wait_duration_ms, ABS(CONVERT(BIGINT,(DATEDIFF(mi, es.last_request_start_time, GETDATE())))*60)) AS blocked_spid_wait_time_ms,
  7222. --er.total_elapsed_time AS blocked_elapsed_time_ms,
  7223. /*
  7224. Check sys.dm_os_waiting_tasks for Exchange wait types in http://technet.microsoft.com/en-us/library/ms188743.aspx.
  7225. - Wait Resource e_waitPipeNewRow in CXPACKET waits – Producer waiting on consumer for a packet to fill.
  7226. - Wait Resource e_waitPipeGetRow in CXPACKET waits – Consumer waiting on producer to fill a packet.
  7227. */
  7228. owt.resource_description AS blocked_spid_res_desc,
  7229. owt.pageid AS blocked_pageid,
  7230. CASE WHEN owt.pageid = 1 OR owt.pageid % 8088 = 0 THEN 'Is_PFS_Page'
  7231. WHEN owt.pageid = 2 OR owt.pageid % 511232 = 0 THEN 'Is_GAM_Page'
  7232. WHEN owt.pageid = 3 OR (owt.pageid - 1) % 511232 = 0 THEN 'Is_SGAM_Page'
  7233. WHEN owt.pageid IS NULL THEN NULL
  7234. ELSE 'Is_not_PFS_GAM_SGAM_page' END AS blocked_spid_res_type,
  7235. (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(
  7236. qt.[text],
  7237. 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'?')
  7238. AS [text()]
  7239. FROM sys.dm_exec_sql_text(COALESCE(er.sql_handle, ec.most_recent_sql_handle)) AS qt
  7240. FOR XML PATH(''), TYPE) AS [blocked_batch],
  7241. (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(
  7242. SUBSTRING(qt2.text,
  7243. 1+(CASE WHEN er.statement_start_offset = 0 THEN 0 ELSE er.statement_start_offset/2 END),
  7244. 1+(CASE WHEN er.statement_end_offset = -1 THEN DATALENGTH(qt2.text) ELSE er.statement_end_offset/2 END - (CASE WHEN er.statement_start_offset = 0 THEN 0 ELSE er.statement_start_offset/2 END))),
  7245. 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'?')
  7246. AS [text()]
  7247. FROM sys.dm_exec_sql_text(COALESCE(er.sql_handle, ec.most_recent_sql_handle)) AS qt2
  7248. FOR XML PATH(''), TYPE) AS [blocked_statement],
  7249. es.last_request_start_time AS blocked_last_start,
  7250. LEFT (CASE COALESCE(es.transaction_isolation_level, er.transaction_isolation_level)
  7251. WHEN 0 THEN '0-Unspecified'
  7252. WHEN 1 THEN '1-ReadUncommitted(NOLOCK)'
  7253. WHEN 2 THEN '2-ReadCommitted'
  7254. WHEN 3 THEN '3-RepeatableRead'
  7255. WHEN 4 THEN '4-Serializable'
  7256. WHEN 5 THEN '5-Snapshot'
  7257. ELSE CONVERT (VARCHAR(30), COALESCE(es.transaction_isolation_level, er.transaction_isolation_level)) + '-UNKNOWN'
  7258. END, 30) AS blocked_tran_isolation_level,
  7259. -- blocker
  7260. er.blocking_session_id As blocker_spid,
  7261. CASE
  7262. -- session has an active request, is blocked, but is blocking others or session is idle but has an open tran and is blocking others
  7263. 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
  7264. -- session is either not blocking someone, or is blocking someone but is blocked by another party
  7265. ELSE 0
  7266. END AS is_head_blocker,
  7267. (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(
  7268. qt2.[text],
  7269. 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'?')
  7270. AS [text()]
  7271. FROM sys.dm_exec_sql_text(COALESCE(er2.sql_handle, ec2.most_recent_sql_handle)) AS qt2
  7272. FOR XML PATH(''), TYPE) AS [blocker_batch],
  7273. (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(
  7274. SUBSTRING(qt2.text,
  7275. 1+(CASE WHEN er2.statement_start_offset = 0 THEN 0 ELSE er2.statement_start_offset/2 END),
  7276. 1+(CASE WHEN er2.statement_end_offset = -1 THEN DATALENGTH(qt2.text) ELSE er2.statement_end_offset/2 END - (CASE WHEN er2.statement_start_offset = 0 THEN 0 ELSE er2.statement_start_offset/2 END))),
  7277. 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'?')
  7278. AS [text()]
  7279. FROM sys.dm_exec_sql_text(COALESCE(er2.sql_handle, ec2.most_recent_sql_handle)) AS qt2
  7280. FOR XML PATH(''), TYPE) AS [blocker_statement],
  7281. es2.last_request_start_time AS blocker_last_start,
  7282. LEFT (CASE COALESCE(er2.transaction_isolation_level, es.transaction_isolation_level)
  7283. WHEN 0 THEN '0-Unspecified'
  7284. WHEN 1 THEN '1-ReadUncommitted(NOLOCK)'
  7285. WHEN 2 THEN '2-ReadCommitted'
  7286. WHEN 3 THEN '3-RepeatableRead'
  7287. WHEN 4 THEN '4-Serializable'
  7288. WHEN 5 THEN '5-Snapshot'
  7289. ELSE CONVERT (VARCHAR(30), COALESCE(er2.transaction_isolation_level, es.transaction_isolation_level)) + '-UNKNOWN'
  7290. END, 30) AS blocker_tran_isolation_level,
  7291. -- blocked - other data
  7292. DB_NAME(er.database_id) AS blocked_database,
  7293. es.[host_name] AS blocked_host,
  7294. es.[program_name] AS blocked_program,
  7295. es.login_name AS blocked_login,
  7296. CASE WHEN es.session_id = -2 THEN 'Orphaned_distributed_tran'
  7297. WHEN es.session_id = -3 THEN 'Defered_recovery_tran'
  7298. WHEN es.session_id = -4 THEN 'Unknown_tran' ELSE NULL END AS blocked_session_comment,
  7299. es.is_user_process AS [blocked_is_user_process],
  7300. -- blocker - other data
  7301. DB_NAME(er2.database_id) AS blocker_database,
  7302. es2.[host_name] AS blocker_host,
  7303. es2.[program_name] AS blocker_program,
  7304. es2.login_name AS blocker_login,
  7305. CASE WHEN es2.session_id = -2 THEN 'Orphaned_distributed_tran'
  7306. WHEN es2.session_id = -3 THEN 'Defered_recovery_tran'
  7307. WHEN es2.session_id = -4 THEN 'Unknown_tran' ELSE NULL END AS blocker_session_comment,
  7308. es2.is_user_process AS [blocker_is_user_process]
  7309. FROM sys.dm_exec_sessions es
  7310. LEFT OUTER JOIN sys.dm_exec_requests er ON es.session_id = er.session_id
  7311. LEFT OUTER JOIN sys.dm_exec_connections ec ON es.session_id = ec.session_id
  7312. LEFT OUTER JOIN sys.dm_os_tasks ot ON er.session_id = ot.session_id AND er.request_id = ot.request_id
  7313. LEFT OUTER JOIN sys.dm_exec_sessions es2 ON er.blocking_session_id = es2.session_id
  7314. LEFT OUTER JOIN sys.dm_exec_requests er2 ON es2.session_id = er2.session_id
  7315. LEFT OUTER JOIN sys.dm_exec_connections ec2 ON es2.session_id = ec2.session_id
  7316. LEFT OUTER JOIN
  7317. (
  7318. -- In some cases (e.g. parallel queries, also waiting for a worker), one thread can be flagged as
  7319. -- waiting for several different threads. This will cause that thread to show up in multiple rows
  7320. -- in our grid, which we don't want. Use ROW_NUMBER to select the longest wait for each thread,
  7321. -- and use it as representative of the other wait relationships this thread is involved in.
  7322. SELECT waiting_task_address, session_id, exec_context_id, wait_duration_ms,
  7323. wait_type, resource_address, blocking_task_address, blocking_session_id,
  7324. blocking_exec_context_id, resource_description,
  7325. 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)
  7326. ELSE NULL END AS pageid,
  7327. ROW_NUMBER() OVER (PARTITION BY waiting_task_address ORDER BY wait_duration_ms DESC) AS row_num
  7328. FROM sys.dm_os_waiting_tasks
  7329. WHERE wait_type <> 'SP_SERVER_DIAGNOSTICS_SLEEP'
  7330. ) owt ON ot.task_address = owt.waiting_task_address AND owt.row_num = 1
  7331. --OUTER APPLY sys.dm_exec_sql_text (er.sql_handle) est
  7332. --OUTER APPLY sys.dm_exec_query_plan (er.plan_handle) eqp
  7333. WHERE es.session_id <> @@SPID AND es.is_user_process = 1
  7334. 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
  7335. AND (es.session_id IN (SELECT er3.blocking_session_id FROM sys.dm_exec_requests er3) OR er.blocking_session_id IS NOT NULL)
  7336. ORDER BY blocked_spid, is_head_blocker DESC, blocked_spid_wait_time_ms DESC, blocker_spid;
  7337. IF (SELECT COUNT(blocked_spid) FROM #tblBlkChains WHERE CONVERT(VARCHAR(max), blocked_batch) <> 'sp_server_diagnostics') > 0
  7338. BEGIN
  7339. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Check], '[WARNING: Blocking chains in excess of 5s were found.]' AS [Deviation]
  7340. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Information],[blocked_spid],[blocked_spid_status],[blocked_task_status],
  7341. [blocked_spid_wait_type],[blocked_spid_wait_time_ms],[blocked_spid_res_desc],[blocked_pageid],[blocked_spid_res_type],
  7342. [blocked_batch],[blocked_statement],[blocked_last_start],[blocked_tran_isolation_level],[blocker_spid],[is_head_blocker],
  7343. [blocker_batch],[blocker_statement],[blocker_last_start],[blocker_tran_isolation_level],[blocked_database],
  7344. [blocked_host],[blocked_program],[blocked_login],[blocked_session_comment],[blocked_is_user_process],[blocker_database],
  7345. [blocker_host],[blocker_program],[blocker_login],[blocker_session_comment],[blocker_is_user_process]
  7346. FROM #tblBlkChains
  7347. END
  7348. ELSE
  7349. BEGIN
  7350. SELECT 'Performance_checks' AS [Category], 'Blocking_Chains_over_5s' AS [Check], '[OK]' AS [Deviation]
  7351. END;
  7352. END;
  7353. --------------------------------------------------------------------------------------------------------------------------------
  7354. -- Plan use ratio subsection
  7355. --------------------------------------------------------------------------------------------------------------------------------
  7356. IF @ptochecks = 1
  7357. BEGIN
  7358. RAISERROR (N' |-Starting Plan use ratio', 10, 1) WITH NOWAIT
  7359. IF (SELECT SUM(CAST(size_in_bytes AS bigint))/1024/1024 AS Size_MB
  7360. FROM sys.dm_exec_cached_plans (NOLOCK)
  7361. WHERE cacheobjtype LIKE '%Plan%' AND usecounts = 1)
  7362. >=
  7363. (SELECT SUM(CAST(size_in_bytes AS bigint))/1024/1024 AS Size_MB
  7364. FROM sys.dm_exec_cached_plans (NOLOCK)
  7365. WHERE cacheobjtype LIKE '%Plan%' AND usecounts > 1)
  7366. BEGIN
  7367. 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]
  7368. END
  7369. ELSE
  7370. BEGIN
  7371. SELECT 'Performance_checks' AS [Category], 'Plan_use_ratio' AS [Check], '[OK]' AS [Deviation], '' AS [Comment]
  7372. END;
  7373. --High number of cached plans with usecounts = 1.
  7374. 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
  7375. FROM sys.dm_exec_cached_plans (NOLOCK)
  7376. WHERE cacheobjtype LIKE '%Plan%' AND usecounts = 1
  7377. GROUP BY objtype, cacheobjtype
  7378. UNION ALL
  7379. --High number of cached plans with usecounts > 1.
  7380. 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
  7381. FROM sys.dm_exec_cached_plans (NOLOCK)
  7382. WHERE cacheobjtype LIKE '%Plan%' AND usecounts > 1
  7383. GROUP BY objtype, cacheobjtype
  7384. ORDER BY objtype, cacheobjtype;
  7385. END;
  7386. --------------------------------------------------------------------------------------------------------------------------------
  7387. -- Hints usage subsection
  7388. -- Refer to "Hints" BOL entry for more information (http://msdn.microsoft.com/en-us/library/ms187713.aspx)
  7389. --------------------------------------------------------------------------------------------------------------------------------
  7390. IF @ptochecks = 1
  7391. BEGIN
  7392. RAISERROR (N' |-Starting Hints usage', 10, 1) WITH NOWAIT
  7393. IF (SELECT COUNT([counter]) FROM sys.dm_exec_query_optimizer_info WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1) > 0
  7394. BEGIN
  7395. RAISERROR (N' |-Hints are being used - finding usage in SQL modules', 10, 1) WITH NOWAIT
  7396. /*DECLARE @dbid int, @dbname VARCHAR(1000), @sqlcmd NVARCHAR(4000)*/
  7397. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  7398. DROP TABLE #tblHints;
  7399. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  7400. CREATE TABLE #tblHints ([DBName] sysname, [Schema] VARCHAR(100), [Object] VARCHAR(255), [Type] VARCHAR(100), Hint VARCHAR(30));
  7401. UPDATE #tmpdbs0
  7402. SET isdone = 0;
  7403. UPDATE #tmpdbs0
  7404. SET isdone = 1
  7405. WHERE [state] <> 0 OR [dbid] < 5;
  7406. UPDATE #tmpdbs0
  7407. SET isdone = 1
  7408. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  7409. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  7410. BEGIN
  7411. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  7412. BEGIN
  7413. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  7414. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  7415. SELECT ''' + @dbname + ''' AS [DBName], ss.name AS [Schema_Name], so.name AS [Object_Name], so.type_desc,
  7416. CASE WHEN sm.[definition] LIKE ''%FORCE ORDER%'' THEN ''[FORCE ORDER Hint]''
  7417. WHEN sm.[definition] LIKE ''%MERGE JOIN%''
  7418. OR sm.[definition] LIKE ''%LOOP JOIN%''
  7419. OR sm.[definition] LIKE ''%HASH JOIN%'' THEN ''[JOIN Hint]'' END AS Hint
  7420. FROM sys.sql_modules sm
  7421. INNER JOIN sys.objects so ON sm.[object_id] = so.[object_id]
  7422. INNER JOIN sys.schemas ss ON so.[schema_id] = ss.[schema_id]
  7423. WHERE sm.[definition] LIKE ''%FORCE ORDER%''
  7424. OR sm.[definition] LIKE ''%MERGE JOIN%''
  7425. OR sm.[definition] LIKE ''%LOOP JOIN%''
  7426. OR sm.[definition] LIKE ''%HASH JOIN%'';'
  7427. BEGIN TRY
  7428. INSERT INTO #tblHints
  7429. EXECUTE sp_executesql @sqlcmd
  7430. END TRY
  7431. BEGIN CATCH
  7432. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  7433. SELECT @ErrorMessage = 'Hints usage subsection - Error raised in TRY block. ' + ERROR_MESSAGE()
  7434. RAISERROR (@ErrorMessage, 16, 1);
  7435. END CATCH
  7436. UPDATE #tmpdbs0
  7437. SET isdone = 1
  7438. WHERE [dbid] = @dbid
  7439. END
  7440. END;
  7441. 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]
  7442. 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
  7443. FROM sys.dm_exec_query_optimizer_info (NOLOCK)
  7444. WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1;
  7445. IF (SELECT COUNT(*) FROM #tblHints WHERE [DBName] IS NOT NULL) > 0
  7446. BEGIN
  7447. SELECT 'Performance_checks' AS [Category], 'Hints_usage_in_Objects' AS [Information], [DBName], [Schema], [Object], [Type], Hint, '' AS Comment
  7448. FROM #tblHints (NOLOCK)
  7449. ORDER BY [DBName], Hint, [Type], [Object];
  7450. END
  7451. ELSE
  7452. BEGIN
  7453. SELECT 'Performance_checks' AS [Category], 'Hints_usage_in_Objects' AS [Information], NULL AS [DBName], NULL AS [Schema], NULL AS [Object], NULL AS [Type],
  7454. 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
  7455. FROM sys.dm_exec_query_optimizer_info (NOLOCK)
  7456. WHERE ([counter] = 'order hint' OR [counter] = 'join hint') AND occurrence > 1;
  7457. END
  7458. END
  7459. ELSE
  7460. BEGIN
  7461. SELECT 'Performance_checks' AS [Category], 'Hints_usage' AS [Check], '[OK]' AS [Deviation]
  7462. END
  7463. END;
  7464. --------------------------------------------------------------------------------------------------------------------------------
  7465. -- Cached Query Plans issues subsection
  7466. --------------------------------------------------------------------------------------------------------------------------------
  7467. IF @ptochecks = 1
  7468. BEGIN
  7469. RAISERROR (N' |-Starting Cached Query Plans issues', 10, 1) WITH NOWAIT
  7470. --DECLARE @sqlcmd NVARCHAR(max), @params NVARCHAR(500), @sqlmajorver int, @sqlminorver int, @sqlbuild int
  7471. --SELECT @sqlmajorver = CONVERT(int, (@@microsoftversion / 0x1000000) & 0xff);
  7472. --SELECT @sqlminorver = CONVERT(int, (@@microsoftversion / 0x10000) & 0xff);
  7473. --SELECT @sqlbuild = CONVERT(int, @@microsoftversion & 0xffff);
  7474. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  7475. DROP TABLE #tmp_dm_exec_query_stats;
  7476. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  7477. CREATE TABLE #tmp_dm_exec_query_stats ([plan_id] [int] NOT NULL IDENTITY(1, 1),
  7478. [sql_handle] [varbinary](64) NOT NULL,
  7479. [statement_start_offset] [int] NOT NULL,
  7480. [statement_end_offset] [int] NOT NULL,
  7481. [plan_generation_num] [bigint] NOT NULL,
  7482. [plan_handle] [varbinary](64) NOT NULL,
  7483. [creation_time] [datetime] NOT NULL,
  7484. [last_execution_time] [datetime] NOT NULL,
  7485. [execution_count] [bigint] NOT NULL,
  7486. [total_worker_time] [bigint] NOT NULL,
  7487. [last_worker_time] [bigint] NOT NULL,
  7488. [min_worker_time] [bigint] NOT NULL,
  7489. [max_worker_time] [bigint] NOT NULL,
  7490. [total_physical_reads] [bigint] NOT NULL,
  7491. [last_physical_reads] [bigint] NOT NULL,
  7492. [min_physical_reads] [bigint] NOT NULL,
  7493. [max_physical_reads] [bigint] NOT NULL,
  7494. [total_logical_writes] [bigint] NOT NULL,
  7495. [last_logical_writes] [bigint] NOT NULL,
  7496. [min_logical_writes] [bigint] NOT NULL,
  7497. [max_logical_writes] [bigint] NOT NULL,
  7498. [total_logical_reads] [bigint] NOT NULL,
  7499. [last_logical_reads] [bigint] NOT NULL,
  7500. [min_logical_reads] [bigint] NOT NULL,
  7501. [max_logical_reads] [bigint] NOT NULL,
  7502. [total_clr_time] [bigint] NOT NULL,
  7503. [last_clr_time] [bigint] NOT NULL,
  7504. [min_clr_time] [bigint] NOT NULL,
  7505. [max_clr_time] [bigint] NOT NULL,
  7506. [total_elapsed_time] [bigint] NOT NULL,
  7507. [last_elapsed_time] [bigint] NOT NULL,
  7508. [min_elapsed_time] [bigint] NOT NULL,
  7509. [max_elapsed_time] [bigint] NOT NULL,
  7510. --2008 only
  7511. [query_hash] [binary](8) NULL,
  7512. [query_plan_hash] [binary](8) NULL,
  7513. --2008R2 only
  7514. [total_rows] bigint NULL,
  7515. [last_rows] bigint NULL,
  7516. [min_rows] bigint NULL,
  7517. [max_rows] bigint NULL,
  7518. --post 2012 SP3, 2014 SP2 and 2016
  7519. [Last_grant_kb] bigint NULL,
  7520. [Min_grant_kb] bigint NULL,
  7521. [Max_grant_kb] bigint NULL,
  7522. [Total_grant_kb] bigint NULL,
  7523. [Last_used_grant_kb] bigint NULL,
  7524. [Min_used_grant_kb] bigint NULL,
  7525. [Max_used_grant_kb] bigint NULL,
  7526. [Total_used_grant_kb] bigint NULL,
  7527. [Last_ideal_grant_kb] bigint NULL,
  7528. [Min_ideal_grant_kb] bigint NULL,
  7529. [Max_ideal_grant_kb] bigint NULL,
  7530. [Total_ideal_grant_kb] bigint NULL,
  7531. [Last_dop] bigint NULL,
  7532. [Min_dop] bigint NULL,
  7533. [Max_dop] bigint NULL,
  7534. [Total_dop] bigint NULL,
  7535. [Last_reserved_threads] bigint NULL,
  7536. [Min_reserved_threads] bigint NULL,
  7537. [Max_reserved_threads] bigint NULL,
  7538. [Total_reserved_threads] bigint NULL,
  7539. [Last_used_threads] bigint NULL,
  7540. [Min_used_threads] bigint NULL,
  7541. [Max_used_threads] bigint NULL,
  7542. [Total_used_threads] bigint NULL,
  7543. [Grant2Used_Ratio] float NULL)
  7544. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  7545. DROP TABLE #dm_exec_query_stats;
  7546. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  7547. CREATE TABLE #dm_exec_query_stats ([plan_id] [int] NOT NULL IDENTITY(1, 1),
  7548. [sql_handle] [varbinary](64) NOT NULL,
  7549. [statement_start_offset] [int] NOT NULL,
  7550. [statement_end_offset] [int] NOT NULL,
  7551. [plan_generation_num] [bigint] NOT NULL,
  7552. [plan_handle] [varbinary](64) NOT NULL,
  7553. [creation_time] [datetime] NOT NULL,
  7554. [last_execution_time] [datetime] NOT NULL,
  7555. [execution_count] [bigint] NOT NULL,
  7556. [total_worker_time] [bigint] NOT NULL,
  7557. [last_worker_time] [bigint] NOT NULL,
  7558. [min_worker_time] [bigint] NOT NULL,
  7559. [max_worker_time] [bigint] NOT NULL,
  7560. [total_physical_reads] [bigint] NOT NULL,
  7561. [last_physical_reads] [bigint] NOT NULL,
  7562. [min_physical_reads] [bigint] NOT NULL,
  7563. [max_physical_reads] [bigint] NOT NULL,
  7564. [total_logical_writes] [bigint] NOT NULL,
  7565. [last_logical_writes] [bigint] NOT NULL,
  7566. [min_logical_writes] [bigint] NOT NULL,
  7567. [max_logical_writes] [bigint] NOT NULL,
  7568. [total_logical_reads] [bigint] NOT NULL,
  7569. [last_logical_reads] [bigint] NOT NULL,
  7570. [min_logical_reads] [bigint] NOT NULL,
  7571. [max_logical_reads] [bigint] NOT NULL,
  7572. [total_clr_time] [bigint] NOT NULL,
  7573. [last_clr_time] [bigint] NOT NULL,
  7574. [min_clr_time] [bigint] NOT NULL,
  7575. [max_clr_time] [bigint] NOT NULL,
  7576. [total_elapsed_time] [bigint] NOT NULL,
  7577. [last_elapsed_time] [bigint] NOT NULL,
  7578. [min_elapsed_time] [bigint] NOT NULL,
  7579. [max_elapsed_time] [bigint] NOT NULL,
  7580. --2008 only
  7581. [query_hash] [binary](8) NULL,
  7582. [query_plan_hash] [binary](8) NULL,
  7583. --2008R2 only
  7584. [total_rows] bigint NULL,
  7585. [last_rows] bigint NULL,
  7586. [min_rows] bigint NULL,
  7587. [max_rows] bigint NULL,
  7588. --post 2012 SP3, 2014 SP2 and 2016
  7589. [Last_grant_kb] bigint NULL,
  7590. [Min_grant_kb] bigint NULL,
  7591. [Max_grant_kb] bigint NULL,
  7592. [Total_grant_kb] bigint NULL,
  7593. [Last_used_grant_kb] bigint NULL,
  7594. [Min_used_grant_kb] bigint NULL,
  7595. [Max_used_grant_kb] bigint NULL,
  7596. [Total_used_grant_kb] bigint NULL,
  7597. [Last_ideal_grant_kb] bigint NULL,
  7598. [Min_ideal_grant_kb] bigint NULL,
  7599. [Max_ideal_grant_kb] bigint NULL,
  7600. [Total_ideal_grant_kb] bigint NULL,
  7601. [Last_dop] bigint NULL,
  7602. [Min_dop] bigint NULL,
  7603. [Max_dop] bigint NULL,
  7604. [Total_dop] bigint NULL,
  7605. [Last_reserved_threads] bigint NULL,
  7606. [Min_reserved_threads] bigint NULL,
  7607. [Max_reserved_threads] bigint NULL,
  7608. [Total_reserved_threads] bigint NULL,
  7609. [Last_used_threads] bigint NULL,
  7610. [Min_used_threads] bigint NULL,
  7611. [Max_used_threads] bigint NULL,
  7612. [Total_used_threads] bigint NULL,
  7613. [Grant2Used_Ratio] float NULL,
  7614. --end
  7615. [query_plan] [xml] NULL,
  7616. [text] [nvarchar](MAX) COLLATE database_default NULL,
  7617. [text_filtered] [nvarchar](MAX) COLLATE database_default NULL)
  7618. IF @sqlmajorver = 9
  7619. BEGIN
  7620. --CPU
  7621. 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])
  7622. --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]
  7623. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7624. --ORDER BY qs.total_worker_time DESC');
  7625. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7626. 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]
  7627. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7628. ORDER BY qs.total_worker_time DESC),
  7629. 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
  7630. FROM TopSearch ts
  7631. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7632. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7633. 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]
  7634. FROM TopFineSearch tfs
  7635. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7636. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7637. ORDER BY tfs.total_worker_time DESC');
  7638. --IO
  7639. 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])
  7640. --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]
  7641. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7642. --ORDER BY qs.total_logical_reads DESC');
  7643. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7644. 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]
  7645. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7646. ORDER BY qs.total_logical_reads DESC),
  7647. 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
  7648. FROM TopSearch ts
  7649. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7650. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7651. 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]
  7652. FROM TopFineSearch tfs
  7653. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7654. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7655. ORDER BY tfs.total_logical_reads DESC');
  7656. --Recompiles
  7657. 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])
  7658. --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]
  7659. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7660. --ORDER BY qs.plan_generation_num DESC');
  7661. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7662. 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]
  7663. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7664. ORDER BY qs.plan_generation_num DESC),
  7665. 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
  7666. FROM TopSearch ts
  7667. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7668. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7669. 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]
  7670. FROM TopFineSearch tfs
  7671. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7672. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7673. ORDER BY tfs.plan_generation_num DESC');
  7674. END
  7675. ELSE IF @sqlmajorver = 10 AND (@sqlminorver = 0 OR (@sqlminorver = 50 AND @sqlbuild < 2500))
  7676. BEGIN
  7677. --CPU
  7678. 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])
  7679. --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]
  7680. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7681. --ORDER BY qs.total_worker_time DESC');
  7682. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7683. 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]
  7684. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7685. ORDER BY qs.total_worker_time DESC),
  7686. 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
  7687. FROM TopSearch ts
  7688. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7689. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7690. 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]
  7691. FROM TopFineSearch tfs
  7692. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7693. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7694. ORDER BY tfs.total_worker_time DESC');
  7695. --IO
  7696. 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])
  7697. --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]
  7698. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7699. --ORDER BY qs.total_logical_reads DESC');
  7700. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7701. 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]
  7702. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7703. ORDER BY qs.total_logical_reads DESC),
  7704. 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
  7705. FROM TopSearch ts
  7706. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7707. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7708. 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]
  7709. FROM TopFineSearch tfs
  7710. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7711. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7712. ORDER BY tfs.total_logical_reads DESC');
  7713. --Recompiles
  7714. 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])
  7715. --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]
  7716. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7717. --ORDER BY qs.plan_generation_num DESC');
  7718. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7719. 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]
  7720. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7721. ORDER BY qs.plan_generation_num DESC),
  7722. 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
  7723. FROM TopSearch ts
  7724. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7725. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7726. 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]
  7727. FROM TopFineSearch tfs
  7728. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7729. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7730. ORDER BY tfs.plan_generation_num DESC');
  7731. END
  7732. ELSE IF (@sqlmajorver = 10 AND @sqlminorver = 50) OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  7733. BEGIN
  7734. --CPU
  7735. 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])
  7736. --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]
  7737. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7738. --ORDER BY qs.total_worker_time DESC');
  7739. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7740. 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]
  7741. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7742. ORDER BY qs.total_worker_time DESC),
  7743. 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
  7744. FROM TopSearch ts
  7745. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7746. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7747. 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]
  7748. FROM TopFineSearch tfs
  7749. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7750. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7751. ORDER BY tfs.total_worker_time DESC');
  7752. --IO
  7753. 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])
  7754. --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]
  7755. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7756. --ORDER BY qs.total_logical_reads DESC');
  7757. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7758. 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]
  7759. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7760. ORDER BY qs.total_logical_reads DESC),
  7761. 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
  7762. FROM TopSearch ts
  7763. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7764. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7765. 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]
  7766. FROM TopFineSearch tfs
  7767. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7768. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7769. ORDER BY tfs.total_logical_reads DESC');
  7770. --Recompiles
  7771. 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])
  7772. --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]
  7773. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7774. --ORDER BY qs.plan_generation_num DESC');
  7775. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7776. 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]
  7777. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7778. ORDER BY qs.plan_generation_num DESC),
  7779. 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
  7780. FROM TopSearch ts
  7781. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7782. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7783. 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]
  7784. FROM TopFineSearch tfs
  7785. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7786. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7787. ORDER BY tfs.plan_generation_num DESC');
  7788. END
  7789. ELSE IF (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  7790. BEGIN
  7791. --CPU
  7792. 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])
  7793. --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]
  7794. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7795. --ORDER BY qs.total_worker_time DESC');
  7796. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7797. 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
  7798. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7799. ORDER BY qs.total_worker_time DESC),
  7800. 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
  7801. FROM TopSearch ts
  7802. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7803. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7804. 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
  7805. FROM TopFineSearch tfs
  7806. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7807. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7808. ORDER BY tfs.total_worker_time DESC');
  7809. --IO
  7810. 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])
  7811. --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]
  7812. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7813. --ORDER BY qs.total_logical_reads DESC');
  7814. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7815. 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
  7816. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7817. ORDER BY qs.total_logical_reads DESC),
  7818. 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
  7819. FROM TopSearch ts
  7820. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7821. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7822. 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
  7823. FROM TopFineSearch tfs
  7824. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7825. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7826. ORDER BY tfs.total_logical_reads DESC');
  7827. --Recompiles
  7828. 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])
  7829. --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]
  7830. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7831. --ORDER BY qs.plan_generation_num DESC');
  7832. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7833. 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
  7834. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7835. ORDER BY qs.plan_generation_num DESC),
  7836. 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
  7837. FROM TopSearch ts
  7838. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7839. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7840. 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
  7841. FROM TopFineSearch tfs
  7842. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7843. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7844. ORDER BY tfs.plan_generation_num DESC');
  7845. --Mem Grants
  7846. 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])
  7847. --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]
  7848. --FROM sys.dm_exec_query_stats qs (NOLOCK)
  7849. --ORDER BY qs.Total_grant_kb DESC');
  7850. EXEC (';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan''),
  7851. 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
  7852. FROM sys.dm_exec_query_stats qs (NOLOCK)
  7853. WHERE [Total_used_grant_kb] > 0
  7854. ORDER BY Total_used_grant_kb DESC, COALESCE((([Total_used_grant_kb] * 100.00) / NULLIF([Total_grant_kb],0)), 0) ASC),
  7855. TopFineSearch AS (SELECT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads],ix.query(''.'') AS StmtSimple, Grant2Used_Ratio
  7856. FROM TopSearch ts
  7857. OUTER APPLY sys.dm_exec_query_plan(ts.plan_handle) qp
  7858. CROSS APPLY qp.query_plan.nodes(''//StmtSimple'') AS p(ix))
  7859. SELECT DISTINCT [sql_handle],[statement_start_offset],[statement_end_offset],[plan_generation_num],[plan_handle],[creation_time],[last_execution_time],[execution_count],[total_worker_time],[last_worker_time],[min_worker_time],[max_worker_time],[total_physical_reads],[last_physical_reads],[min_physical_reads],[max_physical_reads],[total_logical_writes],[last_logical_writes],[min_logical_writes],[max_logical_writes],[total_logical_reads],[last_logical_reads],[min_logical_reads],[max_logical_reads],[total_clr_time],[last_clr_time],[min_clr_time],[max_clr_time],[total_elapsed_time],[last_elapsed_time],[min_elapsed_time],[max_elapsed_time],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows],[Last_grant_kb],[Min_grant_kb],[Max_grant_kb],[Total_grant_kb],[Last_used_grant_kb],[Min_used_grant_kb],[Max_used_grant_kb],[Total_used_grant_kb],[Last_ideal_grant_kb],[Min_ideal_grant_kb],[Max_ideal_grant_kb],[Total_ideal_grant_kb],[Last_dop],[Min_dop],[Max_dop],[Total_dop],[Last_reserved_threads],[Min_reserved_threads],[Max_reserved_threads],[Total_reserved_threads],[Last_used_threads],[Min_used_threads],[Max_used_threads],[Total_used_threads], Grant2Used_Ratio
  7860. FROM TopFineSearch tfs
  7861. CROSS APPLY StmtSimple.nodes(''//Object'') AS o(obj)
  7862. WHERE obj.value(''@Database'',''sysname'') NOT IN (''[master]'',''[mssqlsystemresource]'')
  7863. ORDER BY tfs.Grant2Used_Ratio ASC');
  7864. END;
  7865. -- Remove duplicates before inserting XML
  7866. IF @sqlmajorver = 9
  7867. BEGIN
  7868. 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])
  7869. 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]
  7870. FROM #tmp_dm_exec_query_stats;
  7871. END
  7872. ELSE IF @sqlmajorver = 10 AND (@sqlminorver = 0 OR (@sqlminorver = 50 AND @sqlbuild < 2500))
  7873. BEGIN
  7874. 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])
  7875. 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]
  7876. FROM #tmp_dm_exec_query_stats;
  7877. END
  7878. ELSE IF (@sqlmajorver = 10 AND @sqlminorver = 50) OR (@sqlmajorver = 11 AND @sqlbuild < 6020) OR (@sqlmajorver = 12 AND @sqlbuild < 5000)
  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],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows])
  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],[query_hash],[query_plan_hash],[total_rows],[last_rows],[min_rows],[max_rows]
  7882. FROM #tmp_dm_exec_query_stats;
  7883. END
  7884. ELSE IF (@sqlmajorver = 11 AND @sqlbuild >= 6020) OR (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  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],[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])
  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],[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]
  7888. FROM #tmp_dm_exec_query_stats;
  7889. END;
  7890. UPDATE #dm_exec_query_stats
  7891. SET query_plan = qp.query_plan,
  7892. [text] = st.[text],
  7893. text_filtered = SUBSTRING(st.[text],
  7894. (CASE WHEN qs.statement_start_offset = 0 THEN 0 ELSE qs.statement_start_offset/2 END),
  7895. (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)))
  7896. FROM #dm_exec_query_stats qs
  7897. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
  7898. CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
  7899. -- Delete own queries
  7900. DELETE FROM #dm_exec_query_stats
  7901. WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE '%Query_Plan_Warnings%';
  7902. -- Aggregate results
  7903. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  7904. DROP TABLE #qpwarnings;
  7905. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  7906. CREATE TABLE #qpwarnings ([Deviation] VARCHAR(50), [Comment] VARCHAR(255), query_plan XML, [statement] XML)
  7907. -- Find issues
  7908. INSERT INTO #qpwarnings
  7909. SELECT 'Scalar_UDFs'AS [Deviation],
  7910. ('[WARNING: Scalar UDF found in a top resource-intensive query, which that may inhibit parallelism]') AS [Comment],
  7911. 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(
  7912. qs.text_filtered,
  7913. 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'?')
  7914. FOR XML PATH(''), TYPE) AS [statement]
  7915. FROM #dm_exec_query_stats qs
  7916. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%UserDefinedFunction%'
  7917. UNION ALL
  7918. SELECT 'Implicit_Conversion_with_IX_Scan'AS [Deviation],
  7919. ('[WARNING: Implicit type conversions found where an Index Scan is present]') AS Details ,
  7920. 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(
  7921. qs.text_filtered,
  7922. 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'?')
  7923. FOR XML PATH(''), TYPE) AS [statement]
  7924. FROM #dm_exec_query_stats qs
  7925. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%CONVERT_IMPLICIT%'
  7926. AND CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%PhysicalOp="Index Scan"%'
  7927. UNION ALL
  7928. SELECT 'Missing_Index'AS [Deviation],
  7929. ('[WARNING: One of the top resource-intensive queries may be improved by adding an index]') AS [Comment],
  7930. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7931. qs.text_filtered,
  7932. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7933. FOR XML PATH(''), TYPE) AS [statement]
  7934. FROM #dm_exec_query_stats qs
  7935. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%MissingIndexGroup%'
  7936. UNION ALL
  7937. SELECT 'Cursor'AS [Deviation],
  7938. ('[WARNING: Cursor usage found in a top resource-intensive query. Check if it can be rewritten as a WHILE cycle]') AS [Comment],
  7939. qs.query_plan, (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  7940. qs.text_filtered,
  7941. NCHAR(1),N'?'),NCHAR(2),N'?'),NCHAR(3),N'?'),NCHAR(4),N'?'),NCHAR(5),N'?'),NCHAR(6),N'?'),NCHAR(7),N'?'),NCHAR(8),N'?'),NCHAR(11),N'?'),NCHAR(12),N'?'),NCHAR(14),N'?'),NCHAR(15),N'?'),NCHAR(16),N'?'),NCHAR(17),N'?'),NCHAR(18),N'?'),NCHAR(19),N'?'),NCHAR(20),N'?'),NCHAR(21),N'?'),NCHAR(22),N'?'),NCHAR(23),N'?'),NCHAR(24),N'?'),NCHAR(25),N'?'),NCHAR(26),N'?'),NCHAR(27),N'?'),NCHAR(28),N'?'),NCHAR(29),N'?'),NCHAR(30),N'?'),NCHAR(31),N'?')
  7942. FOR XML PATH(''), TYPE) AS [statement]
  7943. FROM #dm_exec_query_stats qs
  7944. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<CursorType%'
  7945. UNION ALL
  7946. SELECT 'Missing_Join_Predicate'AS [Deviation],
  7947. ('[WARNING: NO JOIN predicate event fired for a top resource-intensive query]') AS [Comment],
  7948. 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(
  7949. qs.text_filtered,
  7950. 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'?')
  7951. FOR XML PATH(''), TYPE) AS [statement]
  7952. FROM #dm_exec_query_stats qs
  7953. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings NoJoinPredicate="true"%'
  7954. UNION ALL
  7955. SELECT 'Columns_with_no_Statistics'AS [Deviation],
  7956. ('[WARNING: Missing Column Statistics event fired for a top resource-intensive query]') AS [Comment],
  7957. 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(
  7958. qs.text_filtered,
  7959. 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'?')
  7960. FOR XML PATH(''), TYPE) AS [statement]
  7961. FROM #dm_exec_query_stats qs
  7962. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings ColumnsWithNoStatistics%';
  7963. IF @sqlmajorver > 10
  7964. BEGIN
  7965. INSERT INTO #qpwarnings
  7966. -- Note that currently SpillToTempDb warnings are only found in actual execution plans
  7967. SELECT 'Spill_to_TempDb'AS [Deviation],
  7968. ('[WARNING: Spill to TempDB found during a HASH or SORT operation]') 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 '%<SpillToTempDb SpillLevel%'
  7975. UNION ALL
  7976. SELECT 'Implicit_Convert_affecting_Seek_Plan'AS [Deviation],
  7977. ('[WARNING: Implicit type conversions found, which can be affecting the choice of seek plans]') AS [Comment],
  7978. 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(
  7979. qs.text_filtered,
  7980. 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'?')
  7981. FOR XML PATH(''), TYPE) AS [statement]
  7982. FROM #dm_exec_query_stats qs
  7983. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Seek Plan" Expression="CONVERT_IMPLICIT%'
  7984. UNION ALL
  7985. SELECT 'Explicit_Conversion_affecting_Cardinality'AS [Deviation],
  7986. ('[WARNING: Explicit type conversions found, which can be affecting cardinality estimates]') AS [Comment],
  7987. 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(
  7988. qs.text_filtered,
  7989. 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'?')
  7990. FOR XML PATH(''), TYPE) AS [statement]
  7991. FROM #dm_exec_query_stats qs
  7992. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Cardinality Estimate" Expression="CONVERT%'
  7993. UNION ALL
  7994. SELECT 'Implicit_Conversion_affecting_Cardinality'AS [Deviation],
  7995. ('[WARNING: Implicit type conversions found, which can be affecting cardinality estimates]') AS [Comment],
  7996. 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(
  7997. qs.text_filtered,
  7998. 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'?')
  7999. FOR XML PATH(''), TYPE) AS [statement]
  8000. FROM #dm_exec_query_stats qs
  8001. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<PlanAffectingConvert ConvertIssue="Cardinality Estimate" Expression="CONVERT_IMPLICIT%'
  8002. UNION ALL
  8003. SELECT 'Unmatched_Indexes'AS [Deviation],
  8004. ('[WARNING: An unmatched indexes warning fired, where an index could not be used due to parameterization]') AS [Comment],
  8005. 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(
  8006. qs.text_filtered,
  8007. 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'?')
  8008. FOR XML PATH(''), TYPE) AS [statement]
  8009. FROM #dm_exec_query_stats qs
  8010. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<Warnings UnmatchedIndexes="true"%';
  8011. END;
  8012. IF (@sqlmajorver = 12 AND @sqlbuild >= 5000) OR @sqlmajorver = 13
  8013. BEGIN
  8014. INSERT INTO #qpwarnings
  8015. -- Note that currently MemoryGrant warnings are only found in actual execution plans
  8016. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8017. ('[WARNING: Granted memory was much larger than maximum used memory]') AS [Comment],
  8018. 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(
  8019. qs.text_filtered,
  8020. 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'?')
  8021. FOR XML PATH(''), TYPE) AS [statement]
  8022. FROM #dm_exec_query_stats qs
  8023. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Excessive Grant"%'
  8024. UNION ALL
  8025. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8026. ('[WARNING: Maximum used memory exceeds granted memory]') AS [Comment],
  8027. 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(
  8028. qs.text_filtered,
  8029. 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'?')
  8030. FOR XML PATH(''), TYPE) AS [statement]
  8031. FROM #dm_exec_query_stats qs
  8032. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Used More Than Granted"%'
  8033. UNION ALL
  8034. SELECT 'Excessive_Memory_Grant'AS [Deviation],
  8035. ('[WARNING: Dynamic grant increased too much when compared to initial grant request]') AS [Comment],
  8036. 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(
  8037. qs.text_filtered,
  8038. 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'?')
  8039. FOR XML PATH(''), TYPE) AS [statement]
  8040. FROM #dm_exec_query_stats qs
  8041. WHERE CAST(qs.query_plan AS NVARCHAR(MAX)) LIKE '%<MemoryGrantWarning GrantWarningKind="Grant Increase"%'
  8042. END;
  8043. IF (SELECT COUNT(*) FROM #qpwarnings) > 0
  8044. BEGIN
  8045. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], '[WARNING: Top resource-intensive queries issued plan level warnings]' AS [Deviation]
  8046. END
  8047. ELSE
  8048. BEGIN
  8049. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], '[OK]' AS [Deviation]
  8050. END;
  8051. IF (SELECT COUNT(*) FROM #qpwarnings) > 0
  8052. BEGIN
  8053. SELECT 'Performance_checks' AS [Category], 'Query_Plan_Warnings' AS [Check], [Comment], query_plan, [statement]
  8054. FROM #qpwarnings;
  8055. END;
  8056. IF (SELECT COUNT(*) FROM #dm_exec_query_stats) > 0
  8057. BEGIN
  8058. SELECT 'Performance_checks' AS [Category], 'Inefficient_Plans_Reads' AS [Check], query_plan,
  8059. (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(
  8060. text_filtered,
  8061. 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'?')
  8062. FOR XML PATH(''), TYPE) AS [statement],
  8063. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8064. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8065. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8066. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8067. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8068. [Grant2Used_Ratio],
  8069. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8070. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8071. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8072. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8073. FROM #dm_exec_query_stats
  8074. ORDER BY [Avg_Logical_Reads] DESC;
  8075. SELECT 'Performance_checks' AS [Category], 'Inefficient_Plans_CPU' AS [Check], query_plan,
  8076. (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(
  8077. text_filtered,
  8078. 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'?')
  8079. FOR XML PATH(''), TYPE) AS [statement],
  8080. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8081. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8082. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8083. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8084. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8085. [Grant2Used_Ratio],
  8086. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8087. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8088. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8089. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8090. FROM #dm_exec_query_stats
  8091. ORDER BY [Avg_Worker_Time] DESC;
  8092. SELECT 'Performance_checks' AS [Category], 'Inefficient_Memory_Use' AS [Check], query_plan,
  8093. (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(
  8094. text_filtered,
  8095. 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'?')
  8096. FOR XML PATH(''), TYPE) AS [statement],
  8097. [execution_count], [total_worker_time]/[execution_count] AS [Avg_Worker_Time],
  8098. [total_physical_reads]/[execution_count] AS [Avg_Physical_Reads],
  8099. [total_logical_reads]/[execution_count] AS [Avg_Logical_Reads],
  8100. CASE WHEN [Total_grant_kb] IS NOT NULL THEN [Total_grant_kb]/[execution_count] ELSE -1 END AS [Avg_grant_kb],
  8101. CASE WHEN [Total_used_grant_kb] IS NOT NULL THEN [Total_used_grant_kb]/[execution_count] ELSE -1 END AS [Avg_used_grant_kb],
  8102. [Grant2Used_Ratio],
  8103. CASE WHEN [Total_ideal_grant_kb] IS NOT NULL THEN [Total_ideal_grant_kb]/[execution_count] ELSE -1 END AS [Avg_ideal_grant_kb],
  8104. CASE WHEN [Total_dop] IS NOT NULL THEN [Total_dop]/[execution_count] ELSE -1 END AS [Avg_dop],
  8105. CASE WHEN [Total_reserved_threads] IS NOT NULL THEN [Total_reserved_threads]/[execution_count] ELSE -1 END AS [Avg_reserved_threads],
  8106. CASE WHEN [Total_used_threads] IS NOT NULL THEN [Total_used_threads]/[execution_count] ELSE -1 END AS [Avg_used_threads]
  8107. FROM #dm_exec_query_stats
  8108. ORDER BY Grant2Used_Ratio ASC;
  8109. END;
  8110. END;
  8111. --------------------------------------------------------------------------------------------------------------------------------
  8112. -- Declarative Referential Integrity - Untrusted Constraints subsection
  8113. --------------------------------------------------------------------------------------------------------------------------------
  8114. IF @ptochecks = 1
  8115. BEGIN
  8116. RAISERROR (N' |-Starting Declarative Referential Integrity - Untrusted Constraints', 10, 1) WITH NOWAIT
  8117. /*
  8118. Declarative Referential Integrity (DRI), meaning “trusting” constraints will allow SQL Server to introduce optimizations that would otherwise not be possible,
  8119. such as eliminating JOINs or even not reading any table for particular queries.
  8120. 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.
  8121. */
  8122. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  8123. DROP TABLE #tblDRI;
  8124. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  8125. 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)
  8126. CONSTRAINT PK_DRI PRIMARY KEY CLUSTERED(databaseID, [schema_id], [object_id], [constraint_name]))
  8127. UPDATE #tmpdbs1
  8128. SET isdone = 0
  8129. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  8130. BEGIN
  8131. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  8132. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8133. USE ' + QUOTENAME(@dbname) + '
  8134. 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]
  8135. FROM sys.foreign_keys FKC (NOLOCK)
  8136. INNER JOIN sys.objects o (NOLOCK) ON FKC.parent_object_id = o.[object_id]
  8137. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8138. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8139. WHERE o.type = ''U'' AND FKC.is_not_trusted = 1 AND FKC.is_not_for_replication = 0
  8140. GROUP BY o.[schema_id], mst.[object_id], FKC.name, t.name, mst.name
  8141. UNION ALL
  8142. 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]
  8143. FROM sys.check_constraints CC (NOLOCK)
  8144. INNER JOIN sys.objects o (NOLOCK) ON CC.parent_object_id = o.[object_id]
  8145. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8146. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8147. WHERE o.type = ''U'' AND CC.is_not_trusted = 1 AND CC.is_not_for_replication = 0 AND CC.is_disabled = 0
  8148. GROUP BY t.[schema_id], mst.[object_id], CC.name, t.name, mst.name
  8149. ORDER BY mst.name, [constraint_name];'
  8150. BEGIN TRY
  8151. INSERT INTO #tblDRI
  8152. EXECUTE sp_executesql @sqlcmd
  8153. END TRY
  8154. BEGIN CATCH
  8155. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8156. SELECT @ErrorMessage = 'Declarative Referential Integrity subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8157. RAISERROR (@ErrorMessage, 16, 1);
  8158. END CATCH
  8159. UPDATE #tmpdbs1
  8160. SET isdone = 1
  8161. WHERE [dbid] = @dbid
  8162. END;
  8163. IF (SELECT COUNT(*) FROM #tblDRI) > 0
  8164. BEGIN
  8165. 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]
  8166. SELECT 'Performance_checks' AS [Category], 'DRI_UntrustedConstraints' AS [Information], [database_name] AS [Database_Name], constraint_name AS [Constraint_Name],
  8167. [schema_name] AS [Schema_Name], table_name AS [Table_Name], [constraint_type] AS [Constraint_Type]
  8168. FROM #tblDRI
  8169. ORDER BY [database_name], [schema_name], table_name, [constraint_type];
  8170. IF @gen_scripts = 1
  8171. BEGIN
  8172. DECLARE @strSQL1 NVARCHAR(4000)
  8173. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8174. PRINT CHAR(10) + '--############# Trust untrusted Contraints statements #############' + CHAR(10)
  8175. DECLARE cDRI CURSOR FAST_FORWARD FOR SELECT 'USE ' + [database_name] + CHAR(10) + 'GO' + CHAR(10) +
  8176. 'ALTER TABLE ' + QUOTENAME([schema_name]) + '.' + QUOTENAME(table_name) + CHAR(10) +
  8177. 'WITH CHECK CHECK CONSTRAINT ' + QUOTENAME(constraint_name) + CHAR(10) + 'GO'
  8178. FROM #tblDRI
  8179. ORDER BY [database_name], [schema_name], table_name, [constraint_type]
  8180. OPEN cDRI
  8181. FETCH NEXT FROM cDRI INTO @strSQL1
  8182. WHILE (@@FETCH_STATUS = 0)
  8183. BEGIN
  8184. PRINT @strSQL1
  8185. FETCH NEXT FROM cDRI INTO @strSQL1
  8186. END
  8187. CLOSE cDRI
  8188. DEALLOCATE cDRI
  8189. PRINT CHAR(10) + '--############# Ended Trust untrusted Contraints statements #############' + CHAR(10)
  8190. END;
  8191. END
  8192. ELSE
  8193. BEGIN
  8194. SELECT 'Performance_checks' AS [Category], 'DRI_UntrustedConstraints' AS [Check], '[OK]' AS [Deviation]
  8195. END;
  8196. END;
  8197. IF @ptochecks = 1
  8198. RAISERROR (N'|-Starting Indexes and Statistics Checks', 10, 1) WITH NOWAIT
  8199. --------------------------------------------------------------------------------------------------------------------------------
  8200. -- Statistics update subsection
  8201. --------------------------------------------------------------------------------------------------------------------------------
  8202. IF @ptochecks = 1
  8203. BEGIN
  8204. RAISERROR (N' |-Starting Statistics update', 10, 1) WITH NOWAIT
  8205. UPDATE #tmpdbs0
  8206. SET isdone = 0;
  8207. UPDATE #tmpdbs0
  8208. SET isdone = 1
  8209. WHERE [state] <> 0 OR [dbid] < 5;
  8210. UPDATE #tmpdbs0
  8211. SET isdone = 1
  8212. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8213. DECLARE @dbcmptlevel int
  8214. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  8215. DROP TABLE #tblStatsUpd;
  8216. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  8217. 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)
  8218. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8219. BEGIN
  8220. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8221. BEGIN
  8222. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid], @dbcmptlevel = [compatibility_level] FROM #tmpdbs0 WHERE isdone = 0
  8223. IF ((@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4000) OR (@sqlmajorver = 11 AND @sqlbuild >= 3000) OR @sqlmajorver > 11) AND @dbcmptlevel > 80
  8224. BEGIN
  8225. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8226. 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,
  8227. 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
  8228. FROM sys.objects AS o
  8229. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8230. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8231. INNER JOIN sys.stats AS ss ON ss.[object_id] = mst.[object_id]
  8232. CROSS APPLY sys.dm_db_stats_properties(ss.[object_id], ss.[stats_id]) AS sp
  8233. WHERE sp.[rows] > 0
  8234. AND ((sp.[rows] <= 500 AND sp.modification_counter >= 500)
  8235. OR (sp.[rows] > 500 AND sp.modification_counter >= (500 + sp.[rows] * 0.20)))'
  8236. END
  8237. ELSE
  8238. BEGIN
  8239. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8240. 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,
  8241. 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
  8242. FROM sys.sysindexes AS si
  8243. INNER JOIN sys.objects AS o ON si.id = o.[object_id]
  8244. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8245. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8246. INNER JOIN sys.stats AS ss ON ss.[object_id] = o.[object_id]
  8247. INNER JOIN sys.partitions AS p ON p.[object_id] = ss.[object_id]
  8248. LEFT JOIN sys.indexes i ON si.id = i.[object_id] AND si.indid = i.index_id
  8249. WHERE o.type <> ''S'' AND i.name IS NOT NULL
  8250. GROUP BY mst.[object_id], t.name, rowmodctr, ss.stats_id, ss.name, ss.auto_created, ss.user_created
  8251. HAVING SUM(p.[rows]) > 0
  8252. AND ((SUM(p.[rows]) <= 500 AND rowmodctr >= 500)
  8253. OR (SUM(p.[rows]) > 500 AND rowmodctr >= (500 + SUM(p.[rows]) * 0.20)))'
  8254. END
  8255. BEGIN TRY
  8256. INSERT INTO #tblStatsUpd
  8257. EXECUTE sp_executesql @sqlcmd
  8258. END TRY
  8259. BEGIN CATCH
  8260. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8261. SELECT @ErrorMessage = 'Statistics update subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8262. RAISERROR (@ErrorMessage, 16, 1);
  8263. END CATCH
  8264. UPDATE #tmpdbs0
  8265. SET isdone = 1
  8266. WHERE [dbid] = @dbid
  8267. END
  8268. END;
  8269. CREATE INDEX IX_Stats ON #tblStatsUpd([databaseID]);
  8270. IF (SELECT COUNT(*) FROM #tblStatsUpd) > 0
  8271. BEGIN
  8272. 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
  8273. BEGIN
  8274. 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]
  8275. 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],
  8276. last_updated, [rows], modification_counter, CAST((su.modification_counter*1.00/(su.[rows]*1.00))*100.0 AS DECIMAL(18,2)) AS [RowMod_Pct],
  8277. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8278. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8279. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8280. ELSE NULL
  8281. END AS [Statistic_Type],
  8282. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition], su.unfiltered_rows AS [Unfiltered_Rows]
  8283. FROM #tblStatsUpd AS su INNER JOIN master.sys.databases AS sd (NOLOCK) ON su.[databaseID] = sd.[database_id]
  8284. WHERE sd.is_auto_update_stats_on = 0
  8285. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8286. END;
  8287. 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
  8288. BEGIN
  8289. 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]
  8290. 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],
  8291. last_updated, [rows], modification_counter, CAST((su.modification_counter*1.00/(su.[rows]*1.00))*100.0 AS DECIMAL(18,2)) AS [RowMod_Pct],
  8292. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8293. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8294. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8295. ELSE NULL
  8296. END AS [Statistic_Type],
  8297. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition]
  8298. FROM #tblStatsUpd AS su INNER JOIN master.sys.databases AS sd (NOLOCK) ON su.[databaseID] = sd.[database_id]
  8299. WHERE sd.is_auto_update_stats_on = 1
  8300. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8301. END;
  8302. END
  8303. ELSE
  8304. BEGIN
  8305. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_to_update' AS [Check], '[OK]' AS [Deviation]
  8306. END;
  8307. END;
  8308. --------------------------------------------------------------------------------------------------------------------------------
  8309. -- Statistics sampling subsection
  8310. --------------------------------------------------------------------------------------------------------------------------------
  8311. IF @ptochecks = 1
  8312. BEGIN
  8313. IF (@sqlmajorver = 10 AND @sqlminorver = 50 AND @sqlbuild >= 4000) OR (@sqlmajorver = 11 AND @sqlbuild >= 3000) OR @sqlmajorver > 11
  8314. BEGIN
  8315. RAISERROR (N' |-Starting Statistics sampling', 10, 1) WITH NOWAIT
  8316. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  8317. DROP TABLE #tblStatsSamp;
  8318. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  8319. 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)
  8320. UPDATE #tmpdbs0
  8321. SET isdone = 0;
  8322. UPDATE #tmpdbs0
  8323. SET isdone = 1
  8324. WHERE [state] <> 0 OR [dbid] < 5;
  8325. UPDATE #tmpdbs0
  8326. SET isdone = 1
  8327. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8328. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8329. BEGIN
  8330. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8331. BEGIN
  8332. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid], @dbcmptlevel = [compatibility_level] FROM #tmpdbs0 WHERE isdone = 0
  8333. IF @dbcmptlevel > 80
  8334. BEGIN
  8335. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8336. 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,
  8337. 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
  8338. FROM sys.objects AS o
  8339. INNER JOIN sys.tables AS mst ON mst.[object_id] = o.[object_id]
  8340. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8341. INNER JOIN sys.stats AS ss ON ss.[object_id] = mst.[object_id]
  8342. CROSS APPLY sys.dm_db_stats_properties(ss.[object_id], ss.[stats_id]) AS sp
  8343. WHERE sp.[rows] > 0
  8344. AND CAST((sp.rows_sampled/(sp.[rows]*1.00))*100.0 AS DECIMAL(5,2)) < 25'
  8345. BEGIN TRY
  8346. INSERT INTO #tblStatsSamp
  8347. EXECUTE sp_executesql @sqlcmd
  8348. END TRY
  8349. BEGIN CATCH
  8350. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8351. SELECT @ErrorMessage = 'Statistics sampling subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8352. RAISERROR (@ErrorMessage, 16, 1);
  8353. END CATCH
  8354. END
  8355. UPDATE #tmpdbs0
  8356. SET isdone = 1
  8357. WHERE [dbid] = @dbid
  8358. END
  8359. END;
  8360. CREATE INDEX IX_Stats ON #tblStatsSamp([databaseID]);
  8361. IF (SELECT COUNT(*) FROM #tblStatsSamp) > 0
  8362. BEGIN
  8363. 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]
  8364. 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],
  8365. last_updated, [rows], rows_sampled, CAST((rows_sampled/([rows]*1.00))*100.0 AS DECIMAL(5,2)) AS [Sample_Pct],
  8366. CASE WHEN su.auto_created = 0 AND su.user_created = 0 THEN 'Index_Statistic'
  8367. WHEN su.auto_created = 0 AND su.user_created = 1 THEN 'User_Created'
  8368. WHEN su.auto_created = 1 AND su.user_created = 0 THEN 'Auto_Created'
  8369. ELSE NULL
  8370. END AS [Statistic_Type],
  8371. su.steps, su.has_filter AS [Is_Filtered], su.filter_definition AS [Filter_Definition]
  8372. FROM #tblStatsSamp AS su
  8373. ORDER BY [DatabaseName], [tableName], [stats_id] DESC
  8374. END
  8375. ELSE
  8376. BEGIN
  8377. SELECT 'Index_and_Stats_checks' AS [Category], 'Statistics_sampling_lt_25pct' AS [Check], '[OK]' AS [Deviation]
  8378. END;
  8379. END;
  8380. END;
  8381. --------------------------------------------------------------------------------------------------------------------------------
  8382. -- Hypothetical objects subsection
  8383. --------------------------------------------------------------------------------------------------------------------------------
  8384. IF @ptochecks = 1
  8385. BEGIN
  8386. RAISERROR (N' |-Starting Hypothetical objects', 10, 1) WITH NOWAIT
  8387. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  8388. DROP TABLE #tblHypObj;
  8389. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  8390. CREATE TABLE #tblHypObj ([DBName] sysname, [Schema] VARCHAR(100), [Table] VARCHAR(255), [Object] VARCHAR(255), [Type] VARCHAR(10));
  8391. UPDATE #tmpdbs0
  8392. SET isdone = 0;
  8393. UPDATE #tmpdbs0
  8394. SET isdone = 1
  8395. WHERE [state] <> 0 OR [dbid] = 2;
  8396. UPDATE #tmpdbs0
  8397. SET isdone = 1
  8398. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8399. IF (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8400. BEGIN
  8401. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8402. BEGIN
  8403. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  8404. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  8405. SELECT ''' + @dbname + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), i.name, ''INDEX''
  8406. FROM sys.indexes i
  8407. INNER JOIN sys.objects o ON o.[object_id] = i.[object_id]
  8408. INNER JOIN sys.tables AS mst ON mst.[object_id] = i.[object_id]
  8409. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8410. WHERE i.is_hypothetical = 1
  8411. UNION ALL
  8412. SELECT ''' + @dbname + ''' AS [DBName], QUOTENAME(t.name), QUOTENAME(o.[name]), s.name, ''STATISTICS''
  8413. FROM sys.stats s
  8414. INNER JOIN sys.objects o (NOLOCK) ON o.[object_id] = s.[object_id]
  8415. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = s.[object_id]
  8416. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8417. WHERE (s.name LIKE ''hind_%'' OR s.name LIKE ''_dta_stat%'') AND auto_created = 0
  8418. AND s.name NOT IN (SELECT name FROM ' + QUOTENAME(@dbname) + '.sys.indexes)'
  8419. BEGIN TRY
  8420. INSERT INTO #tblHypObj
  8421. EXECUTE sp_executesql @sqlcmd
  8422. END TRY
  8423. BEGIN CATCH
  8424. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8425. SELECT @ErrorMessage = 'Hypothetical objects subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8426. RAISERROR (@ErrorMessage, 16, 1);
  8427. END CATCH
  8428. UPDATE #tmpdbs0
  8429. SET isdone = 1
  8430. WHERE [dbid] = @dbid
  8431. END
  8432. END;
  8433. UPDATE #tmpdbs0
  8434. SET isdone = 0;
  8435. IF (SELECT COUNT([Object]) FROM #tblHypObj) > 0
  8436. BEGIN
  8437. 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]
  8438. 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]
  8439. FROM #tblHypObj
  8440. ORDER BY 2, 3, 5
  8441. IF @gen_scripts = 1
  8442. BEGIN
  8443. DECLARE @strSQL NVARCHAR(4000)
  8444. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8445. PRINT CHAR(10) + '--############# Existing Hypothetical objects drop statements #############' + CHAR(10)
  8446. 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) +
  8447. CASE WHEN [Type] = 'STATISTICS' THEN 'DROP STATISTICS ' + [Schema] + '.' + [Table] + '.' + QUOTENAME([Object]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  8448. ELSE 'DROP INDEX ' + QUOTENAME([Object]) + ' ON ' + [Schema] + '.' + [Table] + ';' + CHAR(10) + 'GO' + CHAR(10)
  8449. END
  8450. FROM #tblHypObj
  8451. ORDER BY DBName, [Table]
  8452. OPEN ITW_Stats
  8453. FETCH NEXT FROM ITW_Stats INTO @strSQL
  8454. WHILE (@@FETCH_STATUS = 0)
  8455. BEGIN
  8456. PRINT @strSQL
  8457. FETCH NEXT FROM ITW_Stats INTO @strSQL
  8458. END
  8459. CLOSE ITW_Stats
  8460. DEALLOCATE ITW_Stats
  8461. PRINT CHAR(10) + '--############# Ended Hypothetical objects drop statements #############' + CHAR(10)
  8462. END;
  8463. END
  8464. ELSE
  8465. BEGIN
  8466. SELECT 'Index_and_Stats_checks' AS [Category], 'Hypothetical_objects' AS [Check], '[OK]' AS [Deviation]
  8467. END;
  8468. END;
  8469. --------------------------------------------------------------------------------------------------------------------------------
  8470. -- Index Health Analysis subsection
  8471. --------------------------------------------------------------------------------------------------------------------------------
  8472. IF @ixfrag = 1 AND @ptochecks = 1
  8473. BEGIN
  8474. RAISERROR (N' |-Starting Index Health Analysis check', 10, 1) WITH NOWAIT
  8475. DECLARE /*@dbid int, */@objectid int, @indexid int, @partition_nr int, @type_desc NVARCHAR(60)
  8476. DECLARE @ColumnStoreGetIXSQL NVARCHAR(2000), @ColumnStoreGetIXSQL_Param NVARCHAR(1000), @HasInMem bit
  8477. DECLARE /*@sqlcmd NVARCHAR(4000), @params NVARCHAR(500),*/ @schema_name VARCHAR(100), @table_name VARCHAR(300), @KeyCols VARCHAR(4000), @distinctCnt bigint, @OptimBucketCnt bigint
  8478. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  8479. DROP TABLE #tmpIPS;
  8480. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  8481. 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,
  8482. CONSTRAINT PK_IPS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id], [partition_number]));
  8483. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  8484. DROP TABLE #tmpIPS_CI;
  8485. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  8486. 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),
  8487. CONSTRAINT PK_IPS_CI PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id], [partition_number], row_group_id));
  8488. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  8489. DROP TABLE #tmpXIS;
  8490. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  8491. 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,
  8492. CONSTRAINT PK_tmpXIS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id]));
  8493. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  8494. DROP TABLE #tmpXNCIS;
  8495. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  8496. 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,
  8497. CONSTRAINT PK_tmpXNCIS PRIMARY KEY CLUSTERED(database_id, [object_id], [index_id]));
  8498. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  8499. DROP TABLE #tblWorking;
  8500. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  8501. 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)
  8502. -- type 0 = Heap; 1 = Clustered; 2 = Nonclustered; 3 = XML; 4 = Spatial; 5 = Clustered columnstore; 6 = Nonclustered columnstore; 7 = Nonclustered hash
  8503. RAISERROR (N' |-Populating support table...', 10, 1) WITH NOWAIT
  8504. UPDATE #tmpdbs0
  8505. SET isdone = 0;
  8506. UPDATE #tmpdbs0
  8507. SET isdone = 1
  8508. WHERE [state] <> 0 OR [dbid] < 5;
  8509. UPDATE #tmpdbs0
  8510. SET isdone = 1
  8511. WHERE [role] = 2 AND secondary_role_allow_connections = 0;
  8512. IF EXISTS (SELECT TOP 1 id FROM #tmpdbs0 WHERE isdone = 0)
  8513. BEGIN
  8514. WHILE (SELECT COUNT(id) FROM #tmpdbs0 WHERE isdone = 0) > 0
  8515. BEGIN
  8516. SELECT TOP 1 @dbid = [dbid] FROM #tmpdbs0 WHERE isdone = 0
  8517. 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
  8518. FROM [' + DB_NAME(@dbid) + '].sys.indexes si
  8519. INNER JOIN [' + DB_NAME(@dbid) + '].sys.partitions sp ON si.[object_id] = sp.[object_id] AND si.index_id = sp.index_id
  8520. INNER JOIN [' + DB_NAME(@dbid) + '].sys.tables AS mst ON mst.[object_id] = si.[object_id]
  8521. INNER JOIN [' + DB_NAME(@dbid) + '].sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8522. 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
  8523. INSERT INTO #tblWorking
  8524. EXEC sp_executesql @sqlcmd;
  8525. IF @sqlmajorver >= 12
  8526. BEGIN
  8527. SELECT @sqlcmd = 'SELECT @HasInMemOUT = ISNULL((SELECT TOP 1 1 FROM [' + DB_NAME(@dbid) + '].sys.filegroups FG where FG.[type] = ''FX''), 0)'
  8528. SET @params = N'@HasInMemOUT bit OUTPUT';
  8529. EXECUTE sp_executesql @sqlcmd, @params, @HasInMemOUT=@HasInMem OUTPUT
  8530. IF @HasInMem = 1
  8531. BEGIN
  8532. 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)
  8533. EXECUTE sp_executesql @ColumnStoreGetIXSQL, @ColumnStoreGetIXSQL_Param, @dbid_In = @dbid, @objectid_In = @objectid, @indexid_In = @indexid, @partition_nr_In = @partition_nr;
  8534. SELECT @ErrorMessage = ' |-Gathering sys.dm_db_xtp_hash_index_stats and sys.dm_db_xtp_nonclustered_index_stats data in ' + DB_NAME(@dbid) + '...'
  8535. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT;
  8536. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8537. USE [' + DB_NAME(@dbid) + '];
  8538. 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,
  8539. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8540. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8541. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8542. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8543. WHERE si.[object_id] = i.[object_id] AND si.index_id = i.index_id AND ic.is_included_column = 0
  8544. ORDER BY ic.key_ordinal
  8545. FOR XML PATH('''')), 2, 8000) AS KeyCols, NULL, NULL, 0
  8546. FROM sys.dm_db_xtp_hash_index_stats AS xhis
  8547. INNER JOIN sys.dm_db_xtp_index_stats AS xis ON xis.[object_id] = xhis.[object_id] AND xis.[index_id] = xhis.[index_id]
  8548. INNER JOIN sys.indexes AS si (NOLOCK) ON xis.[object_id] = si.[object_id] AND xis.[index_id] = si.[index_id]
  8549. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  8550. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8551. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8552. WHERE o.[type] = ''U'''
  8553. BEGIN TRY
  8554. INSERT INTO #tmpXIS
  8555. EXECUTE sp_executesql @sqlcmd
  8556. END TRY
  8557. BEGIN CATCH
  8558. 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)) + ')'
  8559. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8560. END CATCH
  8561. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8562. USE [' + DB_NAME(@dbid) + '];
  8563. SELECT ' + CONVERT(NVARCHAR(20), @dbid) + ' AS [database_id],
  8564. xis.[object_id], t.name, o.name, xis.index_id, si.name, si.type_desc,
  8565. xnis.delta_pages, xnis.internal_pages, xnis.leaf_pages, xnis.page_update_count,
  8566. xnis.page_update_retry_count, xnis.page_consolidation_count,
  8567. xnis.page_consolidation_retry_count, xnis.page_split_count, xnis.page_split_retry_count,
  8568. xnis.key_split_count, xnis.key_split_retry_count, xnis.page_merge_count, xnis.page_merge_retry_count,
  8569. xnis.key_merge_count, xnis.key_merge_retry_count,
  8570. xis.scans_started, xis.scans_retries
  8571. FROM sys.dm_db_xtp_nonclustered_index_stats AS xnis (NOLOCK)
  8572. 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]
  8573. INNER JOIN sys.indexes AS si (NOLOCK) ON xis.[object_id] = si.[object_id] AND xis.[index_id] = si.[index_id]
  8574. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  8575. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  8576. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  8577. WHERE o.[type] = ''U'''
  8578. BEGIN TRY
  8579. INSERT INTO #tmpXNCIS
  8580. EXECUTE sp_executesql @sqlcmd
  8581. END TRY
  8582. BEGIN CATCH
  8583. 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)) + ')'
  8584. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8585. END CATCH
  8586. END;
  8587. /*ELSE
  8588. BEGIN
  8589. SELECT @ErrorMessage = ' |-Skipping ' + DB_NAME(@dbid) + '. No memory optimized filegroup was found...'
  8590. RAISERROR (@ErrorMessage, 10, 1) WITH NOWAIT;
  8591. END;*/
  8592. END;
  8593. UPDATE #tmpdbs0
  8594. SET isdone = 1
  8595. WHERE [dbid] = @dbid;
  8596. END
  8597. END;
  8598. IF EXISTS (SELECT TOP 1 database_id FROM #tmpXIS WHERE isdone = 0)
  8599. BEGIN
  8600. RAISERROR (' |-Gathering additional data on xtp hash indexes...', 10, 1) WITH NOWAIT;
  8601. WHILE (SELECT COUNT(database_id) FROM #tmpXIS WHERE isdone = 0) > 0
  8602. BEGIN
  8603. 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
  8604. 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;'
  8605. SET @params = N'@distinctCntOUT bigint OUTPUT, @OptimBucketCntOUT bigint OUTPUT';
  8606. EXECUTE sp_executesql @sqlcmd, @params, @distinctCntOUT=@distinctCnt OUTPUT, @OptimBucketCntOUT=@OptimBucketCnt OUTPUT;
  8607. UPDATE #tmpXIS
  8608. SET DistinctCnt = @distinctCnt, OptimBucketCnt = @OptimBucketCnt, isdone = 1
  8609. WHERE database_id = @dbid AND [object_id] = @objectid AND [index_id] = @indexid;
  8610. END;
  8611. END;
  8612. IF (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND [type] <= 2) > 0
  8613. BEGIN
  8614. RAISERROR (' |-Gathering sys.dm_db_index_physical_stats data...', 10, 1) WITH NOWAIT;
  8615. WHILE (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND [type] <= 2) > 0
  8616. BEGIN
  8617. SELECT TOP 1 @dbid = database_id, @objectid = [object_id], @indexid = index_id, @partition_nr = partition_number
  8618. FROM #tblWorking WHERE is_done = 0 AND [type] <= 2
  8619. INSERT INTO #tmpIPS
  8620. SELECT ps.database_id, ps.[object_id], ps.index_id, ps.partition_number, SUM(ps.avg_fragmentation_in_percent), SUM(ps.page_count),
  8621. CAST((SUM(ps.page_count)*8)/1024 AS DECIMAL(26,3)) AS [size_MB], ps.record_count, ps.forwarded_record_count -- for heaps
  8622. FROM sys.dm_db_index_physical_stats(@dbid, @objectid, @indexid , @partition_nr, @ixfragscanmode) AS ps
  8623. WHERE /*ps.index_id > 0 -- ignore heaps
  8624. AND */ps.index_level = 0 -- leaf-level nodes only
  8625. AND ps.alloc_unit_type_desc = 'IN_ROW_DATA'
  8626. GROUP BY ps.database_id, ps.[object_id], ps.index_id, ps.partition_number, ps.record_count, ps.forwarded_record_count
  8627. OPTION (MAXDOP 2);
  8628. UPDATE #tblWorking
  8629. SET is_done = 1
  8630. WHERE database_id = @dbid AND [object_id] = @objectid AND index_id = @indexid AND partition_number = @partition_nr
  8631. END
  8632. END;
  8633. IF (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND type = 5) > 0
  8634. BEGIN
  8635. RAISERROR (' |-Gathering sys.column_store_row_groups data...', 10, 1) WITH NOWAIT;
  8636. WHILE (SELECT COUNT(*) FROM #tblWorking WHERE is_done = 0 AND type IN (5,6)) > 0
  8637. BEGIN
  8638. SELECT TOP 1 @dbid = database_id, @objectid = [object_id], @indexid = index_id, @partition_nr = partition_number
  8639. FROM #tblWorking WHERE is_done = 0 AND type IN (5,6)
  8640. BEGIN TRY
  8641. 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
  8642. FROM [' + DB_NAME(@dbid) + '].sys.column_store_row_groups rg
  8643. WHERE rg.object_id = @objectid_In
  8644. AND rg.index_id = @indexid_In
  8645. AND rg.partition_number = @partition_nr_In
  8646. --AND rg.state = 3 -- Only COMPRESSED row groups
  8647. 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
  8648. OPTION (MAXDOP 2)'
  8649. SET @ColumnStoreGetIXSQL_Param = N'@dbid_In int, @objectid_In int, @indexid_In int, @partition_nr_In int';
  8650. 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)
  8651. EXECUTE sp_executesql @ColumnStoreGetIXSQL, @ColumnStoreGetIXSQL_Param, @dbid_In = @dbid, @objectid_In = @objectid, @indexid_In = @indexid, @partition_nr_In = @partition_nr;
  8652. END TRY
  8653. BEGIN CATCH
  8654. 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)) + ')'
  8655. RAISERROR(@ErrorMessage, 0, 42) WITH NOWAIT;
  8656. END CATCH
  8657. UPDATE #tblWorking
  8658. SET is_done = 1
  8659. WHERE database_id = @dbid AND [object_id] = @objectid AND index_id = @indexid AND partition_number = @partition_nr
  8660. END
  8661. END;
  8662. -- Check for index fragmentation over 5 pct when index has more than 1 extent allocated, or in CCI, all compressed row groups
  8663. IF (SELECT COUNT(*) FROM #tmpIPS WHERE fragmentation > 5 AND [page_count] > 8) > 0
  8664. OR (SELECT COUNT(*) FROM #tmpIPS_CI WHERE fragmentation > 5 AND [state] = 3) > 0
  8665. BEGIN
  8666. 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]
  8667. 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,
  8668. ips.page_count, ips.[size_MB], ips.record_count, ips.forwarded_record_count, -- for heaps
  8669. NULL AS row_group_id, NULL AS [Comment]
  8670. FROM #tmpIPS ips
  8671. 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
  8672. WHERE ips.fragmentation > 5 AND ips.[page_count] > 8
  8673. UNION ALL
  8674. 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,
  8675. ipsci.page_count, ipsci.[size_MB], ipsci.record_count, NULL AS forwarded_record_count, ipsci.row_group_id,
  8676. '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]
  8677. FROM #tmpIPS_CI ipsci
  8678. 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
  8679. WHERE ipsci.fragmentation > 5 AND ipsci.[state] = 3
  8680. ORDER BY fragmentation DESC, [page_count] ASC
  8681. END
  8682. ELSE
  8683. BEGIN
  8684. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Fragmentation' AS [Check], '[OK]' AS [Deviation]
  8685. END;
  8686. IF @sqlmajorver >= 12
  8687. BEGIN
  8688. -- For the below values, your mileage may vary. Assuming more than 50 percent empty buckets and an average chain length over 5 requires investigation
  8689. -- http://blogs.technet.com/b/dataplatforminsider/archive/2014/01/30/in-memory-oltp-index-troubleshooting-part-ii.aspx
  8690. IF (SELECT COUNT(*) FROM #tmpXIS WHERE FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) > 50 AND [avg_chain_length] > 5) > 0
  8691. BEGIN
  8692. 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]
  8693. 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,
  8694. DistinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8695. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8696. FROM #tmpXIS
  8697. WHERE FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) > 50 AND [avg_chain_length] > 5
  8698. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8699. END
  8700. ELSE
  8701. BEGIN
  8702. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_AvgChain_EmptyBuckets' AS [Check], '[OK]' AS [Deviation]
  8703. END;
  8704. IF (SELECT COUNT(*) FROM #tmpXIS WHERE total_bucket_count > DistinctCnt) > 0
  8705. BEGIN
  8706. 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]
  8707. 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,
  8708. DistinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8709. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8710. FROM #tmpXIS
  8711. WHERE total_bucket_count > DistinctCnt
  8712. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8713. END
  8714. ELSE
  8715. BEGIN
  8716. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooManyBuckets' AS [Check], '[OK]' AS [Deviation]
  8717. END;
  8718. IF (SELECT COUNT(*) FROM #tmpXIS WHERE total_bucket_count < DistinctCnt) > 0
  8719. BEGIN
  8720. 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]
  8721. 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,
  8722. DistinctCnt AS [distinct_keys], OptimBucketCnt AS [optimal_bucket_count], total_bucket_count, empty_bucket_count,
  8723. FLOOR((CAST(empty_bucket_count AS FLOAT)/total_bucket_count) * 100) AS [empty_bucket_pct], avg_chain_length, max_chain_length
  8724. FROM #tmpXIS
  8725. WHERE total_bucket_count < DistinctCnt
  8726. ORDER BY [database_name], [schema_name], table_name, [total_bucket_count] DESC;
  8727. END
  8728. ELSE
  8729. BEGIN
  8730. SELECT 'Index_and_Stats_checks' AS [Category], 'XTP_HashIX_Health_TooFewBuckets' AS [Check], '[OK]' AS [Deviation]
  8731. END;
  8732. -- For the below values, your mileage may vary. Assuming more than 5 percent retries requires investigation .
  8733. -- https://msdn.microsoft.com/en-us/library/dn645468.aspx
  8734. 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
  8735. OR FLOOR((CAST(page_consolidation_retry_count AS FLOAT)/CASE WHEN page_consolidation_count = 0 THEN 1 ELSE page_consolidation_count END) * 100) > 5
  8736. OR FLOOR((CAST(page_split_retry_count AS FLOAT)/CASE WHEN page_split_count = 0 THEN 1 ELSE page_split_count END) * 100) > 5
  8737. OR FLOOR((CAST(key_split_retry_count AS FLOAT)/CASE WHEN key_split_count = 0 THEN 1 ELSE key_split_count END) * 100) > 5
  8738. OR FLOOR((CAST(page_merge_retry_count AS FLOAT)/CASE WHEN page_merge_count = 0 THEN 1 ELSE page_merge_count END) * 100) > 5
  8739. OR FLOOR((CAST(key_merge_retry_count AS FLOAT)/CASE WHEN key_merge_count = 0 THEN 1 ELSE key_merge_count END) * 100) > 5
  8740. ) > 0
  8741. BEGIN
  8742. 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]
  8743. 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,
  8744. delta_pages, internal_pages, leaf_pages,
  8745. 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],
  8746. 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],
  8747. 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],
  8748. 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],
  8749. 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],
  8750. 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]
  8751. FROM #tmpXNCIS
  8752. WHERE FLOOR((CAST(page_update_retry_count AS FLOAT)/CASE WHEN page_update_count = 0 THEN 1 ELSE page_update_count END) * 100) > 5
  8753. OR FLOOR((CAST(page_consolidation_retry_count AS FLOAT)/CASE WHEN page_consolidation_count = 0 THEN 1 ELSE page_consolidation_count END) * 100) > 5
  8754. OR FLOOR((CAST(page_split_retry_count AS FLOAT)/CASE WHEN page_split_count = 0 THEN 1 ELSE page_split_count END) * 100) > 5
  8755. OR FLOOR((CAST(key_split_retry_count AS FLOAT)/CASE WHEN key_split_count = 0 THEN 1 ELSE key_split_count END) * 100) > 5
  8756. OR FLOOR((CAST(page_merge_retry_count AS FLOAT)/CASE WHEN page_merge_count = 0 THEN 1 ELSE page_merge_count END) * 100) > 5
  8757. OR FLOOR((CAST(key_merge_retry_count AS FLOAT)/CASE WHEN key_merge_count = 0 THEN 1 ELSE key_merge_count END) * 100) > 5
  8758. ORDER BY [database_name], [schema_name], table_name, [leaf_pages] DESC;
  8759. END;
  8760. END;
  8761. END
  8762. ELSE
  8763. BEGIN
  8764. RAISERROR(' |- [INFORMATION: "Index Health Analysis" check is disabled]', 10, 1, N'disallow_ixfrag')
  8765. --RETURN
  8766. END;
  8767. --------------------------------------------------------------------------------------------------------------------------------
  8768. -- Duplicate or Redundant indexes subsection (clustered, non-clustered, clustered and non-clustered columnstore indexes only)
  8769. --------------------------------------------------------------------------------------------------------------------------------
  8770. IF @ptochecks = 1
  8771. BEGIN
  8772. RAISERROR (N' |-Starting Duplicate or Redundant indexes', 10, 1) WITH NOWAIT
  8773. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  8774. DROP TABLE #tblIxs1;
  8775. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  8776. CREATE TABLE #tblIxs1 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  8777. [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),
  8778. KeyCols VARCHAR(4000), KeyColsOrdered VARCHAR(4000), IncludedCols VARCHAR(4000) NULL, IncludedColsOrdered VARCHAR(4000) NULL, AllColsOrdered VARCHAR(4000) NULL, [KeyCols_data_length_bytes] int,
  8779. CONSTRAINT PK_Ixs PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]));
  8780. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  8781. DROP TABLE #tblCode;
  8782. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  8783. CREATE TABLE #tblCode ([DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [indexName] VARCHAR(200), type_desc NVARCHAR(60));
  8784. UPDATE #tmpdbs1
  8785. SET isdone = 0;
  8786. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  8787. BEGIN
  8788. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  8789. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  8790. USE ' + QUOTENAME(@dbname) + ';
  8791. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  8792. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, mi.index_id AS indexID,
  8793. mi.[name] AS Index_Name, mi.[type] AS [indexType], mi.is_primary_key, mi.[is_unique_constraint], mi.is_unique, mi.is_disabled,
  8794. mi.fill_factor, mi.is_padded, ' + CASE WHEN @sqlmajorver > 9 THEN 'mi.has_filter, mi.filter_definition,' ELSE 'NULL, NULL,' END + '
  8795. SUBSTRING(( SELECT '','' + ac.name FROM sys.tables AS st
  8796. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8797. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8798. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8799. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  8800. ORDER BY ic.key_ordinal
  8801. FOR XML PATH('''')), 2, 8000) AS KeyCols,
  8802. SUBSTRING(( SELECT '','' + ac.name FROM sys.tables AS st
  8803. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8804. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8805. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8806. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  8807. ORDER BY ac.name
  8808. FOR XML PATH('''')), 2, 8000) AS KeyColsOrdered,
  8809. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8810. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8811. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8812. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8813. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 1
  8814. ORDER BY ic.key_ordinal
  8815. FOR XML PATH('''')), 2, 8000) AS IncludedCols,
  8816. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8817. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8818. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8819. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8820. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 1
  8821. ORDER BY ac.name
  8822. FOR XML PATH('''')), 2, 8000) AS IncludedColsOrdered,
  8823. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  8824. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  8825. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  8826. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  8827. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id
  8828. ORDER BY ac.name
  8829. FOR XML PATH('''')), 2, 8000) AS AllColsOrdered,
  8830. (SELECT SUM(CASE sty.name WHEN ''nvarchar'' THEN sc.max_length/2 ELSE sc.max_length END) FROM sys.indexes AS i
  8831. INNER JOIN sys.tables AS t ON t.[object_id] = i.[object_id]
  8832. INNER JOIN sys.schemas ss ON ss.[schema_id] = t.[schema_id]
  8833. INNER JOIN sys.index_columns AS sic ON sic.object_id = mst.object_id AND sic.index_id = mi.index_id
  8834. INNER JOIN sys.columns AS sc ON sc.object_id = t.object_id AND sc.column_id = sic.column_id
  8835. INNER JOIN sys.types AS sty ON sc.user_type_id = sty.user_type_id
  8836. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND sic.key_ordinal > 0) AS [KeyCols_data_length_bytes]
  8837. FROM sys.indexes AS mi
  8838. INNER JOIN sys.tables AS mst ON mst.[object_id] = mi.[object_id]
  8839. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  8840. WHERE mi.type IN (1,2,5,6) AND mst.is_ms_shipped = 0
  8841. ORDER BY objectName
  8842. OPTION (MAXDOP 2);'
  8843. BEGIN TRY
  8844. INSERT INTO #tblIxs1
  8845. EXECUTE sp_executesql @sqlcmd
  8846. END TRY
  8847. BEGIN CATCH
  8848. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  8849. SELECT @ErrorMessage = 'Duplicate or Redundant indexes subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  8850. RAISERROR (@ErrorMessage, 16, 1);
  8851. END CATCH
  8852. UPDATE #tmpdbs1
  8853. SET isdone = 1
  8854. WHERE [dbid] = @dbid;
  8855. END
  8856. 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]
  8857. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8858. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))) > 0
  8859. BEGIN
  8860. 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]
  8861. 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],
  8862. 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,
  8863. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  8864. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8865. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8866. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8867. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8868. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8869. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8870. 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
  8871. ORDER BY I.DatabaseName, I.[objectName], I.[indexID]
  8872. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes_toDrop' AS [Check], I.[DatabaseName], I.schemaName AS [Schema_Name], I.[objectName] AS [Table_Name],
  8873. I.[indexID], I.[indexName] AS [Index_Name], I.is_primary_key, I.is_unique_constraint, I.is_unique, I.fill_factor, I.is_padded, I.has_filter, I.filter_definition,
  8874. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  8875. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8876. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8877. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8878. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8879. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8880. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8881. AND I.[indexID] NOT IN (
  8882. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8883. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8884. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8885. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8886. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8887. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8888. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8889. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8890. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8891. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8892. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8893. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8894. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8895. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8896. ))
  8897. 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
  8898. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8899. DECLARE @strSQL2 NVARCHAR(4000), @DatabaseName sysname, @indexName sysname
  8900. IF @gen_scripts = 1
  8901. BEGIN
  8902. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  8903. PRINT CHAR(10) + '/*
  8904. 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.
  8905. 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.
  8906. */'
  8907. PRINT CHAR(10) + '--############# Existing Duplicate indexes drop statements #############' + CHAR(10)
  8908. 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) +
  8909. 'DROP INDEX ' + QUOTENAME(I.[indexName]) + ' ON ' + QUOTENAME(I.[schemaName]) + '.' + QUOTENAME(I.[objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  8910. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8911. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8912. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8913. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8914. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8915. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8916. AND I.[indexID] NOT IN (
  8917. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8918. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8919. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8920. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8921. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8922. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8923. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8924. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8925. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8926. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8927. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8928. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8929. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8930. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8931. ))
  8932. GROUP BY I.[databaseID], I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered
  8933. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8934. OPEN Dup_Stats
  8935. FETCH NEXT FROM Dup_Stats INTO @strSQL2
  8936. WHILE (@@FETCH_STATUS = 0)
  8937. BEGIN
  8938. PRINT @strSQL2
  8939. FETCH NEXT FROM Dup_Stats INTO @strSQL2
  8940. END
  8941. CLOSE Dup_Stats
  8942. DEALLOCATE Dup_Stats
  8943. PRINT '--############# Ended Duplicate indexes drop statements #############' + CHAR(10)
  8944. END;
  8945. RAISERROR (N' |-Starting index search in sql modules...', 10, 1) WITH NOWAIT
  8946. DECLARE Dup_HardCoded CURSOR FAST_FORWARD FOR SELECT I.[DatabaseName],I.[indexName]
  8947. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  8948. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  8949. AND I.[KeyCols] = I2.[KeyCols] AND (I.IncludedCols = I2.IncludedCols OR (I.IncludedCols IS NULL AND I2.IncludedCols IS NULL))
  8950. AND ((I.filter_definition = I2.filter_definition) OR (I.filter_definition IS NULL AND I2.filter_definition IS NULL))
  8951. WHERE I.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8952. AND I2.indexType IN (1,2,5,6) -- clustered, non-clustered, clustered and non-clustered columnstore indexes only
  8953. AND I.[indexID] NOT IN (
  8954. SELECT COALESCE((SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8955. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8956. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8957. AND (tI3.is_unique = 1 AND tI3.is_primary_key = 1)
  8958. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8959. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8960. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8961. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8962. AND (tI3.is_unique = 1 OR tI3.is_primary_key = 1)
  8963. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered),
  8964. (SELECT MIN(tI3.[indexID]) FROM #tblIxs1 tI3
  8965. WHERE tI3.[databaseID] = I.[databaseID] AND tI3.[objectID] = I.[objectID]
  8966. AND tI3.[KeyCols] = I.[KeyCols] AND (tI3.IncludedCols = I.IncludedCols OR (tI3.IncludedCols IS NULL AND I.IncludedCols IS NULL))
  8967. GROUP BY tI3.[objectID], tI3.KeyCols, tI3.IncludedCols, tI3.[KeyColsOrdered], tI3.IncludedColsOrdered)
  8968. ))
  8969. GROUP BY I.[databaseID], I.[DatabaseName], I.[schemaName], I.[objectName], I.[indexID], I.[indexName], I.KeyCols, I.IncludedCols, I.[KeyColsOrdered], I.IncludedColsOrdered
  8970. ORDER BY I.DatabaseName, I.[objectName], I.[indexID];
  8971. OPEN Dup_HardCoded
  8972. FETCH NEXT FROM Dup_HardCoded INTO @DatabaseName,@indexName
  8973. WHILE (@@FETCH_STATUS = 0)
  8974. BEGIN
  8975. SET @sqlcmd = 'USE [' + @DatabaseName + '];
  8976. SELECT ''' + @DatabaseName + ''' AS [database], ss.name AS [schemaName], so.name AS [objectName], ''' + @indexName + ''' AS indexName, so.type_desc
  8977. FROM sys.sql_modules sm
  8978. INNER JOIN sys.objects so ON sm.[object_id] = so.[object_id]
  8979. INNER JOIN sys.schemas ss ON ss.[schema_id] = so.[schema_id]
  8980. WHERE sm.[definition] LIKE ''%' + @indexName + '%'''
  8981. INSERT INTO #tblCode
  8982. EXECUTE sp_executesql @sqlcmd
  8983. FETCH NEXT FROM Dup_HardCoded INTO @DatabaseName,@indexName
  8984. END
  8985. CLOSE Dup_HardCoded
  8986. DEALLOCATE Dup_HardCoded
  8987. RAISERROR (N' |-Ended index search in sql modules', 10, 1) WITH NOWAIT
  8988. IF (SELECT COUNT(*) FROM #tblCode) > 0
  8989. BEGIN
  8990. 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]
  8991. SELECT [DatabaseName],[schemaName],[objectName] AS [referedIn_objectName], indexName AS [referenced_indexName], type_desc AS [refered_objectType]
  8992. FROM #tblCode
  8993. ORDER BY [DatabaseName], [objectName]
  8994. END
  8995. ELSE
  8996. BEGIN
  8997. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes_HardCoded' AS [Check], '[OK]' AS [Deviation]
  8998. END
  8999. END
  9000. ELSE
  9001. BEGIN
  9002. SELECT 'Index_and_Stats_checks' AS [Category], 'Duplicate_Indexes' AS [Check], '[OK]' AS [Deviation]
  9003. END;
  9004. 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]
  9005. AND (I.[KeyCols] <> I2.[KeyCols] OR I.IncludedCols <> I2.IncludedCols)
  9006. AND (((I.[KeyColsOrdered] <> I2.[KeyColsOrdered] OR I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9007. 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)
  9008. OR I.[AllColsOrdered] = I2.[AllColsOrdered]))
  9009. OR (I.[KeyColsOrdered] <> I2.[KeyColsOrdered] AND I.IncludedColsOrdered = I2.IncludedColsOrdered)
  9010. OR (I.[KeyColsOrdered] = I2.[KeyColsOrdered] AND I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9011. 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)))
  9012. AND I.indexID NOT IN (SELECT I3.[indexID]
  9013. FROM #tblIxs1 I3 INNER JOIN #tblIxs1 I4
  9014. ON I3.[databaseID] = I4.[databaseID] AND I3.[objectID] = I4.[objectID] AND I3.[indexID] <> I4.[indexID]
  9015. AND I3.[KeyCols] = I4.[KeyCols] AND (I3.IncludedCols = I4.IncludedCols OR (I3.IncludedCols IS NULL AND I4.IncludedCols IS NULL))
  9016. WHERE I3.[databaseID] = I.[databaseID] AND I3.[objectID] = I.[objectID]
  9017. GROUP BY I3.[indexID])
  9018. WHERE I.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9019. AND I2.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9020. AND I.is_unique_constraint = 0 -- no unique constraints
  9021. AND I2.is_unique_constraint = 0 -- no unique constraints
  9022. ) > 0
  9023. BEGIN
  9024. 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]
  9025. 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],
  9026. I.[indexID], I.[indexName] AS [Index_Name], I.is_unique, I.fill_factor, I.is_padded, I.has_filter, I.filter_definition,
  9027. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedColsOrdered IS NULL THEN I.[KeyColsOrdered] ELSE I.[KeyColsOrdered] + ',' + I.IncludedColsOrdered END AS [KeyInclColsOrdered]
  9028. FROM #tblIxs1 I INNER JOIN #tblIxs1 I2
  9029. ON I.[databaseID] = I2.[databaseID] AND I.[objectID] = I2.[objectID] AND I.[indexID] <> I2.[indexID]
  9030. AND (((I.[KeyColsOrdered] <> I2.[KeyColsOrdered] OR I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9031. 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)
  9032. OR I.[AllColsOrdered] = I2.[AllColsOrdered]))
  9033. OR (I.[KeyColsOrdered] <> I2.[KeyColsOrdered] AND I.IncludedColsOrdered = I2.IncludedColsOrdered)
  9034. OR (I.[KeyColsOrdered] = I2.[KeyColsOrdered] AND I.IncludedColsOrdered <> I2.IncludedColsOrdered)
  9035. 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)))
  9036. AND I.indexID NOT IN (SELECT I3.[indexID]
  9037. FROM #tblIxs1 I3 INNER JOIN #tblIxs1 I4
  9038. ON I3.[databaseID] = I4.[databaseID] AND I3.[objectID] = I4.[objectID] AND I3.[indexID] <> I4.[indexID]
  9039. AND I3.[KeyCols] = I4.[KeyCols] AND (I3.IncludedCols = I4.IncludedCols OR (I3.IncludedCols IS NULL AND I4.IncludedCols IS NULL))
  9040. WHERE I3.[databaseID] = I.[databaseID] AND I3.[objectID] = I.[objectID]
  9041. GROUP BY I3.[indexID])
  9042. WHERE I.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9043. AND I2.indexType IN (1,2,5,6) -- 1 = clustered, 2 = non-clustered, 5 = clustered and 7 = non-clustered columnstore indexes only
  9044. AND I.is_unique_constraint = 0 -- no unique constraints
  9045. AND I2.is_unique_constraint = 0 -- no unique constraints
  9046. 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
  9047. ORDER BY I.DatabaseName, I.[objectName], I.[KeyColsOrdered], I.IncludedColsOrdered, I.[indexID]
  9048. END
  9049. ELSE
  9050. BEGIN
  9051. SELECT 'Index_and_Stats_checks' AS [Category], 'Redundant_Indexes' AS [Check], '[OK]' AS [Deviation]
  9052. END;
  9053. END;
  9054. --------------------------------------------------------------------------------------------------------------------------------
  9055. -- Unused and rarely used indexes subsection
  9056. --------------------------------------------------------------------------------------------------------------------------------
  9057. IF @ptochecks = 1
  9058. BEGIN
  9059. RAISERROR (N' |-Starting Unused and rarely used indexes', 10, 1) WITH NOWAIT
  9060. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  9061. DROP TABLE #tblIxs2;
  9062. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  9063. CREATE TABLE #tblIxs2 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  9064. [indexID] int, [indexName] VARCHAR(200), [Hits] bigint NULL, [Reads_Ratio] DECIMAL(5,2), [Writes_Ratio] DECIMAL(5,2),
  9065. user_updates bigint, last_user_seek DATETIME NULL, last_user_scan DATETIME NULL, last_user_lookup DATETIME NULL,
  9066. last_user_update DATETIME NULL, is_unique bit, [type] tinyint, is_primary_key bit, is_unique_constraint bit, is_disabled bit,
  9067. CONSTRAINT PK_Ixs2 PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]))
  9068. UPDATE #tmpdbs1
  9069. SET isdone = 0;
  9070. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9071. BEGIN
  9072. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9073. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9074. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9075. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, si.index_id AS indexID, si.[name] AS Index_Name,
  9076. (s.user_seeks + s.user_scans + s.user_lookups) AS [Hits],
  9077. 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 /
  9078. 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],
  9079. RTRIM(CONVERT(NVARCHAR(10),CAST(CASE WHEN s.user_updates = 0 THEN 0 ELSE CONVERT(REAL, s.user_updates) * 100 /
  9080. 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],
  9081. s.user_updates,
  9082. MAX(s.last_user_seek) AS last_user_seek,
  9083. MAX(s.last_user_scan) AS last_user_scan,
  9084. MAX(s.last_user_lookup) AS last_user_lookup,
  9085. MAX(s.last_user_update) AS last_user_update,
  9086. si.is_unique, si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9087. FROM sys.indexes AS si (NOLOCK)
  9088. INNER JOIN sys.objects AS o (NOLOCK) ON si.[object_id] = o.[object_id]
  9089. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = si.[object_id]
  9090. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9091. INNER JOIN sys.dm_db_index_usage_stats AS s (NOLOCK) ON s.database_id = ' + CONVERT(VARCHAR(8), @dbid) + '
  9092. AND s.object_id = si.object_id AND s.index_id = si.index_id
  9093. WHERE mst.is_ms_shipped = 0
  9094. --AND OBJECTPROPERTY(o.object_id,''IsUserTable'') = 1 -- sys.tables only returns type U
  9095. AND si.type IN (2,6) -- non-clustered and non-clustered columnstore indexes only
  9096. AND si.is_primary_key = 0 -- no primary keys
  9097. AND si.is_unique_constraint = 0 -- no unique constraints
  9098. --AND si.is_unique = 0 -- no alternate keys
  9099. 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,
  9100. si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9101. ORDER BY objectName
  9102. OPTION (MAXDOP 2);'
  9103. BEGIN TRY
  9104. INSERT INTO #tblIxs2
  9105. EXECUTE sp_executesql @sqlcmd
  9106. END TRY
  9107. BEGIN CATCH
  9108. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9109. SELECT @ErrorMessage = 'Unused and rarely used indexes subsection - Error raised in TRY block 1 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9110. RAISERROR (@ErrorMessage, 16, 1);
  9111. END CATCH
  9112. UPDATE #tmpdbs1
  9113. SET isdone = 1
  9114. WHERE [dbid] = @dbid
  9115. END
  9116. UPDATE #tmpdbs1
  9117. SET isdone = 0;
  9118. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9119. BEGIN
  9120. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9121. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9122. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9123. 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,
  9124. si.[name] AS Index_Name, 0, 0, 0, 0, NULL, NULL, NULL, NULL,
  9125. si.is_unique, si.[type], si.is_primary_key, si.is_unique_constraint, si.is_disabled
  9126. FROM sys.indexes AS si (NOLOCK)
  9127. INNER JOIN sys.objects AS so (NOLOCK) ON si.object_id = so.object_id
  9128. INNER JOIN sys.tables AS mst (NOLOCK) ON mst.[object_id] = si.[object_id]
  9129. INNER JOIN sys.schemas AS t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9130. WHERE OBJECTPROPERTY(so.object_id,''IsUserTable'') = 1
  9131. AND mst.is_ms_shipped = 0
  9132. AND si.index_id NOT IN (SELECT s.index_id
  9133. FROM sys.dm_db_index_usage_stats s
  9134. WHERE s.object_id = si.object_id
  9135. AND si.index_id = s.index_id
  9136. AND database_id = ' + CONVERT(VARCHAR(8), @dbid) + ')
  9137. AND si.name IS NOT NULL
  9138. AND si.type IN (2,6) -- non-clustered and non-clustered columnstore indexes only
  9139. AND si.is_primary_key = 0 -- no primary keys
  9140. AND si.is_unique_constraint = 0 -- no unique constraints
  9141. --AND si.is_unique = 0 -- no alternate keys
  9142. '
  9143. BEGIN TRY
  9144. INSERT INTO #tblIxs2
  9145. EXECUTE sp_executesql @sqlcmd
  9146. END TRY
  9147. BEGIN CATCH
  9148. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9149. SELECT @ErrorMessage = 'Unused and rarely used indexes subsection - Error raised in TRY block 2 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9150. RAISERROR (@ErrorMessage, 16, 1);
  9151. END CATCH
  9152. UPDATE #tmpdbs1
  9153. SET isdone = 1
  9154. WHERE [dbid] = @dbid
  9155. END;
  9156. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 /*AND is_disabled = 0*/) > 0
  9157. BEGIN
  9158. 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]
  9159. 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,
  9160. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9161. user_updates, last_user_update
  9162. FROM #tblIxs2
  9163. WHERE [Hits] = 0 AND last_user_update > 0
  9164. UNION ALL
  9165. 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,
  9166. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9167. user_updates, last_user_update
  9168. FROM #tblIxs2
  9169. WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)
  9170. ORDER BY [Information], [Database_Name], [Table_Name], [R/W_Ratio] DESC;
  9171. IF @gen_scripts = 1
  9172. BEGIN
  9173. DECLARE @strSQL3 NVARCHAR(4000)
  9174. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9175. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 AND last_user_update > 0) > 0
  9176. BEGIN
  9177. PRINT CHAR(10) + '--############# Existing unused indexes with updates drop statements #############' + CHAR(10)
  9178. 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) +
  9179. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9180. FROM #tblIxs2
  9181. WHERE [Hits] = 0 AND last_user_update > 0
  9182. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC;
  9183. OPEN Un_Stats
  9184. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9185. WHILE (@@FETCH_STATUS = 0)
  9186. BEGIN
  9187. PRINT @strSQL3
  9188. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9189. END
  9190. CLOSE Un_Stats
  9191. DEALLOCATE Un_Stats
  9192. PRINT CHAR(10) + '--############# Ended unused indexes with updates drop statements #############' + CHAR(10)
  9193. END;
  9194. IF (SELECT COUNT(*) FROM #tblIxs2 WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)) > 0
  9195. BEGIN
  9196. PRINT CHAR(10) + '--############# Existing unused indexes with no updates drop statements #############' + CHAR(10)
  9197. DECLARE Un_Stats CURSOR FAST_FORWARD FOR SELECT 'USE ' + [DatabaseName] + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'''+ [indexName] + ''')' + CHAR(10) +
  9198. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9199. FROM #tblIxs2
  9200. WHERE [Hits] = 0 AND (last_user_update = 0 OR last_user_update IS NULL)
  9201. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC;
  9202. OPEN Un_Stats
  9203. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9204. WHILE (@@FETCH_STATUS = 0)
  9205. BEGIN
  9206. PRINT @strSQL3
  9207. FETCH NEXT FROM Un_Stats INTO @strSQL3
  9208. END
  9209. CLOSE Un_Stats
  9210. DEALLOCATE Un_Stats
  9211. PRINT CHAR(10) + '--############# Ended unused indexes with no updates drop statements #############' + CHAR(10)
  9212. END
  9213. END;
  9214. END
  9215. ELSE
  9216. BEGIN
  9217. SELECT 'Index_and_Stats_checks' AS [Category], 'Unused_Indexes' AS [Check], '[OK]' AS [Deviation]
  9218. END;
  9219. 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
  9220. BEGIN
  9221. 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]
  9222. 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,
  9223. [Hits], CONVERT(NVARCHAR,[Reads_Ratio]) COLLATE database_default + '/' + CONVERT(NVARCHAR,[Writes_Ratio]) COLLATE database_default AS [R/W_Ratio],
  9224. user_updates, last_user_seek, last_user_scan, last_user_lookup, last_user_update
  9225. FROM #tblIxs2
  9226. WHERE [Hits] > 0 AND [Reads_Ratio] < 5
  9227. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC
  9228. IF @gen_scripts = 1
  9229. BEGIN
  9230. DECLARE @strSQL4 NVARCHAR(4000)
  9231. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9232. PRINT CHAR(10) + '--############# Existing rarely used indexes drop statements #############' + CHAR(10)
  9233. 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) +
  9234. 'DROP INDEX ' + QUOTENAME([indexName]) + ' ON ' + QUOTENAME([schemaName]) + '.' + QUOTENAME([objectName]) + ';' + CHAR(10) + 'GO' + CHAR(10)
  9235. FROM #tblIxs2
  9236. WHERE [Hits] > 0 AND [Reads_Ratio] < 5
  9237. ORDER BY [DatabaseName], [objectName], [Reads_Ratio] DESC
  9238. OPEN curRarUsed
  9239. FETCH NEXT FROM curRarUsed INTO @strSQL4
  9240. WHILE (@@FETCH_STATUS = 0)
  9241. BEGIN
  9242. PRINT @strSQL4
  9243. FETCH NEXT FROM curRarUsed INTO @strSQL4
  9244. END
  9245. CLOSE curRarUsed
  9246. DEALLOCATE curRarUsed
  9247. PRINT '--############# Ended rarely used indexes drop statements #############' + CHAR(10)
  9248. END;
  9249. END
  9250. ELSE
  9251. BEGIN
  9252. SELECT 'Index_and_Stats_checks' AS [Category], 'Rarely_Used_Indexes' AS [Check], '[OK]' AS [Deviation]
  9253. END;
  9254. END;
  9255. --------------------------------------------------------------------------------------------------------------------------------
  9256. -- Indexes with large keys (> 900 bytes) subsection
  9257. --------------------------------------------------------------------------------------------------------------------------------
  9258. IF @ptochecks = 1
  9259. BEGIN
  9260. RAISERROR (N' |-Starting Indexes with large keys (> 900 bytes)', 10, 1) WITH NOWAIT
  9261. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [KeyCols_data_length_bytes] > 900) > 0
  9262. BEGIN
  9263. 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]
  9264. 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],
  9265. I.KeyCols, [KeyCols_data_length_bytes]
  9266. FROM #tblIxs1 I
  9267. WHERE [KeyCols_data_length_bytes] > 900
  9268. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9269. END
  9270. ELSE
  9271. BEGIN
  9272. SELECT 'Index_and_Stats_checks' AS [Category], 'Large_Index_Key' AS [Check], '[OK]' AS [Deviation]
  9273. END;
  9274. END;
  9275. --------------------------------------------------------------------------------------------------------------------------------
  9276. -- Indexes with fill factor < 80 pct subsection
  9277. --------------------------------------------------------------------------------------------------------------------------------
  9278. IF @ptochecks = 1
  9279. BEGIN
  9280. RAISERROR (N' |-Starting Indexes with fill factor < 80 pct', 10, 1) WITH NOWAIT
  9281. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [fill_factor] BETWEEN 1 AND 79) > 0
  9282. BEGIN
  9283. 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]
  9284. 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],
  9285. [fill_factor], I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  9286. FROM #tblIxs1 I
  9287. WHERE [fill_factor] BETWEEN 1 AND 79
  9288. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9289. END
  9290. ELSE
  9291. BEGIN
  9292. SELECT 'Index_and_Stats_checks' AS [Category], 'Low_Fill_Factor' AS [Check], '[OK]' AS [Deviation]
  9293. END;
  9294. END;
  9295. --------------------------------------------------------------------------------------------------------------------------------
  9296. -- Disabled indexes subsection
  9297. --------------------------------------------------------------------------------------------------------------------------------
  9298. IF @ptochecks = 1
  9299. BEGIN
  9300. RAISERROR (N' |-Starting Disabled indexes', 10, 1) WITH NOWAIT
  9301. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [is_disabled] = 1) > 0
  9302. BEGIN
  9303. SELECT 'Index_and_Stats_checks' AS [Category], 'Disabled_IXs' AS [Check], '[WARNING: Some indexes are disabled. Revise the need to maintain these]' AS [Deviation]
  9304. 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],
  9305. CASE WHEN [indexType] = 1 THEN 'Clustered'
  9306. WHEN [indexType] = 2 THEN 'Non-clustered'
  9307. WHEN [indexType] = 3 THEN 'Clustered columnstore'
  9308. ELSE 'Non-clustered columnstore' END AS [Index_Type],
  9309. I.KeyCols, I.IncludedCols, CASE WHEN I.IncludedCols IS NULL THEN I.[KeyCols] ELSE I.[KeyCols] + ',' + I.IncludedCols END AS [AllColsOrdered]
  9310. FROM #tblIxs1 I
  9311. WHERE [is_disabled] = 1
  9312. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9313. END
  9314. ELSE
  9315. BEGIN
  9316. SELECT 'Index_and_Stats_checks' AS [Category], 'Disabled_IXs' AS [Check], '[OK]' AS [Deviation]
  9317. END;
  9318. END;
  9319. --------------------------------------------------------------------------------------------------------------------------------
  9320. -- Non-unique clustered indexes subsection
  9321. --------------------------------------------------------------------------------------------------------------------------------
  9322. IF @ptochecks = 1
  9323. BEGIN
  9324. RAISERROR (N' |-Starting Non-unique clustered indexes', 10, 1) WITH NOWAIT
  9325. IF (SELECT COUNT(*) FROM #tblIxs1 WHERE [is_unique] = 0 AND indexID = 1) > 0
  9326. BEGIN
  9327. 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]
  9328. 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]
  9329. FROM #tblIxs1 I
  9330. WHERE [is_unique] = 0 AND indexID = 1
  9331. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName]
  9332. END
  9333. ELSE
  9334. BEGIN
  9335. SELECT 'Index_and_Stats_checks' AS [Category], 'NonUnique_CIXs' AS [Check], '[OK]' AS [Deviation]
  9336. END;
  9337. END;
  9338. --------------------------------------------------------------------------------------------------------------------------------
  9339. -- Clustered Indexes with GUIDs in key subsection
  9340. --------------------------------------------------------------------------------------------------------------------------------
  9341. IF @ptochecks = 1
  9342. BEGIN
  9343. RAISERROR (N' |-Starting Clustered Indexes with GUIDs in key', 10, 1) WITH NOWAIT
  9344. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  9345. DROP TABLE #tblIxs6;
  9346. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  9347. CREATE TABLE #tblIxs6 ([databaseID] int, [DatabaseName] sysname, [objectID] int, [schemaName] VARCHAR(100), [objectName] VARCHAR(200),
  9348. [indexID] int, [indexName] VARCHAR(200), [indexType] tinyint, [is_unique_constraint] bit, is_unique bit, is_disabled bit, fill_factor tinyint, is_padded bit,
  9349. KeyCols VARCHAR(4000), KeyColsOrdered VARCHAR(4000), Key_has_GUID int,
  9350. CONSTRAINT PK_Ixs3 PRIMARY KEY CLUSTERED(databaseID, [objectID], [indexID]));
  9351. UPDATE #tmpdbs1
  9352. SET isdone = 0;
  9353. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9354. BEGIN
  9355. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9356. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  9357. USE ' + QUOTENAME(@dbname) + ';
  9358. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name,
  9359. mst.[object_id] AS objectID, t.name AS schemaName, mst.[name] AS objectName, mi.index_id AS indexID,
  9360. mi.[name] AS Index_Name, mi.[type] AS [indexType], mi.[is_unique_constraint], mi.is_unique, mi.is_disabled,
  9361. mi.fill_factor, mi.is_padded,
  9362. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  9363. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  9364. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  9365. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9366. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  9367. ORDER BY ic.key_ordinal
  9368. FOR XML PATH('''')), 2, 8000) AS KeyCols,
  9369. SUBSTRING((SELECT '','' + ac.name FROM sys.tables AS st
  9370. INNER JOIN sys.indexes AS i ON st.[object_id] = i.[object_id]
  9371. INNER JOIN sys.index_columns AS ic ON i.[object_id] = ic.[object_id] AND i.[index_id] = ic.[index_id]
  9372. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9373. WHERE mi.[object_id] = i.[object_id] AND mi.index_id = i.index_id AND ic.is_included_column = 0
  9374. ORDER BY ac.name
  9375. FOR XML PATH('''')), 2, 8000) AS KeyColsOrdered,
  9376. (SELECT COUNT(sty.name) FROM sys.indexes AS i
  9377. INNER JOIN sys.tables AS t ON t.[object_id] = i.[object_id]
  9378. INNER JOIN sys.schemas ss ON ss.[schema_id] = t.[schema_id]
  9379. INNER JOIN sys.index_columns AS sic ON sic.object_id = mst.object_id AND sic.index_id = mi.index_id
  9380. INNER JOIN sys.columns AS sc ON sc.object_id = t.object_id AND sc.column_id = sic.column_id
  9381. INNER JOIN sys.types AS sty ON sc.user_type_id = sty.user_type_id
  9382. 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]
  9383. FROM sys.indexes AS mi
  9384. INNER JOIN sys.tables AS mst ON mst.[object_id] = mi.[object_id]
  9385. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  9386. WHERE mi.type = 1 AND mi.is_unique_constraint = 0
  9387. AND mst.is_ms_shipped = 0
  9388. --AND OBJECTPROPERTY(o.object_id,''IsUserTable'') = 1 -- sys.tables only returns type U
  9389. ORDER BY objectName
  9390. OPTION (MAXDOP 2);'
  9391. BEGIN TRY
  9392. INSERT INTO #tblIxs6
  9393. EXECUTE sp_executesql @sqlcmd
  9394. END TRY
  9395. BEGIN CATCH
  9396. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9397. SELECT @ErrorMessage = 'Clustered Indexes with GUIDs in key subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9398. RAISERROR (@ErrorMessage, 16, 1);
  9399. END CATCH
  9400. UPDATE #tmpdbs1
  9401. SET isdone = 1
  9402. WHERE [dbid] = @dbid
  9403. END;
  9404. IF (SELECT COUNT(*) FROM #tblIxs6 WHERE [Key_has_GUID] > 0) > 0
  9405. BEGIN
  9406. 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]
  9407. 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
  9408. FROM #tblIxs6 I
  9409. WHERE [Key_has_GUID] > 0
  9410. ORDER BY I.[DatabaseName], I.schemaName, I.[objectName], I.[indexID]
  9411. END
  9412. ELSE
  9413. BEGIN
  9414. SELECT 'Index_and_Stats_checks' AS [Category], 'Index_Key_GUID' AS [Check], '[OK]' AS [Deviation]
  9415. END
  9416. END;
  9417. --------------------------------------------------------------------------------------------------------------------------------
  9418. -- Foreign Keys with no Index subsection
  9419. --------------------------------------------------------------------------------------------------------------------------------
  9420. IF @ptochecks = 1
  9421. BEGIN
  9422. RAISERROR (N' |-Starting Foreign Keys with no Index', 10, 1) WITH NOWAIT
  9423. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  9424. DROP TABLE #tblFK;
  9425. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  9426. CREATE TABLE #tblFK ([databaseID] int, [DatabaseName] sysname, [constraint_name] VARCHAR(200), [parent_schema_name] VARCHAR(100),
  9427. [parent_table_name] VARCHAR(200), parent_columns VARCHAR(4000), [referenced_schema] VARCHAR(100), [referenced_table_name] VARCHAR(200), referenced_columns VARCHAR(4000),
  9428. CONSTRAINT PK_FK PRIMARY KEY CLUSTERED(databaseID, [constraint_name]))
  9429. UPDATE #tmpdbs1
  9430. SET isdone = 0
  9431. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9432. BEGIN
  9433. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9434. SET @sqlcmd = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  9435. USE ' + QUOTENAME(@dbname) + '
  9436. ;WITH cteFK AS (
  9437. SELECT t.name AS [parent_schema_name],
  9438. OBJECT_NAME(FKC.parent_object_id) [parent_table_name],
  9439. OBJECT_NAME(constraint_object_id) AS [constraint_name],
  9440. t2.name AS [referenced_schema],
  9441. OBJECT_NAME(referenced_object_id) AS [referenced_table_name],
  9442. SUBSTRING((SELECT '','' + RTRIM(COL_NAME(k.parent_object_id,parent_column_id)) AS [data()]
  9443. FROM sys.foreign_key_columns k (NOLOCK)
  9444. INNER JOIN sys.foreign_keys (NOLOCK) ON k.constraint_object_id = [object_id]
  9445. AND k.constraint_object_id = FKC.constraint_object_id
  9446. ORDER BY constraint_column_id
  9447. FOR XML PATH('''')), 2, 8000) AS [parent_columns],
  9448. SUBSTRING((SELECT '','' + RTRIM(COL_NAME(k.referenced_object_id,referenced_column_id)) AS [data()]
  9449. FROM sys.foreign_key_columns k (NOLOCK)
  9450. INNER JOIN sys.foreign_keys (NOLOCK) ON k.constraint_object_id = [object_id]
  9451. AND k.constraint_object_id = FKC.constraint_object_id
  9452. ORDER BY constraint_column_id
  9453. FOR XML PATH('''')), 2, 8000) AS [referenced_columns]
  9454. FROM sys.foreign_key_columns FKC (NOLOCK)
  9455. INNER JOIN sys.objects o (NOLOCK) ON FKC.parent_object_id = o.[object_id]
  9456. INNER JOIN sys.tables mst (NOLOCK) ON mst.[object_id] = o.[object_id]
  9457. INNER JOIN sys.schemas t (NOLOCK) ON t.[schema_id] = mst.[schema_id]
  9458. INNER JOIN sys.objects so (NOLOCK) ON FKC.referenced_object_id = so.[object_id]
  9459. INNER JOIN sys.tables AS mst2 (NOLOCK) ON mst2.[object_id] = so.[object_id]
  9460. INNER JOIN sys.schemas AS t2 (NOLOCK) ON t2.[schema_id] = mst2.[schema_id]
  9461. WHERE o.type = ''U'' AND so.type = ''U''
  9462. GROUP BY o.[schema_id],so.[schema_id],FKC.parent_object_id,constraint_object_id,referenced_object_id,t.name,t2.name
  9463. ),
  9464. cteIndexCols AS (
  9465. SELECT t.name AS schemaName,
  9466. OBJECT_NAME(mst.[object_id]) AS objectName,
  9467. SUBSTRING(( SELECT '','' + RTRIM(ac.name) FROM sys.tables AS st
  9468. INNER JOIN sys.indexes AS mi ON st.[object_id] = mi.[object_id]
  9469. INNER JOIN sys.index_columns AS ic ON mi.[object_id] = ic.[object_id] AND mi.[index_id] = ic.[index_id]
  9470. INNER JOIN sys.all_columns AS ac ON st.[object_id] = ac.[object_id] AND ic.[column_id] = ac.[column_id]
  9471. WHERE i.[object_id] = mi.[object_id] AND i.index_id = mi.index_id AND ic.is_included_column = 0
  9472. ORDER BY ac.column_id
  9473. FOR XML PATH('''')), 2, 8000) AS KeyCols
  9474. FROM sys.indexes AS i
  9475. INNER JOIN sys.tables AS mst ON mst.[object_id] = i.[object_id]
  9476. INNER JOIN sys.schemas AS t ON t.[schema_id] = mst.[schema_id]
  9477. WHERE i.[type] IN (1,2,5,6) AND i.is_unique_constraint = 0
  9478. AND mst.is_ms_shipped = 0
  9479. )
  9480. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ' AS Database_ID, ''' + @dbname + ''' AS Database_Name, fk.constraint_name AS constraintName,
  9481. fk.parent_schema_name AS schemaName, fk.parent_table_name AS tableName,
  9482. REPLACE(fk.parent_columns,'' ,'','','') AS parentColumns, fk.referenced_schema AS referencedSchemaName,
  9483. fk.referenced_table_name AS referencedTableName, REPLACE(fk.referenced_columns,'' ,'','','') AS referencedColumns
  9484. FROM cteFK fk
  9485. WHERE NOT EXISTS (SELECT 1 FROM cteIndexCols ict
  9486. WHERE fk.parent_schema_name = ict.schemaName
  9487. AND fk.parent_table_name = ict.objectName
  9488. AND REPLACE(fk.parent_columns,'' ,'','','') = ict.KeyCols);'
  9489. BEGIN TRY
  9490. INSERT INTO #tblFK
  9491. EXECUTE sp_executesql @sqlcmd
  9492. END TRY
  9493. BEGIN CATCH
  9494. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9495. SELECT @ErrorMessage = 'Foreign Keys with no Index subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9496. RAISERROR (@ErrorMessage, 16, 1);
  9497. END CATCH
  9498. UPDATE #tmpdbs1
  9499. SET isdone = 1
  9500. WHERE [dbid] = @dbid
  9501. END;
  9502. IF (SELECT COUNT(*) FROM #tblFK) > 0
  9503. BEGIN
  9504. 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]
  9505. SELECT 'Index_and_Stats_checks' AS [Category], 'FK_no_Index' AS [Information], FK.[DatabaseName] AS [Database_Name], constraint_name AS [Constraint_Name],
  9506. FK.parent_schema_name AS [Schema_Name], FK.parent_table_name AS [Table_Name],
  9507. FK.parent_columns AS parentColumns, FK.referenced_schema AS Referenced_Schema_Name,
  9508. FK.referenced_table_name AS Referenced_Table_Name, FK.referenced_columns AS referencedColumns
  9509. FROM #tblFK FK
  9510. ORDER BY [DatabaseName], parent_schema_name, parent_table_name, referenced_schema, referenced_table_name
  9511. IF @gen_scripts = 1
  9512. BEGIN
  9513. DECLARE @strSQL5 NVARCHAR(4000)
  9514. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */'
  9515. PRINT CHAR(10) + '--############# FK index creation statements #############' + CHAR(10)
  9516. DECLARE curFKs CURSOR FAST_FORWARD FOR SELECT 'USE ' + [DatabaseName] + CHAR(10) + 'GO' + CHAR(10) +
  9517. 'CREATE INDEX IX_' + REPLACE(constraint_name,' ','_') + ' ON ' + QUOTENAME(parent_schema_name) + '.' + QUOTENAME(parent_table_name) + ' ([' + REPLACE(REPLACE(parent_columns,',','],['),']]',']') + ']);' + CHAR(10) + 'GO' + CHAR(10)
  9518. FROM #tblFK
  9519. ORDER BY [DatabaseName], parent_schema_name, parent_table_name, referenced_schema, referenced_table_name
  9520. OPEN curFKs
  9521. FETCH NEXT FROM curFKs INTO @strSQL5
  9522. WHILE (@@FETCH_STATUS = 0)
  9523. BEGIN
  9524. PRINT @strSQL5
  9525. FETCH NEXT FROM curFKs INTO @strSQL5
  9526. END
  9527. CLOSE curFKs
  9528. DEALLOCATE curFKs
  9529. PRINT '--############# Ended FK index creation statements #############' + CHAR(10)
  9530. END;
  9531. END
  9532. ELSE
  9533. BEGIN
  9534. SELECT 'Index_and_Stats_checks' AS [Category], 'FK_no_Index' AS [Check], '[OK]' AS [Deviation]
  9535. END;
  9536. END;
  9537. --------------------------------------------------------------------------------------------------------------------------------
  9538. -- Indexing per Table subsection
  9539. --------------------------------------------------------------------------------------------------------------------------------
  9540. IF @ptochecks = 1
  9541. BEGIN
  9542. RAISERROR (N' |-Starting Indexing per Table', 10, 1) WITH NOWAIT
  9543. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  9544. DROP TABLE #tblIxs3;
  9545. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  9546. CREATE TABLE #tblIxs3 ([Operation] tinyint, [databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200))
  9547. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  9548. DROP TABLE #tblIxs4;
  9549. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  9550. CREATE TABLE #tblIxs4 ([databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [CntCols] int, [CntIxs] int)
  9551. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  9552. DROP TABLE #tblIxs5;
  9553. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  9554. CREATE TABLE #tblIxs5 ([databaseID] int, [DatabaseName] sysname, [schemaName] VARCHAR(100), [objectName] VARCHAR(200), [indexName] VARCHAR(200), [indexLocation] VARCHAR(200))
  9555. UPDATE #tmpdbs1
  9556. SET isdone = 0
  9557. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9558. BEGIN
  9559. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9560. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9561. SELECT 1 AS [Check], ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name
  9562. FROM sys.indexes AS si (NOLOCK)
  9563. INNER JOIN sys.tables AS t (NOLOCK) ON si.[object_id] = t.[object_id]
  9564. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9565. WHERE si.is_hypothetical = 0
  9566. GROUP BY si.[object_id], t.name, s.name
  9567. HAVING COUNT(index_id) = 1 AND MAX(index_id) = 0
  9568. UNION ALL
  9569. SELECT 2 AS [Check], ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name
  9570. FROM sys.indexes AS si (NOLOCK)
  9571. INNER JOIN sys.tables AS t (NOLOCK) ON si.[object_id] = t.[object_id]
  9572. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9573. WHERE si.is_hypothetical = 0
  9574. GROUP BY t.name, s.name
  9575. HAVING COUNT(index_id) > 1 AND MIN(index_id) = 0;'
  9576. BEGIN TRY
  9577. INSERT INTO #tblIxs3
  9578. EXECUTE sp_executesql @sqlcmd
  9579. END TRY
  9580. BEGIN CATCH
  9581. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9582. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 1 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9583. RAISERROR (@ErrorMessage, 16, 1);
  9584. END CATCH
  9585. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9586. SELECT ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name, COUNT(c.column_id),
  9587. (SELECT COUNT(si.index_id) FROM sys.tables AS t2 INNER JOIN sys.indexes AS si ON si.[object_id] = t2.[object_id]
  9588. WHERE si.index_id > 0 AND si.[object_id] = t.[object_id] AND si.is_hypothetical = 0
  9589. GROUP BY si.[object_id])
  9590. FROM sys.tables AS t (NOLOCK)
  9591. INNER JOIN sys.columns AS c (NOLOCK) ON t.[object_id] = c.[object_id]
  9592. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9593. GROUP BY s.name, t.name, t.[object_id];'
  9594. BEGIN TRY
  9595. INSERT INTO #tblIxs4
  9596. EXECUTE sp_executesql @sqlcmd
  9597. END TRY
  9598. BEGIN CATCH
  9599. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9600. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 2 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9601. RAISERROR (@ErrorMessage, 16, 1);
  9602. END CATCH
  9603. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9604. SELECT DISTINCT ' + CONVERT(VARCHAR(8), @dbid) + ', ''' + @dbname + ''', s.name, t.name, i.name, ds.name
  9605. FROM sys.tables AS t (NOLOCK)
  9606. INNER JOIN sys.indexes AS i (NOLOCK) ON t.[object_id] = i.[object_id]
  9607. INNER JOIN sys.data_spaces AS ds (NOLOCK) ON ds.data_space_id = i.data_space_id
  9608. INNER JOIN sys.schemas AS s (NOLOCK) ON s.[schema_id] = t.[schema_id]
  9609. WHERE t.[type] = ''U''
  9610. AND i.[type] IN (1,2)
  9611. AND i.is_hypothetical = 0
  9612. -- Get partitioned tables
  9613. AND t.name IN (SELECT ob.name
  9614. FROM sys.tables AS ob (NOLOCK)
  9615. INNER JOIN sys.indexes AS ind (NOLOCK) ON ind.[object_id] = ob.[object_id]
  9616. INNER JOIN sys.data_spaces AS sds (NOLOCK) ON sds.data_space_id = ind.data_space_id
  9617. WHERE sds.[type] = ''PS''
  9618. GROUP BY ob.name)
  9619. AND ds.[type] <> ''PS'';'
  9620. BEGIN TRY
  9621. INSERT INTO #tblIxs5
  9622. EXECUTE sp_executesql @sqlcmd
  9623. END TRY
  9624. BEGIN CATCH
  9625. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9626. SELECT @ErrorMessage = 'Indexing per Table subsection - Error raised in TRY block 3 in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9627. RAISERROR (@ErrorMessage, 16, 1);
  9628. END CATCH
  9629. UPDATE #tmpdbs1
  9630. SET isdone = 1
  9631. WHERE [dbid] = @dbid
  9632. END;
  9633. IF (SELECT COUNT(*) FROM #tblIxs3 WHERE [Operation] = 1) > 0
  9634. BEGIN
  9635. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_Indexes' AS [Check], '[WARNING: Some tables do not have indexes]' AS [Deviation]
  9636. 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
  9637. END
  9638. ELSE
  9639. BEGIN
  9640. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_Indexes' AS [Check], '[OK]' AS [Deviation]
  9641. END;
  9642. IF (SELECT COUNT(*) FROM #tblIxs3 WHERE [Operation] = 2) > 0
  9643. BEGIN
  9644. 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]
  9645. 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
  9646. END
  9647. ELSE
  9648. BEGIN
  9649. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_no_CL_Index' AS [Check], '[OK]' AS [Deviation]
  9650. END;
  9651. IF (SELECT COUNT(*) FROM #tblIxs4 WHERE [CntCols] < [CntIxs]) > 0
  9652. BEGIN
  9653. 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]
  9654. 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]
  9655. END
  9656. ELSE
  9657. BEGIN
  9658. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_more_Indexes_than_Cols' AS [Check], '[OK]' AS [Deviation]
  9659. END;
  9660. IF (SELECT COUNT(*) FROM #tblIxs5) > 0
  9661. BEGIN
  9662. 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]
  9663. 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
  9664. END
  9665. ELSE
  9666. BEGIN
  9667. SELECT 'Index_and_Stats_checks' AS [Category], 'Tables_with_partition_misaligned_Indexes' AS [Check], '[OK]' AS [Deviation]
  9668. END;
  9669. END;
  9670. --------------------------------------------------------------------------------------------------------------------------------
  9671. -- Missing Indexes subsection
  9672. -- Outputs only potentially most relevant, based in scoring method - use at you own discretion)
  9673. --------------------------------------------------------------------------------------------------------------------------------
  9674. IF @ptochecks = 1
  9675. BEGIN
  9676. RAISERROR (N' |-Starting Missing Indexes', 10, 1) WITH NOWAIT
  9677. DECLARE @IC VARCHAR(4000), @ICWI VARCHAR(4000), @editionCheck bit
  9678. /* Refer to http://msdn.microsoft.com/en-us/library/ms174396.aspx */
  9679. IF (SELECT SERVERPROPERTY('EditionID')) IN (1804890536, 1872460670, 610778273, -2117995310)
  9680. SET @editionCheck = 1 -- supports enterprise only features
  9681. ELSE
  9682. SET @editionCheck = 0; -- does not support enterprise only features
  9683. -- Create the helper functions
  9684. 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')
  9685. EXEC ('USE tempdb; EXEC(''
  9686. CREATE FUNCTION dbo.fn_createindex_allcols (@ix_handle int)
  9687. RETURNS NVARCHAR(max)
  9688. AS
  9689. BEGIN
  9690. DECLARE @ReturnCols NVARCHAR(max)
  9691. ;WITH ColumnToPivot ([data()]) AS (
  9692. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9693. FROM sys.dm_db_missing_index_details id
  9694. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9695. WHERE id.index_handle = @ix_handle
  9696. ORDER BY ic.column_id ASC
  9697. FOR XML PATH(''''''''), TYPE
  9698. ),
  9699. XmlRawData (CSVString) AS (
  9700. SELECT (SELECT [data()] AS InputData
  9701. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9702. )
  9703. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9704. FROM XmlRawData
  9705. RETURN (@ReturnCols)
  9706. END'')
  9707. ')
  9708. 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')
  9709. EXEC ('USE tempdb; EXEC(''
  9710. CREATE FUNCTION dbo.fn_createindex_keycols (@ix_handle int)
  9711. RETURNS NVARCHAR(max)
  9712. AS
  9713. BEGIN
  9714. DECLARE @ReturnCols NVARCHAR(max)
  9715. ;WITH ColumnToPivot ([data()]) AS (
  9716. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9717. FROM sys.dm_db_missing_index_details id
  9718. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9719. WHERE id.index_handle = @ix_handle
  9720. AND (ic.column_usage = ''''EQUALITY'''' OR ic.column_usage = ''''INEQUALITY'''')
  9721. ORDER BY ic.column_id ASC
  9722. FOR XML PATH(''''''''), TYPE
  9723. ),
  9724. XmlRawData (CSVString) AS (
  9725. SELECT (SELECT [data()] AS InputData
  9726. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9727. )
  9728. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9729. FROM XmlRawData
  9730. RETURN (@ReturnCols)
  9731. END'')
  9732. ')
  9733. 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')
  9734. EXEC ('USE tempdb; EXEC(''
  9735. CREATE FUNCTION dbo.fn_createindex_includecols (@ix_handle int)
  9736. RETURNS NVARCHAR(max)
  9737. AS
  9738. BEGIN
  9739. DECLARE @ReturnCols NVARCHAR(max)
  9740. ;WITH ColumnToPivot ([data()]) AS (
  9741. SELECT CONVERT(VARCHAR(3),ic.column_id) + N'''',''''
  9742. FROM sys.dm_db_missing_index_details id
  9743. CROSS APPLY sys.dm_db_missing_index_columns(id.index_handle) ic
  9744. WHERE id.index_handle = @ix_handle
  9745. AND ic.column_usage = ''''INCLUDE''''
  9746. ORDER BY ic.column_id ASC
  9747. FOR XML PATH(''''''''), TYPE
  9748. ),
  9749. XmlRawData (CSVString) AS (
  9750. SELECT (SELECT [data()] AS InputData
  9751. FROM ColumnToPivot AS d FOR XML RAW, TYPE).value(''''/row[1]/InputData[1]'''', ''''NVARCHAR(max)'''') AS CSVCol
  9752. )
  9753. SELECT @ReturnCols = CASE WHEN LEN(CSVString) <= 1 THEN NULL ELSE LEFT(CSVString, LEN(CSVString)-1) END
  9754. FROM XmlRawData
  9755. RETURN (@ReturnCols)
  9756. END'')
  9757. ')
  9758. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  9759. DROP TABLE #IndexCreation;
  9760. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  9761. CREATE TABLE #IndexCreation (
  9762. [database_id] int,
  9763. DBName VARCHAR(255),
  9764. [Table] VARCHAR(255),
  9765. [ix_handle] int,
  9766. [User_Hits_on_Missing_Index] int,
  9767. [Estimated_Improvement_Percent] DECIMAL(5,2),
  9768. [Avg_Total_User_Cost] int,
  9769. [Unique_Compiles] int,
  9770. [Score] NUMERIC(19,3),
  9771. [KeyCols] VARCHAR(1000),
  9772. [IncludedCols] VARCHAR(4000),
  9773. [Ix_Name] VARCHAR(255),
  9774. [AllCols] NVARCHAR(max),
  9775. [KeyColsOrdered] NVARCHAR(max),
  9776. [IncludedColsOrdered] NVARCHAR(max)
  9777. )
  9778. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  9779. DROP TABLE #IndexRedundant;
  9780. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  9781. CREATE TABLE #IndexRedundant (
  9782. DBName VARCHAR(255),
  9783. [Table] VARCHAR(255),
  9784. [Ix_Name] VARCHAR(255),
  9785. [ix_handle] int,
  9786. [KeyCols] VARCHAR(1000),
  9787. [IncludedCols] VARCHAR(4000),
  9788. [Redundant_With] VARCHAR(255)
  9789. )
  9790. INSERT INTO #IndexCreation
  9791. SELECT i.database_id,
  9792. m.[name],
  9793. RIGHT(i.[statement], LEN(i.[statement]) - (LEN(m.[name]) + 3)) AS [Table],
  9794. i.index_handle AS [ix_handle],
  9795. [User_Hits_on_Missing_Index] = (s.user_seeks + s.user_scans),
  9796. s.avg_user_impact, -- Query cost would reduce by this amount in percentage, on average.
  9797. s.avg_total_user_cost, -- Average cost of the user queries that could be reduced by the index in the group.
  9798. s.unique_compiles, -- Number of compilations and recompilations that would benefit from this missing index group.
  9799. (CONVERT(NUMERIC(19,3), s.user_seeks) + CONVERT(NUMERIC(19,3), s.user_scans))
  9800. * CONVERT(NUMERIC(19,3), s.avg_total_user_cost)
  9801. * CONVERT(NUMERIC(19,3), s.avg_user_impact) AS Score, -- The higher the score, higher is the anticipated improvement for user queries.
  9802. CASE WHEN (i.equality_columns IS NOT NULL AND i.inequality_columns IS NULL) THEN i.equality_columns
  9803. WHEN (i.equality_columns IS NULL AND i.inequality_columns IS NOT NULL) THEN i.inequality_columns
  9804. ELSE i.equality_columns + ',' + i.inequality_columns END AS [KeyCols],
  9805. i.included_columns AS [IncludedCols],
  9806. '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),
  9807. 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],
  9808. tempdb.dbo.fn_createindex_allcols(i.index_handle),
  9809. tempdb.dbo.fn_createindex_keycols(i.index_handle),
  9810. tempdb.dbo.fn_createindex_includecols(i.index_handle)
  9811. FROM sys.dm_db_missing_index_details i
  9812. INNER JOIN master.sys.databases m ON i.database_id = m.database_id
  9813. INNER JOIN sys.dm_db_missing_index_groups g ON i.index_handle = g.index_handle
  9814. INNER JOIN sys.dm_db_missing_index_group_stats s ON s.group_handle = g.index_group_handle
  9815. WHERE i.database_id > 4
  9816. INSERT INTO #IndexRedundant
  9817. SELECT I.DBName, I.[Table], I.[Ix_Name], I.[ix_handle], I.[KeyCols], I.[IncludedCols], I2.[Ix_Name]
  9818. FROM #IndexCreation I
  9819. INNER JOIN #IndexCreation I2 ON I.[database_id] = I2.[database_id] AND I.[Table] = I2.[Table] AND I.[Ix_Name] <> I2.[Ix_Name]
  9820. AND (((I.KeyColsOrdered <> I2.KeyColsOrdered OR I.[IncludedColsOrdered] <> I2.[IncludedColsOrdered])
  9821. 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)
  9822. OR I.[AllCols] = I2.[AllCols]))
  9823. OR (I.KeyColsOrdered <> I2.KeyColsOrdered AND I.[IncludedColsOrdered] = I2.[IncludedColsOrdered])
  9824. OR (I.KeyColsOrdered = I2.KeyColsOrdered AND I.[IncludedColsOrdered] <> I2.[IncludedColsOrdered]))
  9825. WHERE I.[Score] >= 100000
  9826. AND I2.[Score] >= 100000
  9827. GROUP BY I.DBName, I.[Table], I.[Ix_Name], I.[ix_handle], I.[KeyCols], I.[IncludedCols], I2.[Ix_Name]
  9828. ORDER BY I.DBName, I.[Table], I.[Ix_Name]
  9829. IF (SELECT COUNT(*) FROM #IndexCreation WHERE [Score] >= 100000) > 0
  9830. BEGIN
  9831. 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]
  9832. 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],
  9833. [Estimated_Improvement_Percent], [Avg_Total_User_Cost], [Unique_Compiles], IC.[KeyCols], IC.[IncludedCols], IC.[Ix_Name] AS [Index_Name],
  9834. SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9835. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9836. ORDER BY IR.[Redundant_With]
  9837. FOR XML PATH('')), 2, 8000) AS [Possibly_Redundant_With],
  9838. CASE WHEN IC.[Score] >= 100000 THEN 'Y' ELSE 'N' END AS [Generate_Script]
  9839. FROM #IndexCreation IC
  9840. --WHERE [Score] >= 100000
  9841. ORDER BY IC.DBName, IC.[Score] DESC, IC.[User_Hits_on_Missing_Index], IC.[Estimated_Improvement_Percent];
  9842. 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],
  9843. I.[Ix_Name] AS [Index_Name], I.[KeyCols], I.[IncludedCols]
  9844. FROM #IndexRedundant I
  9845. ORDER BY I.DBName, I.[Table], I.[Ix_Name]
  9846. IF @gen_scripts = 1
  9847. BEGIN
  9848. PRINT CHAR(10) + '/* Generated on ' + CONVERT (VARCHAR, GETDATE()) + ' in ' + @@SERVERNAME + ' */' + CHAR(10)
  9849. IF (SELECT COUNT(*) FROM #IndexCreation IC
  9850. WHERE IC.[IncludedCols] IS NULL AND IC.[Score] >= 100000
  9851. ) > 0
  9852. BEGIN
  9853. PRINT '--############# Indexes creation statements #############' + CHAR(10)
  9854. DECLARE cIC CURSOR FAST_FORWARD FOR
  9855. SELECT '-- User Hits on Missing Index ' + IC.[Ix_Name] + ': ' + CONVERT(VARCHAR(20),IC.[User_Hits_on_Missing_Index]) + CHAR(10) +
  9856. '-- Estimated Improvement Percent: ' + CONVERT(VARCHAR(6),IC.[Estimated_Improvement_Percent]) + CHAR(10) +
  9857. '-- Average Total User Cost: ' + CONVERT(VARCHAR(50),IC.[Avg_Total_User_Cost]) + CHAR(10) +
  9858. '-- Unique Compiles: ' + CONVERT(VARCHAR(50),IC.[Unique_Compiles]) + CHAR(10) +
  9859. '-- Score: ' + CONVERT(VARCHAR(20),CONVERT(bigint,IC.[Score])) +
  9860. CASE WHEN (SELECT COUNT(IR.[Redundant_With]) FROM #IndexRedundant IR
  9861. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]) > 0
  9862. THEN CHAR(10) + '-- Possibly Redundant with Missing Index(es): ' + SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9863. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9864. FOR XML PATH('')), 2, 8000)
  9865. ELSE '' END +
  9866. CHAR(10) + 'USE ' + QUOTENAME(IC.DBName) + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sysindexes WHERE name = N''' +
  9867. IC.[Ix_Name] + ''') DROP INDEX ' + IC.[Table] + '.' +
  9868. IC.[Ix_Name] + ';' + CHAR(10) + 'GO' + CHAR(10) + 'CREATE INDEX ' +
  9869. IC.[Ix_Name] + ' ON ' + IC.[Table] + ' (' + IC.[KeyCols] + CASE WHEN @editionCheck = 1 THEN ') WITH (ONLINE = ON);' ELSE ');' END + CHAR(10) + 'GO' + CHAR(10)
  9870. FROM #IndexCreation IC
  9871. WHERE IC.[IncludedCols] IS NULL AND IC.[Score] >= 100000
  9872. ORDER BY IC.DBName, IC.[Table], IC.[Ix_Name]
  9873. OPEN cIC
  9874. FETCH NEXT FROM cIC INTO @IC
  9875. WHILE @@FETCH_STATUS = 0
  9876. BEGIN
  9877. PRINT @IC
  9878. FETCH NEXT FROM cIC INTO @IC
  9879. END
  9880. CLOSE cIC
  9881. DEALLOCATE cIC
  9882. END;
  9883. IF (SELECT COUNT(*) FROM #IndexCreation IC
  9884. WHERE IC.[IncludedCols] IS NOT NULL AND IC.[Score] >= 100000
  9885. ) > 0
  9886. BEGIN
  9887. PRINT '--############# Covering indexes creation statements #############' + CHAR(10)
  9888. DECLARE cICWI CURSOR FAST_FORWARD FOR
  9889. SELECT '-- User Hits on Missing Index ' + IC.[Ix_Name] + ': ' + CONVERT(VARCHAR(20),IC.[User_Hits_on_Missing_Index]) + CHAR(10) +
  9890. '-- Estimated Improvement Percent: ' + CONVERT(VARCHAR(6),IC.[Estimated_Improvement_Percent]) + CHAR(10) +
  9891. '-- Average Total User Cost: ' + CONVERT(VARCHAR(50),IC.[Avg_Total_User_Cost]) + CHAR(10) +
  9892. '-- Unique Compiles: ' + CONVERT(VARCHAR(50),IC.[Unique_Compiles]) + CHAR(10) +
  9893. '-- Score: ' + CONVERT(VARCHAR(20),CONVERT(bigint,IC.[Score])) +
  9894. CASE WHEN (SELECT COUNT(IR.[Redundant_With]) FROM #IndexRedundant IR
  9895. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]) > 0
  9896. THEN CHAR(10) + '-- Possibly Redundant with Missing Index(es): ' + SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9897. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9898. FOR XML PATH('')), 2, 8000)
  9899. ELSE '' END +
  9900. CHAR(10) + 'USE ' + QUOTENAME(IC.DBName) + CHAR(10) + 'GO' + CHAR(10) + 'IF EXISTS (SELECT name FROM sysindexes WHERE name = N''' +
  9901. IC.[Ix_Name] + ''') DROP INDEX ' + IC.[Table] + '.' +
  9902. IC.[Ix_Name] + ';' + CHAR(10) + 'GO' + CHAR(10) + 'CREATE INDEX ' +
  9903. 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)
  9904. FROM #IndexCreation IC
  9905. WHERE IC.[IncludedCols] IS NOT NULL AND IC.[Score] >= 100000
  9906. ORDER BY IC.DBName, IC.[Table], IC.[Ix_Name]
  9907. OPEN cICWI
  9908. FETCH NEXT FROM cICWI INTO @ICWI
  9909. WHILE @@FETCH_STATUS = 0
  9910. BEGIN
  9911. PRINT @ICWI
  9912. FETCH NEXT FROM cICWI INTO @ICWI
  9913. END
  9914. CLOSE cICWI
  9915. DEALLOCATE cICWI
  9916. END;
  9917. PRINT '--############# Ended missing indexes creation statements #############' + CHAR(10)
  9918. END;
  9919. END
  9920. ELSE IF (SELECT COUNT(*) FROM #IndexCreation WHERE [Score] < 100000) > 0
  9921. BEGIN
  9922. 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]
  9923. 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],
  9924. [Estimated_Improvement_Percent], [Avg_Total_User_Cost], [Unique_Compiles], IC.[KeyCols], IC.[IncludedCols], IC.[Ix_Name] AS [Index_Name],
  9925. SUBSTRING((SELECT ',' + IR.[Redundant_With] FROM #IndexRedundant IR
  9926. WHERE IC.DBName = IR.DBName AND IC.[Table] = IR.[Table] AND IC.[ix_handle] = IR.[ix_handle]
  9927. ORDER BY IR.[Redundant_With]
  9928. FOR XML PATH('')), 2, 8000) AS [Possibly_Redundant_With],
  9929. CASE WHEN IC.[Score] >= 100000 THEN 'Y' ELSE 'N' END AS [Generate_Script]
  9930. FROM #IndexCreation IC
  9931. --WHERE [Score] < 100000
  9932. ORDER BY IC.DBName, IC.[Score] DESC, IC.[User_Hits_on_Missing_Index], IC.[Estimated_Improvement_Percent];
  9933. END
  9934. ELSE
  9935. BEGIN
  9936. SELECT 'Index_and_Stats_checks' AS [Category], 'Missing_Indexes' AS [Check], '[OK]' AS [Deviation]
  9937. END
  9938. END;
  9939. --------------------------------------------------------------------------------------------------------------------------------
  9940. -- Objects naming conventions subsection
  9941. -- Refer to BOL for more information
  9942. -- (http://msdn.microsoft.com/en-us/library/dd172115(v=vs.100).aspx)
  9943. -- (http://msdn.microsoft.com/en-us/library/dd172134.aspx)
  9944. -- (http://msdn.microsoft.com/en-us/library/ms189822.aspx)
  9945. --------------------------------------------------------------------------------------------------------------------------------
  9946. RAISERROR (N'|-Starting Objects naming conventions Checks', 10, 1) WITH NOWAIT
  9947. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  9948. DROP TABLE #tmpobjectnames;
  9949. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  9950. CREATE TABLE #tmpobjectnames ([DBName] sysname, [schemaName] VARCHAR(100), [Object] VARCHAR(255), [Col] VARCHAR(255), [type] CHAR(2), type_desc VARCHAR(60));
  9951. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  9952. DROP TABLE #tmpfinalobjectnames;
  9953. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  9954. CREATE TABLE #tmpfinalobjectnames ([Deviation] tinyint, [DBName] sysname, [schemaName] VARCHAR(100), [Object] VARCHAR(255), [Col] VARCHAR(255), type_desc VARCHAR(60), [Comment] VARCHAR(500) NULL);
  9955. UPDATE #tmpdbs1
  9956. SET isdone = 0
  9957. WHILE (SELECT COUNT(id) FROM #tmpdbs1 WHERE isdone = 0) > 0
  9958. BEGIN
  9959. SELECT TOP 1 @dbname = [dbname], @dbid = [dbid] FROM #tmpdbs1 WHERE isdone = 0
  9960. SET @sqlcmd = 'USE ' + QUOTENAME(@dbname) + ';
  9961. SELECT ''' + @dbname + ''' AS [DBName], s.name, so.name, NULL, type, type_desc
  9962. FROM sys.objects so
  9963. INNER JOIN sys.schemas s ON so.schema_id = s.schema_id
  9964. WHERE so.is_ms_shipped = 0
  9965. UNION ALL
  9966. SELECT ''' + @dbname + ''' AS [DBName], s.name, so.name, sc.name, ''TC'' AS [type], ''TABLE_COLUMN'' AS [type_desc]
  9967. FROM sys.columns sc
  9968. INNER JOIN sys.objects so ON sc.object_id = so.object_id
  9969. INNER JOIN sys.schemas s ON so.schema_id = s.schema_id
  9970. WHERE so.is_ms_shipped = 0'
  9971. BEGIN TRY
  9972. INSERT INTO #tmpobjectnames
  9973. EXECUTE sp_executesql @sqlcmd
  9974. END TRY
  9975. BEGIN CATCH
  9976. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  9977. SELECT @ErrorMessage = 'Object naming conventions subsection - Error raised in TRY block in database ' + @dbname +'. ' + ERROR_MESSAGE()
  9978. RAISERROR (@ErrorMessage, 16, 1);
  9979. END CATCH
  9980. UPDATE #tmpdbs1
  9981. SET isdone = 1
  9982. WHERE [dbid] = @dbid
  9983. END;
  9984. UPDATE #tmpdbs1
  9985. SET isdone = 0
  9986. CREATE INDEX IX1 ON #tmpobjectnames([type],[Object]);
  9987. /* http://msdn.microsoft.com/en-us/library/dd172115(v=vs.100).aspx */
  9988. INSERT INTO #tmpfinalobjectnames
  9989. SELECT 1, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  9990. FROM #tmpobjectnames
  9991. WHERE [type] = 'P' AND [Object] LIKE 'sp[_]%'
  9992. AND [Object] NOT IN ('sp_alterdiagram','sp_creatediagram','sp_dropdiagram','sp_helpdiagramdefinition','sp_helpdiagrams','sp_renamediagram','sp_upgraddiagrams');
  9993. /* http://msdn.microsoft.com/en-us/library/dd172134.aspx */
  9994. INSERT INTO #tmpfinalobjectnames
  9995. SELECT 2, [DBName], [schemaName], [Object], [Col], type_desc, CASE WHEN [Object] LIKE '% %' THEN 'Space - ' + QUOTENAME([Object]) ELSE NULL END COLLATE database_default AS [Comment]
  9996. FROM #tmpobjectnames
  9997. WHERE [type] <> 'S' AND [type] <> 'TC'
  9998. AND ([Object] LIKE '% %' --space
  9999. OR [Object] LIKE '%[[]%'
  10000. OR [Object] LIKE '%]%'
  10001. OR [Object] LIKE '%-%'
  10002. OR [Object] LIKE '%.%'
  10003. OR [Object] LIKE '%,%'
  10004. OR [Object] LIKE '%;%'
  10005. OR [Object] LIKE '%' + CHAR(34) + '%' --double quote
  10006. OR [Object] LIKE '%' + CHAR(39) + '%'); --single quote
  10007. INSERT INTO #tmpfinalobjectnames
  10008. SELECT 3, [DBName], [schemaName], [Object], [Col], type_desc, CASE WHEN [Col] LIKE '% %' THEN 'Space - ' + QUOTENAME([Col]) ELSE NULL END COLLATE database_default AS [Comment]
  10009. FROM #tmpobjectnames
  10010. WHERE [type] = 'TC'
  10011. AND ([Col] LIKE '% %' --space
  10012. OR [Col] LIKE '%[[]%'
  10013. OR [Col] LIKE '%]%'
  10014. OR [Col] LIKE '%-%'
  10015. OR [Col] LIKE '%.%'
  10016. OR [Col] LIKE '%,%'
  10017. OR [Col] LIKE '%;%'
  10018. OR [Col] LIKE '%' + CHAR(34) + '%' --double quote
  10019. OR [Col] LIKE '%' + CHAR(39) + '%'); --single quote
  10020. /* http://msdn.microsoft.com/en-us/library/ms189822.aspx */
  10021. INSERT INTO #tmpfinalobjectnames
  10022. SELECT 4, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10023. FROM #tmpobjectnames
  10024. WHERE [type] <> 'S'
  10025. AND ([Object] LIKE '% ABSOLUTE %' OR [Object] LIKE '% ABSOLUTE' OR [Object] = 'ABSOLUTE'
  10026. OR [Object] LIKE '% ACTION %' OR [Object] LIKE '% ACTION' OR [Object] = 'ACTION'
  10027. OR [Object] LIKE '% ADA %' OR [Object] LIKE '% ADA' OR [Object] = 'ADA'
  10028. OR [Object] LIKE '% ADD %' OR [Object] LIKE '% ADD' OR [Object] = 'ADD'
  10029. OR [Object] LIKE '% ADMIN %' OR [Object] LIKE '% ADMIN' OR [Object] = 'ADMIN'
  10030. OR [Object] LIKE '% AFTER %' OR [Object] LIKE '% AFTER' OR [Object] = 'AFTER'
  10031. OR [Object] LIKE '% AGGREGATE %' OR [Object] LIKE '% AGGREGATE' OR [Object] = 'AGGREGATE'
  10032. OR [Object] LIKE '% ALIAS %' OR [Object] LIKE '% ALIAS' OR [Object] = 'ALIAS'
  10033. OR [Object] LIKE '% ALL %' OR [Object] LIKE '% ALL' OR [Object] = 'ALL'
  10034. OR [Object] LIKE '% ALLOCATE %' OR [Object] LIKE '% ALLOCATE' OR [Object] = 'ALLOCATE'
  10035. OR [Object] LIKE '% ALTER %' OR [Object] LIKE '% ALTER' OR [Object] = 'ALTER'
  10036. OR [Object] LIKE '% AND %' OR [Object] LIKE '% AND' OR [Object] = 'AND'
  10037. OR [Object] LIKE '% ANY %' OR [Object] LIKE '% ANY' OR [Object] = 'ANY'
  10038. OR [Object] LIKE '% ARE %' OR [Object] LIKE '% ARE' OR [Object] = 'ARE'
  10039. OR [Object] LIKE '% ARRAY %' OR [Object] LIKE '% ARRAY' OR [Object] = 'ARRAY'
  10040. OR [Object] LIKE '% AS %' OR [Object] LIKE '% AS' OR [Object] = 'AS'
  10041. OR [Object] LIKE '% ASC %' OR [Object] LIKE '% ASC' OR [Object] = 'ASC'
  10042. OR [Object] LIKE '% ASSERTION %' OR [Object] LIKE '% ASSERTION' OR [Object] = 'ASSERTION'
  10043. OR [Object] LIKE '% AT %' OR [Object] LIKE '% AT' OR [Object] = 'AT'
  10044. OR [Object] LIKE '% AUTHORIZATION %' OR [Object] LIKE '% AUTHORIZATION' OR [Object] = 'AUTHORIZATION'
  10045. OR [Object] LIKE '% AVG %' OR [Object] LIKE '% AVG' OR [Object] = 'AVG'
  10046. OR [Object] LIKE '% BACKUP %' OR [Object] LIKE '% BACKUP' OR [Object] = 'BACKUP'
  10047. OR [Object] LIKE '% BEFORE %' OR [Object] LIKE '% BEFORE' OR [Object] = 'BEFORE'
  10048. OR [Object] LIKE '% BEGIN %' OR [Object] LIKE '% BEGIN' OR [Object] = 'BEGIN'
  10049. OR [Object] LIKE '% BETWEEN %' OR [Object] LIKE '% BETWEEN' OR [Object] = 'BETWEEN'
  10050. OR [Object] LIKE '% BINARY %' OR [Object] LIKE '% BINARY' OR [Object] = 'BINARY'
  10051. OR [Object] LIKE '% BIT %' OR [Object] LIKE '% BIT' OR [Object] = 'BIT'
  10052. OR [Object] LIKE '% BIT_LENGTH %' OR [Object] LIKE '% BIT_LENGTH' OR [Object] = 'BIT_LENGTH'
  10053. OR [Object] LIKE '% BLOB %' OR [Object] LIKE '% BLOB' OR [Object] = 'BLOB'
  10054. OR [Object] LIKE '% BOOLEAN %' OR [Object] LIKE '% BOOLEAN' OR [Object] = 'BOOLEAN'
  10055. OR [Object] LIKE '% BOTH %' OR [Object] LIKE '% BOTH' OR [Object] = 'BOTH'
  10056. OR [Object] LIKE '% BREADTH %' OR [Object] LIKE '% BREADTH' OR [Object] = 'BREADTH'
  10057. OR [Object] LIKE '% BREAK %' OR [Object] LIKE '% BREAK' OR [Object] = 'BREAK'
  10058. OR [Object] LIKE '% BROWSE %' OR [Object] LIKE '% BROWSE' OR [Object] = 'BROWSE'
  10059. OR [Object] LIKE '% BULK %' OR [Object] LIKE '% BULK' OR [Object] = 'BULK'
  10060. OR [Object] LIKE '% BY %' OR [Object] LIKE '% BY' OR [Object] = 'BY'
  10061. OR [Object] LIKE '% CALL %' OR [Object] LIKE '% CALL' OR [Object] = 'CALL'
  10062. OR [Object] LIKE '% CASCADE %' OR [Object] LIKE '% CASCADE' OR [Object] = 'CASCADE'
  10063. OR [Object] LIKE '% CASCADED %' OR [Object] LIKE '% CASCADED' OR [Object] = 'CASCADED'
  10064. OR [Object] LIKE '% CASE %' OR [Object] LIKE '% CASE' OR [Object] = 'CASE'
  10065. OR [Object] LIKE '% CAST %' OR [Object] LIKE '% CAST' OR [Object] = 'CAST'
  10066. OR [Object] LIKE '% CATALOG %' OR [Object] LIKE '% CATALOG' OR [Object] = 'CATALOG'
  10067. OR [Object] LIKE '% CHAR %' OR [Object] LIKE '% CHAR' OR [Object] = 'CHAR'
  10068. OR [Object] LIKE '% CHAR_LENGTH %' OR [Object] LIKE '% CHAR_LENGTH' OR [Object] = 'CHAR_LENGTH'
  10069. OR [Object] LIKE '% CHARACTER %' OR [Object] LIKE '% CHARACTER' OR [Object] = 'CHARACTER'
  10070. OR [Object] LIKE '% CHARACTER_LENGTH %' OR [Object] LIKE '% CHARACTER_LENGTH' OR [Object] = 'CHARACTER_LENGTH'
  10071. OR [Object] LIKE '% CHECK %' OR [Object] LIKE '% CHECK' OR [Object] = 'CHECK'
  10072. OR [Object] LIKE '% CHECKPOINT %' OR [Object] LIKE '% CHECKPOINT' OR [Object] = 'CHECKPOINT'
  10073. OR [Object] LIKE '% CLASS %' OR [Object] LIKE '% CLASS' OR [Object] = 'CLASS'
  10074. OR [Object] LIKE '% CLOB %' OR [Object] LIKE '% CLOB' OR [Object] = 'CLOB'
  10075. OR [Object] LIKE '% CLOSE %' OR [Object] LIKE '% CLOSE' OR [Object] = 'CLOSE'
  10076. OR [Object] LIKE '% CLUSTERED %' OR [Object] LIKE '% CLUSTERED' OR [Object] = 'CLUSTERED'
  10077. OR [Object] LIKE '% COALESCE %' OR [Object] LIKE '% COALESCE' OR [Object] = 'COALESCE'
  10078. OR [Object] LIKE '% COLLATE %' OR [Object] LIKE '% COLLATE' OR [Object] = 'COLLATE'
  10079. OR [Object] LIKE '% COLLATION %' OR [Object] LIKE '% COLLATION' OR [Object] = 'COLLATION'
  10080. OR [Object] LIKE '% COLUMN %' OR [Object] LIKE '% COLUMN' OR [Object] = 'COLUMN'
  10081. OR [Object] LIKE '% COMMIT %' OR [Object] LIKE '% COMMIT' OR [Object] = 'COMMIT'
  10082. OR [Object] LIKE '% COMPLETION %' OR [Object] LIKE '% COMPLETION' OR [Object] = 'COMPLETION'
  10083. OR [Object] LIKE '% COMPUTE %' OR [Object] LIKE '% COMPUTE' OR [Object] = 'COMPUTE'
  10084. OR [Object] LIKE '% CONNECT %' OR [Object] LIKE '% CONNECT' OR [Object] = 'CONNECT'
  10085. OR [Object] LIKE '% CONNECTION %' OR [Object] LIKE '% CONNECTION' OR [Object] = 'CONNECTION'
  10086. OR [Object] LIKE '% CONSTRAINT %' OR [Object] LIKE '% CONSTRAINT' OR [Object] = 'CONSTRAINT'
  10087. OR [Object] LIKE '% CONSTRAINTS %' OR [Object] LIKE '% CONSTRAINTS' OR [Object] = 'CONSTRAINTS'
  10088. OR [Object] LIKE '% CONSTRUCTOR %' OR [Object] LIKE '% CONSTRUCTOR' OR [Object] = 'CONSTRUCTOR'
  10089. OR [Object] LIKE '% CONTAINS %' OR [Object] LIKE '% CONTAINS' OR [Object] = 'CONTAINS'
  10090. OR [Object] LIKE '% CONTAINSTABLE %' OR [Object] LIKE '% CONTAINSTABLE' OR [Object] = 'CONTAINSTABLE'
  10091. OR [Object] LIKE '% CONTINUE %' OR [Object] LIKE '% CONTINUE' OR [Object] = 'CONTINUE'
  10092. OR [Object] LIKE '% CONVERT %' OR [Object] LIKE '% CONVERT' OR [Object] = 'CONVERT'
  10093. OR [Object] LIKE '% CORRESPONDING %' OR [Object] LIKE '% CORRESPONDING' OR [Object] = 'CORRESPONDING'
  10094. OR [Object] LIKE '% COUNT %' OR [Object] LIKE '% COUNT' OR [Object] = 'COUNT'
  10095. OR [Object] LIKE '% CREATE %' OR [Object] LIKE '% CREATE' OR [Object] = 'CREATE'
  10096. OR [Object] LIKE '% CROSS %' OR [Object] LIKE '% CROSS' OR [Object] = 'CROSS'
  10097. OR [Object] LIKE '% CUBE %' OR [Object] LIKE '% CUBE' OR [Object] = 'CUBE'
  10098. OR [Object] LIKE '% CURRENT %' OR [Object] LIKE '% CURRENT' OR [Object] = 'CURRENT'
  10099. OR [Object] LIKE '% CURRENT_DATE %' OR [Object] LIKE '% CURRENT_DATE' OR [Object] = 'CURRENT_DATE'
  10100. OR [Object] LIKE '% CURRENT_PATH %' OR [Object] LIKE '% CURRENT_PATH' OR [Object] = 'CURRENT_PATH'
  10101. OR [Object] LIKE '% CURRENT_ROLE %' OR [Object] LIKE '% CURRENT_ROLE' OR [Object] = 'CURRENT_ROLE'
  10102. OR [Object] LIKE '% CURRENT_TIME %' OR [Object] LIKE '% CURRENT_TIME' OR [Object] = 'CURRENT_TIME'
  10103. OR [Object] LIKE '% CURRENT_TIMESTAMP %' OR [Object] LIKE '% CURRENT_TIMESTAMP' OR [Object] = 'CURRENT_TIMESTAMP'
  10104. OR [Object] LIKE '% CURRENT_USER %' OR [Object] LIKE '% CURRENT_USER' OR [Object] = 'CURRENT_USER'
  10105. OR [Object] LIKE '% CURSOR %' OR [Object] LIKE '% CURSOR' OR [Object] = 'CURSOR'
  10106. OR [Object] LIKE '% CYCLE %' OR [Object] LIKE '% CYCLE' OR [Object] = 'CYCLE'
  10107. OR [Object] LIKE '% DATA %' OR [Object] LIKE '% DATA' OR [Object] = 'DATA'
  10108. OR [Object] LIKE '% DATABASE %' OR [Object] LIKE '% DATABASE' OR [Object] = 'DATABASE'
  10109. OR [Object] LIKE '% DATE %' OR [Object] LIKE '% DATE' OR [Object] = 'DATE'
  10110. OR [Object] LIKE '% DAY %' OR [Object] LIKE '% DAY' OR [Object] = 'DAY'
  10111. OR [Object] LIKE '% DBCC %' OR [Object] LIKE '% DBCC' OR [Object] = 'DBCC'
  10112. OR [Object] LIKE '% DEALLOCATE %' OR [Object] LIKE '% DEALLOCATE' OR [Object] = 'DEALLOCATE'
  10113. OR [Object] LIKE '% DEC %' OR [Object] LIKE '% DEC' OR [Object] = 'DEC'
  10114. OR [Object] LIKE '% DECIMAL %' OR [Object] LIKE '% DECIMAL' OR [Object] = 'DECIMAL'
  10115. OR [Object] LIKE '% DECLARE %' OR [Object] LIKE '% DECLARE' OR [Object] = 'DECLARE'
  10116. OR [Object] LIKE '% DEFAULT %' OR [Object] LIKE '% DEFAULT' OR [Object] = 'DEFAULT'
  10117. OR [Object] LIKE '% DEFERRABLE %' OR [Object] LIKE '% DEFERRABLE' OR [Object] = 'DEFERRABLE'
  10118. OR [Object] LIKE '% DEFERRED %' OR [Object] LIKE '% DEFERRED' OR [Object] = 'DEFERRED'
  10119. OR [Object] LIKE '% DELETE %' OR [Object] LIKE '% DELETE' OR [Object] = 'DELETE'
  10120. OR [Object] LIKE '% DENY %' OR [Object] LIKE '% DENY' OR [Object] = 'DENY'
  10121. OR [Object] LIKE '% DEPTH %' OR [Object] LIKE '% DEPTH' OR [Object] = 'DEPTH'
  10122. OR [Object] LIKE '% DEREF %' OR [Object] LIKE '% DEREF' OR [Object] = 'DEREF'
  10123. OR [Object] LIKE '% DESC %' OR [Object] LIKE '% DESC' OR [Object] = 'DESC'
  10124. OR [Object] LIKE '% DESCRIBE %' OR [Object] LIKE '% DESCRIBE' OR [Object] = 'DESCRIBE'
  10125. OR [Object] LIKE '% DESCRIPTOR %' OR [Object] LIKE '% DESCRIPTOR' OR [Object] = 'DESCRIPTOR'
  10126. OR [Object] LIKE '% DESTROY %' OR [Object] LIKE '% DESTROY' OR [Object] = 'DESTROY'
  10127. OR [Object] LIKE '% DESTRUCTOR %' OR [Object] LIKE '% DESTRUCTOR' OR [Object] = 'DESTRUCTOR'
  10128. OR [Object] LIKE '% DETERMINISTIC %' OR [Object] LIKE '% DETERMINISTIC' OR [Object] = 'DETERMINISTIC'
  10129. OR [Object] LIKE '% DIAGNOSTICS %' OR [Object] LIKE '% DIAGNOSTICS' OR [Object] = 'DIAGNOSTICS'
  10130. OR [Object] LIKE '% DICTIONARY %' OR [Object] LIKE '% DICTIONARY' OR [Object] = 'DICTIONARY'
  10131. OR [Object] LIKE '% DISCONNECT %' OR [Object] LIKE '% DISCONNECT' OR [Object] = 'DISCONNECT'
  10132. OR [Object] LIKE '% DISK %' OR [Object] LIKE '% DISK' OR [Object] = 'DISK'
  10133. OR [Object] LIKE '% DISTINCT %' OR [Object] LIKE '% DISTINCT' OR [Object] = 'DISTINCT'
  10134. OR [Object] LIKE '% DISTRIBUTED %' OR [Object] LIKE '% DISTRIBUTED' OR [Object] = 'DISTRIBUTED'
  10135. OR [Object] LIKE '% DOMAIN %' OR [Object] LIKE '% DOMAIN' OR [Object] = 'DOMAIN'
  10136. OR [Object] LIKE '% DOUBLE %' OR [Object] LIKE '% DOUBLE' OR [Object] = 'DOUBLE'
  10137. OR [Object] LIKE '% DROP %' OR [Object] LIKE '% DROP' OR [Object] = 'DROP'
  10138. OR [Object] LIKE '% DUMMY %' OR [Object] LIKE '% DUMMY' OR [Object] = 'DUMMY'
  10139. OR [Object] LIKE '% DUMP %' OR [Object] LIKE '% DUMP' OR [Object] = 'DUMP'
  10140. OR [Object] LIKE '% DYNAMIC %' OR [Object] LIKE '% DYNAMIC' OR [Object] = 'DYNAMIC'
  10141. OR [Object] LIKE '% EACH %' OR [Object] LIKE '% EACH' OR [Object] = 'EACH'
  10142. OR [Object] LIKE '% ELSE %' OR [Object] LIKE '% ELSE' OR [Object] = 'ELSE'
  10143. OR [Object] LIKE '% END %' OR [Object] LIKE '% END' OR [Object] = 'END'
  10144. OR [Object] LIKE '% END-EXEC %' OR [Object] LIKE '% END-EXEC' OR [Object] = 'END-EXEC'
  10145. OR [Object] LIKE '% EQUALS %' OR [Object] LIKE '% EQUALS' OR [Object] = 'EQUALS'
  10146. OR [Object] LIKE '% ERRLVL %' OR [Object] LIKE '% ERRLVL' OR [Object] = 'ERRLVL'
  10147. OR [Object] LIKE '% ESCAPE %' OR [Object] LIKE '% ESCAPE' OR [Object] = 'ESCAPE'
  10148. OR [Object] LIKE '% EVERY %' OR [Object] LIKE '% EVERY' OR [Object] = 'EVERY'
  10149. OR [Object] LIKE '% EXCEPT %' OR [Object] LIKE '% EXCEPT' OR [Object] = 'EXCEPT'
  10150. OR [Object] LIKE '% EXCEPTION %' OR [Object] LIKE '% EXCEPTION' OR [Object] = 'EXCEPTION'
  10151. OR [Object] LIKE '% EXEC %' OR [Object] LIKE '% EXEC' OR [Object] = 'EXEC'
  10152. OR [Object] LIKE '% EXECUTE %' OR [Object] LIKE '% EXECUTE' OR [Object] = 'EXECUTE'
  10153. OR [Object] LIKE '% EXISTS %' OR [Object] LIKE '% EXISTS' OR [Object] = 'EXISTS'
  10154. OR [Object] LIKE '% EXIT %' OR [Object] LIKE '% EXIT' OR [Object] = 'EXIT'
  10155. OR [Object] LIKE '% EXTERNAL %' OR [Object] LIKE '% EXTERNAL' OR [Object] = 'EXTERNAL'
  10156. OR [Object] LIKE '% EXTRACT %' OR [Object] LIKE '% EXTRACT' OR [Object] = 'EXTRACT'
  10157. OR [Object] LIKE '% FALSE %' OR [Object] LIKE '% FALSE' OR [Object] = 'FALSE'
  10158. OR [Object] LIKE '% FETCH %' OR [Object] LIKE '% FETCH' OR [Object] = 'FETCH'
  10159. OR [Object] LIKE '% FILE %' OR [Object] LIKE '% FILE' OR [Object] = 'FILE'
  10160. OR [Object] LIKE '% FILLFACTOR %' OR [Object] LIKE '% FILLFACTOR' OR [Object] = 'FILLFACTOR'
  10161. OR [Object] LIKE '% FIRST %' OR [Object] LIKE '% FIRST' OR [Object] = 'FIRST'
  10162. OR [Object] LIKE '% FLOAT %' OR [Object] LIKE '% FLOAT' OR [Object] = 'FLOAT'
  10163. OR [Object] LIKE '% FOR %' OR [Object] LIKE '% FOR' OR [Object] = 'FOR'
  10164. OR [Object] LIKE '% FOREIGN %' OR [Object] LIKE '% FOREIGN' OR [Object] = 'FOREIGN'
  10165. OR [Object] LIKE '% FORTRAN %' OR [Object] LIKE '% FORTRAN' OR [Object] = 'FORTRAN'
  10166. OR [Object] LIKE '% FOUND %' OR [Object] LIKE '% FOUND' OR [Object] = 'FOUND'
  10167. OR [Object] LIKE '% FREE %' OR [Object] LIKE '% FREE' OR [Object] = 'FREE'
  10168. OR [Object] LIKE '% FREETEXT %' OR [Object] LIKE '% FREETEXT' OR [Object] = 'FREETEXT'
  10169. OR [Object] LIKE '% FREETEXTTABLE %' OR [Object] LIKE '% FREETEXTTABLE' OR [Object] = 'FREETEXTTABLE'
  10170. OR [Object] LIKE '% FROM %' OR [Object] LIKE '% FROM' OR [Object] = 'FROM'
  10171. OR [Object] LIKE '% FULL %' OR [Object] LIKE '% FULL' OR [Object] = 'FULL'
  10172. OR [Object] LIKE '% FULLTEXTTABLE %' OR [Object] LIKE '% FULLTEXTTABLE' OR [Object] = 'FULLTEXTTABLE'
  10173. OR [Object] LIKE '% FUNCTION %' OR [Object] LIKE '% FUNCTION' OR [Object] = 'FUNCTION'
  10174. OR [Object] LIKE '% GENERAL %' OR [Object] LIKE '% GENERAL' OR [Object] = 'GENERAL'
  10175. OR [Object] LIKE '% GET %' OR [Object] LIKE '% GET' OR [Object] = 'GET'
  10176. OR [Object] LIKE '% GLOBAL %' OR [Object] LIKE '% GLOBAL' OR [Object] = 'GLOBAL'
  10177. OR [Object] LIKE '% GO %' OR [Object] LIKE '% GO' OR [Object] = 'GO'
  10178. OR [Object] LIKE '% GOTO %' OR [Object] LIKE '% GOTO' OR [Object] = 'GOTO'
  10179. OR [Object] LIKE '% GRANT %' OR [Object] LIKE '% GRANT' OR [Object] = 'GRANT'
  10180. OR [Object] LIKE '% GROUP %' OR [Object] LIKE '% GROUP' OR [Object] = 'GROUP'
  10181. OR [Object] LIKE '% GROUPING %' OR [Object] LIKE '% GROUPING' OR [Object] = 'GROUPING'
  10182. OR [Object] LIKE '% HAVING %' OR [Object] LIKE '% HAVING' OR [Object] = 'HAVING'
  10183. OR [Object] LIKE '% HOLDLOCK %' OR [Object] LIKE '% HOLDLOCK' OR [Object] = 'HOLDLOCK'
  10184. OR [Object] LIKE '% HOST %' OR [Object] LIKE '% HOST' OR [Object] = 'HOST'
  10185. OR [Object] LIKE '% HOUR %' OR [Object] LIKE '% HOUR' OR [Object] = 'HOUR'
  10186. OR [Object] LIKE '% IDENTITY %' OR [Object] LIKE '% IDENTITY' OR [Object] = 'IDENTITY'
  10187. OR [Object] LIKE '% IDENTITY_INSERT %' OR [Object] LIKE '% IDENTITY_INSERT' OR [Object] = 'IDENTITY_INSERT'
  10188. OR [Object] LIKE '% IDENTITYCOL %' OR [Object] LIKE '% IDENTITYCOL' OR [Object] = 'IDENTITYCOL'
  10189. OR [Object] LIKE '% IF %' OR [Object] LIKE '% IF' OR [Object] = 'IF'
  10190. OR [Object] LIKE '% IGNORE %' OR [Object] LIKE '% IGNORE' OR [Object] = 'IGNORE'
  10191. OR [Object] LIKE '% IMMEDIATE %' OR [Object] LIKE '% IMMEDIATE' OR [Object] = 'IMMEDIATE'
  10192. OR [Object] LIKE '% IN %' OR [Object] LIKE '% IN' OR [Object] = 'IN'
  10193. OR [Object] LIKE '% INCLUDE %' OR [Object] LIKE '% INCLUDE' OR [Object] = 'INCLUDE'
  10194. OR [Object] LIKE '% INDEX %' OR [Object] LIKE '% INDEX' OR [Object] = 'INDEX'
  10195. OR [Object] LIKE '% INDICATOR %' OR [Object] LIKE '% INDICATOR' OR [Object] = 'INDICATOR'
  10196. OR [Object] LIKE '% INITIALIZE %' OR [Object] LIKE '% INITIALIZE' OR [Object] = 'INITIALIZE'
  10197. OR [Object] LIKE '% INITIALLY %' OR [Object] LIKE '% INITIALLY' OR [Object] = 'INITIALLY'
  10198. OR [Object] LIKE '% INNER %' OR [Object] LIKE '% INNER' OR [Object] = 'INNER'
  10199. OR [Object] LIKE '% INOUT %' OR [Object] LIKE '% INOUT' OR [Object] = 'INOUT'
  10200. OR [Object] LIKE '% INPUT %' OR [Object] LIKE '% INPUT' OR [Object] = 'INPUT'
  10201. OR [Object] LIKE '% INSENSITIVE %' OR [Object] LIKE '% INSENSITIVE' OR [Object] = 'INSENSITIVE'
  10202. OR [Object] LIKE '% INSERT %' OR [Object] LIKE '% INSERT' OR [Object] = 'INSERT'
  10203. OR [Object] LIKE '% INT %' OR [Object] LIKE '% INT' OR [Object] = 'INT'
  10204. OR [Object] LIKE '% INTEGER %' OR [Object] LIKE '% INTEGER' OR [Object] = 'INTEGER'
  10205. OR [Object] LIKE '% INTERSECT %' OR [Object] LIKE '% INTERSECT' OR [Object] = 'INTERSECT'
  10206. OR [Object] LIKE '% INTERVAL %' OR [Object] LIKE '% INTERVAL' OR [Object] = 'INTERVAL'
  10207. OR [Object] LIKE '% INTO %' OR [Object] LIKE '% INTO' OR [Object] = 'INTO'
  10208. OR [Object] LIKE '% IS %' OR [Object] LIKE '% IS' OR [Object] = 'IS'
  10209. OR [Object] LIKE '% ISOLATION %' OR [Object] LIKE '% ISOLATION' OR [Object] = 'ISOLATION'
  10210. OR [Object] LIKE '% ITERATE %' OR [Object] LIKE '% ITERATE' OR [Object] = 'ITERATE'
  10211. OR [Object] LIKE '% JOIN %' OR [Object] LIKE '% JOIN' OR [Object] = 'JOIN'
  10212. OR [Object] LIKE '% KEY %' OR [Object] LIKE '% KEY' OR [Object] = 'KEY'
  10213. OR [Object] LIKE '% KILL %' OR [Object] LIKE '% KILL' OR [Object] = 'KILL'
  10214. OR [Object] LIKE '% LANGUAGE %' OR [Object] LIKE '% LANGUAGE' OR [Object] = 'LANGUAGE'
  10215. OR [Object] LIKE '% LARGE %' OR [Object] LIKE '% LARGE' OR [Object] = 'LARGE'
  10216. OR [Object] LIKE '% LAST %' OR [Object] LIKE '% LAST' OR [Object] = 'LAST'
  10217. OR [Object] LIKE '% LATERAL %' OR [Object] LIKE '% LATERAL' OR [Object] = 'LATERAL'
  10218. OR [Object] LIKE '% LEADING %' OR [Object] LIKE '% LEADING' OR [Object] = 'LEADING'
  10219. OR [Object] LIKE '% LEFT %' OR [Object] LIKE '% LEFT' OR [Object] = 'LEFT'
  10220. OR [Object] LIKE '% LESS %' OR [Object] LIKE '% LESS' OR [Object] = 'LESS'
  10221. OR [Object] LIKE '% LEVEL %' OR [Object] LIKE '% LEVEL' OR [Object] = 'LEVEL'
  10222. OR [Object] LIKE '% LIKE %' OR [Object] LIKE '% LIKE' OR [Object] = 'LIKE'
  10223. OR [Object] LIKE '% LIMIT %' OR [Object] LIKE '% LIMIT' OR [Object] = 'LIMIT'
  10224. OR [Object] LIKE '% LINENO %' OR [Object] LIKE '% LINENO' OR [Object] = 'LINENO'
  10225. OR [Object] LIKE '% LOAD %' OR [Object] LIKE '% LOAD' OR [Object] = 'LOAD'
  10226. OR [Object] LIKE '% LOCAL %' OR [Object] LIKE '% LOCAL' OR [Object] = 'LOCAL'
  10227. OR [Object] LIKE '% LOCALTIME %' OR [Object] LIKE '% LOCALTIME' OR [Object] = 'LOCALTIME'
  10228. OR [Object] LIKE '% LOCALTIMESTAMP %' OR [Object] LIKE '% LOCALTIMESTAMP' OR [Object] = 'LOCALTIMESTAMP'
  10229. OR [Object] LIKE '% LOCATOR %' OR [Object] LIKE '% LOCATOR' OR [Object] = 'LOCATOR'
  10230. OR [Object] LIKE '% LOWER %' OR [Object] LIKE '% LOWER' OR [Object] = 'LOWER'
  10231. OR [Object] LIKE '% MAP %' OR [Object] LIKE '% MAP' OR [Object] = 'MAP'
  10232. OR [Object] LIKE '% MATCH %' OR [Object] LIKE '% MATCH' OR [Object] = 'MATCH'
  10233. OR [Object] LIKE '% MAX %' OR [Object] LIKE '% MAX' OR [Object] = 'MAX'
  10234. OR [Object] LIKE '% MIN %' OR [Object] LIKE '% MIN' OR [Object] = 'MIN'
  10235. OR [Object] LIKE '% MINUTE %' OR [Object] LIKE '% MINUTE' OR [Object] = 'MINUTE'
  10236. OR [Object] LIKE '% MODIFIES %' OR [Object] LIKE '% MODIFIES' OR [Object] = 'MODIFIES'
  10237. OR [Object] LIKE '% MODIFY %' OR [Object] LIKE '% MODIFY' OR [Object] = 'MODIFY'
  10238. OR [Object] LIKE '% MODULE %' OR [Object] LIKE '% MODULE' OR [Object] = 'MODULE'
  10239. OR [Object] LIKE '% MONTH %' OR [Object] LIKE '% MONTH' OR [Object] = 'MONTH'
  10240. OR [Object] LIKE '% NAMES %' OR [Object] LIKE '% NAMES' OR [Object] = 'NAMES'
  10241. OR [Object] LIKE '% NATIONAL %' OR [Object] LIKE '% NATIONAL' OR [Object] = 'NATIONAL'
  10242. OR [Object] LIKE '% NATURAL %' OR [Object] LIKE '% NATURAL' OR [Object] = 'NATURAL'
  10243. OR [Object] LIKE '% NCHAR %' OR [Object] LIKE '% NCHAR' OR [Object] = 'NCHAR'
  10244. OR [Object] LIKE '% NCLOB %' OR [Object] LIKE '% NCLOB' OR [Object] = 'NCLOB'
  10245. OR [Object] LIKE '% NEW %' OR [Object] LIKE '% NEW' OR [Object] = 'NEW'
  10246. OR [Object] LIKE '% NEXT %' OR [Object] LIKE '% NEXT' OR [Object] = 'NEXT'
  10247. OR [Object] LIKE '% NO %' OR [Object] LIKE '% NO' OR [Object] = 'NO'
  10248. OR [Object] LIKE '% NOCHECK %' OR [Object] LIKE '% NOCHECK' OR [Object] = 'NOCHECK'
  10249. OR [Object] LIKE '% NONCLUSTERED %' OR [Object] LIKE '% NONCLUSTERED' OR [Object] = 'NONCLUSTERED'
  10250. OR [Object] LIKE '% NONE %' OR [Object] LIKE '% NONE' OR [Object] = 'NONE'
  10251. OR [Object] LIKE '% NOT %' OR [Object] LIKE '% NOT' OR [Object] = 'NOT'
  10252. OR [Object] LIKE '% NULL %' OR [Object] LIKE '% NULL' OR [Object] = 'NULL'
  10253. OR [Object] LIKE '% NULLIF %' OR [Object] LIKE '% NULLIF' OR [Object] = 'NULLIF'
  10254. OR [Object] LIKE '% NUMERIC %' OR [Object] LIKE '% NUMERIC' OR [Object] = 'NUMERIC'
  10255. OR [Object] LIKE '% OBJECT %' OR [Object] LIKE '% OBJECT' OR [Object] = 'OBJECT'
  10256. OR [Object] LIKE '% OCTET_LENGTH %' OR [Object] LIKE '% OCTET_LENGTH' OR [Object] = 'OCTET_LENGTH'
  10257. OR [Object] LIKE '% OF %' OR [Object] LIKE '% OF' OR [Object] = 'OF'
  10258. OR [Object] LIKE '% OFF %' OR [Object] LIKE '% OFF' OR [Object] = 'OFF'
  10259. OR [Object] LIKE '% OFFSETS %' OR [Object] LIKE '% OFFSETS' OR [Object] = 'OFFSETS'
  10260. OR [Object] LIKE '% OLD %' OR [Object] LIKE '% OLD' OR [Object] = 'OLD'
  10261. OR [Object] LIKE '% ON %' OR [Object] LIKE '% ON' OR [Object] = 'ON'
  10262. OR [Object] LIKE '% ONLY %' OR [Object] LIKE '% ONLY' OR [Object] = 'ONLY'
  10263. OR [Object] LIKE '% OPEN %' OR [Object] LIKE '% OPEN' OR [Object] = 'OPEN'
  10264. OR [Object] LIKE '% OPENDATASOURCE %' OR [Object] LIKE '% OPENDATASOURCE' OR [Object] = 'OPENDATASOURCE'
  10265. OR [Object] LIKE '% OPENQUERY %' OR [Object] LIKE '% OPENQUERY' OR [Object] = 'OPENQUERY'
  10266. OR [Object] LIKE '% OPENROWSET %' OR [Object] LIKE '% OPENROWSET' OR [Object] = 'OPENROWSET'
  10267. OR [Object] LIKE '% OPENXML %' OR [Object] LIKE '% OPENXML' OR [Object] = 'OPENXML'
  10268. OR [Object] LIKE '% OPERATION %' OR [Object] LIKE '% OPERATION' OR [Object] = 'OPERATION'
  10269. OR [Object] LIKE '% OPTION %' OR [Object] LIKE '% OPTION' OR [Object] = 'OPTION'
  10270. OR [Object] LIKE '% OR %' OR [Object] LIKE '% OR' OR [Object] = 'OR'
  10271. OR [Object] LIKE '% ORDER %' OR [Object] LIKE '% ORDER' OR [Object] = 'ORDER'
  10272. OR [Object] LIKE '% ORDINALITY %' OR [Object] LIKE '% ORDINALITY' OR [Object] = 'ORDINALITY'
  10273. OR [Object] LIKE '% OUT %' OR [Object] LIKE '% OUT' OR [Object] = 'OUT'
  10274. OR [Object] LIKE '% OUTER %' OR [Object] LIKE '% OUTER' OR [Object] = 'OUTER'
  10275. OR [Object] LIKE '% OUTPUT %' OR [Object] LIKE '% OUTPUT' OR [Object] = 'OUTPUT'
  10276. OR [Object] LIKE '% OVER %' OR [Object] LIKE '% OVER' OR [Object] = 'OVER'
  10277. OR [Object] LIKE '% OVERLAPS %' OR [Object] LIKE '% OVERLAPS' OR [Object] = 'OVERLAPS'
  10278. OR [Object] LIKE '% PAD %' OR [Object] LIKE '% PAD' OR [Object] = 'PAD'
  10279. OR [Object] LIKE '% PARAMETER %' OR [Object] LIKE '% PARAMETER' OR [Object] = 'PARAMETER'
  10280. OR [Object] LIKE '% PARAMETERS %' OR [Object] LIKE '% PARAMETERS' OR [Object] = 'PARAMETERS'
  10281. OR [Object] LIKE '% PARTIAL %' OR [Object] LIKE '% PARTIAL' OR [Object] = 'PARTIAL'
  10282. OR [Object] LIKE '% PASCAL %' OR [Object] LIKE '% PASCAL' OR [Object] = 'PASCAL'
  10283. OR [Object] LIKE '% PATH %' OR [Object] LIKE '% PATH' OR [Object] = 'PATH'
  10284. OR [Object] LIKE '% PERCENT %' OR [Object] LIKE '% PERCENT' OR [Object] = 'PERCENT'
  10285. OR [Object] LIKE '% PLAN %' OR [Object] LIKE '% PLAN' OR [Object] = 'PLAN'
  10286. OR [Object] LIKE '% POSITION %' OR [Object] LIKE '% POSITION' OR [Object] = 'POSITION'
  10287. OR [Object] LIKE '% POSTFIX %' OR [Object] LIKE '% POSTFIX' OR [Object] = 'POSTFIX'
  10288. OR [Object] LIKE '% PRECISION %' OR [Object] LIKE '% PRECISION' OR [Object] = 'PRECISION'
  10289. OR [Object] LIKE '% PREFIX %' OR [Object] LIKE '% PREFIX' OR [Object] = 'PREFIX'
  10290. OR [Object] LIKE '% PREORDER %' OR [Object] LIKE '% PREORDER' OR [Object] = 'PREORDER'
  10291. OR [Object] LIKE '% PREPARE %' OR [Object] LIKE '% PREPARE' OR [Object] = 'PREPARE'
  10292. OR [Object] LIKE '% PRESERVE %' OR [Object] LIKE '% PRESERVE' OR [Object] = 'PRESERVE'
  10293. OR [Object] LIKE '% PRIMARY %' OR [Object] LIKE '% PRIMARY' OR [Object] = 'PRIMARY'
  10294. OR [Object] LIKE '% PRINT %' OR [Object] LIKE '% PRINT' OR [Object] = 'PRINT'
  10295. OR [Object] LIKE '% PRIOR %' OR [Object] LIKE '% PRIOR' OR [Object] = 'PRIOR'
  10296. OR [Object] LIKE '% PRIVILEGES %' OR [Object] LIKE '% PRIVILEGES' OR [Object] = 'PRIVILEGES'
  10297. OR [Object] LIKE '% PROC %' OR [Object] LIKE '% PROC' OR [Object] = 'PROC'
  10298. OR [Object] LIKE '% PROCEDURE %' OR [Object] LIKE '% PROCEDURE' OR [Object] = 'PROCEDURE'
  10299. OR [Object] LIKE '% PUBLIC %' OR [Object] LIKE '% PUBLIC' OR [Object] = 'PUBLIC'
  10300. OR [Object] LIKE '% RAISERROR %' OR [Object] LIKE '% RAISERROR' OR [Object] = 'RAISERROR'
  10301. OR [Object] LIKE '% READ %' OR [Object] LIKE '% READ' OR [Object] = 'READ'
  10302. OR [Object] LIKE '% READS %' OR [Object] LIKE '% READS' OR [Object] = 'READS'
  10303. OR [Object] LIKE '% READTEXT %' OR [Object] LIKE '% READTEXT' OR [Object] = 'READTEXT'
  10304. OR [Object] LIKE '% REAL %' OR [Object] LIKE '% REAL' OR [Object] = 'REAL'
  10305. OR [Object] LIKE '% RECONFIGURE %' OR [Object] LIKE '% RECONFIGURE' OR [Object] = 'RECONFIGURE'
  10306. OR [Object] LIKE '% RECURSIVE %' OR [Object] LIKE '% RECURSIVE' OR [Object] = 'RECURSIVE'
  10307. OR [Object] LIKE '% REF %' OR [Object] LIKE '% REF' OR [Object] = 'REF'
  10308. OR [Object] LIKE '% REFERENCES %' OR [Object] LIKE '% REFERENCES' OR [Object] = 'REFERENCES'
  10309. OR [Object] LIKE '% REFERENCING %' OR [Object] LIKE '% REFERENCING' OR [Object] = 'REFERENCING'
  10310. OR [Object] LIKE '% RELATIVE %' OR [Object] LIKE '% RELATIVE' OR [Object] = 'RELATIVE'
  10311. OR [Object] LIKE '% REPLICATION %' OR [Object] LIKE '% REPLICATION' OR [Object] = 'REPLICATION'
  10312. OR [Object] LIKE '% RESTORE %' OR [Object] LIKE '% RESTORE' OR [Object] = 'RESTORE'
  10313. OR [Object] LIKE '% RESTRICT %' OR [Object] LIKE '% RESTRICT' OR [Object] = 'RESTRICT'
  10314. OR [Object] LIKE '% RESULT %' OR [Object] LIKE '% RESULT' OR [Object] = 'RESULT'
  10315. OR [Object] LIKE '% RETURN %' OR [Object] LIKE '% RETURN' OR [Object] = 'RETURN'
  10316. OR [Object] LIKE '% RETURNS %' OR [Object] LIKE '% RETURNS' OR [Object] = 'RETURNS'
  10317. OR [Object] LIKE '% REVOKE %' OR [Object] LIKE '% REVOKE' OR [Object] = 'REVOKE'
  10318. OR [Object] LIKE '% RIGHT %' OR [Object] LIKE '% RIGHT' OR [Object] = 'RIGHT'
  10319. OR [Object] LIKE '% ROLE %' OR [Object] LIKE '% ROLE' OR [Object] = 'ROLE'
  10320. OR [Object] LIKE '% ROLLBACK %' OR [Object] LIKE '% ROLLBACK' OR [Object] = 'ROLLBACK'
  10321. OR [Object] LIKE '% ROLLUP %' OR [Object] LIKE '% ROLLUP' OR [Object] = 'ROLLUP'
  10322. OR [Object] LIKE '% ROUTINE %' OR [Object] LIKE '% ROUTINE' OR [Object] = 'ROUTINE'
  10323. OR [Object] LIKE '% ROW %' OR [Object] LIKE '% ROW' OR [Object] = 'ROW'
  10324. OR [Object] LIKE '% ROWCOUNT %' OR [Object] LIKE '% ROWCOUNT' OR [Object] = 'ROWCOUNT'
  10325. OR [Object] LIKE '% ROWGUIDCOL %' OR [Object] LIKE '% ROWGUIDCOL' OR [Object] = 'ROWGUIDCOL'
  10326. OR [Object] LIKE '% ROWS %' OR [Object] LIKE '% ROWS' OR [Object] = 'ROWS'
  10327. OR [Object] LIKE '% RULE %' OR [Object] LIKE '% RULE' OR [Object] = 'RULE'
  10328. OR [Object] LIKE '% SAVE %' OR [Object] LIKE '% SAVE' OR [Object] = 'SAVE'
  10329. OR [Object] LIKE '% SAVEPOINT %' OR [Object] LIKE '% SAVEPOINT' OR [Object] = 'SAVEPOINT'
  10330. OR [Object] LIKE '% SCHEMA %' OR [Object] LIKE '% SCHEMA' OR [Object] = 'SCHEMA'
  10331. OR [Object] LIKE '% SCOPE %' OR [Object] LIKE '% SCOPE' OR [Object] = 'SCOPE'
  10332. OR [Object] LIKE '% SCROLL %' OR [Object] LIKE '% SCROLL' OR [Object] = 'SCROLL'
  10333. OR [Object] LIKE '% SEARCH %' OR [Object] LIKE '% SEARCH' OR [Object] = 'SEARCH'
  10334. OR [Object] LIKE '% SECOND %' OR [Object] LIKE '% SECOND' OR [Object] = 'SECOND'
  10335. OR [Object] LIKE '% SECTION %' OR [Object] LIKE '% SECTION' OR [Object] = 'SECTION'
  10336. OR [Object] LIKE '% SELECT %' OR [Object] LIKE '% SELECT' OR [Object] = 'SELECT'
  10337. OR [Object] LIKE '% SEQUENCE %' OR [Object] LIKE '% SEQUENCE' OR [Object] = 'SEQUENCE'
  10338. OR [Object] LIKE '% SESSION %' OR [Object] LIKE '% SESSION' OR [Object] = 'SESSION'
  10339. OR [Object] LIKE '% SESSION_USER %' OR [Object] LIKE '% SESSION_USER' OR [Object] = 'SESSION_USER'
  10340. OR [Object] LIKE '% SET %' OR [Object] LIKE '% SET' OR [Object] = 'SET'
  10341. OR [Object] LIKE '% SETS %' OR [Object] LIKE '% SETS' OR [Object] = 'SETS'
  10342. OR [Object] LIKE '% SETUSER %' OR [Object] LIKE '% SETUSER' OR [Object] = 'SETUSER'
  10343. OR [Object] LIKE '% SHUTDOWN %' OR [Object] LIKE '% SHUTDOWN' OR [Object] = 'SHUTDOWN'
  10344. OR [Object] LIKE '% SIZE %' OR [Object] LIKE '% SIZE' OR [Object] = 'SIZE'
  10345. OR [Object] LIKE '% SMALLINT %' OR [Object] LIKE '% SMALLINT' OR [Object] = 'SMALLINT'
  10346. OR [Object] LIKE '% SOME %' OR [Object] LIKE '% SOME' OR [Object] = 'SOME'
  10347. OR [Object] LIKE '% SPACE %' OR [Object] LIKE '% SPACE' OR [Object] = 'SPACE'
  10348. OR [Object] LIKE '% SPECIFIC %' OR [Object] LIKE '% SPECIFIC' OR [Object] = 'SPECIFIC'
  10349. OR [Object] LIKE '% SPECIFICTYPE %' OR [Object] LIKE '% SPECIFICTYPE' OR [Object] = 'SPECIFICTYPE'
  10350. OR [Object] LIKE '% SQL %' OR [Object] LIKE '% SQL' OR [Object] = 'SQL'
  10351. OR [Object] LIKE '% SQLCA %' OR [Object] LIKE '% SQLCA' OR [Object] = 'SQLCA'
  10352. OR [Object] LIKE '% SQLCODE %' OR [Object] LIKE '% SQLCODE' OR [Object] = 'SQLCODE'
  10353. OR [Object] LIKE '% SQLERROR %' OR [Object] LIKE '% SQLERROR' OR [Object] = 'SQLERROR'
  10354. OR [Object] LIKE '% SQLEXCEPTION %' OR [Object] LIKE '% SQLEXCEPTION' OR [Object] = 'SQLEXCEPTION'
  10355. OR [Object] LIKE '% SQLSTATE %' OR [Object] LIKE '% SQLSTATE' OR [Object] = 'SQLSTATE'
  10356. OR [Object] LIKE '% SQLWARNING %' OR [Object] LIKE '% SQLWARNING' OR [Object] = 'SQLWARNING'
  10357. OR [Object] LIKE '% START %' OR [Object] LIKE '% START' OR [Object] = 'START'
  10358. OR [Object] LIKE '% STATE %' OR [Object] LIKE '% STATE' OR [Object] = 'STATE'
  10359. OR [Object] LIKE '% STATEMENT %' OR [Object] LIKE '% STATEMENT' OR [Object] = 'STATEMENT'
  10360. OR [Object] LIKE '% STATIC %' OR [Object] LIKE '% STATIC' OR [Object] = 'STATIC'
  10361. OR [Object] LIKE '% STATISTICS %' OR [Object] LIKE '% STATISTICS' OR [Object] = 'STATISTICS'
  10362. OR [Object] LIKE '% STRUCTURE %' OR [Object] LIKE '% STRUCTURE' OR [Object] = 'STRUCTURE'
  10363. OR [Object] LIKE '% SUBSTRING %' OR [Object] LIKE '% SUBSTRING' OR [Object] = 'SUBSTRING'
  10364. OR [Object] LIKE '% SUM %' OR [Object] LIKE '% SUM' OR [Object] = 'SUM'
  10365. OR [Object] LIKE '% SYSTEM_USER %' OR [Object] LIKE '% SYSTEM_USER' OR [Object] = 'SYSTEM_USER'
  10366. OR [Object] LIKE '% TABLE %' OR [Object] LIKE '% TABLE' OR [Object] = 'TABLE'
  10367. OR [Object] LIKE '% TEMPORARY %' OR [Object] LIKE '% TEMPORARY' OR [Object] = 'TEMPORARY'
  10368. OR [Object] LIKE '% TERMINATE %' OR [Object] LIKE '% TERMINATE' OR [Object] = 'TERMINATE'
  10369. OR [Object] LIKE '% TEXTSIZE %' OR [Object] LIKE '% TEXTSIZE' OR [Object] = 'TEXTSIZE'
  10370. OR [Object] LIKE '% THAN %' OR [Object] LIKE '% THAN' OR [Object] = 'THAN'
  10371. OR [Object] LIKE '% THEN %' OR [Object] LIKE '% THEN' OR [Object] = 'THEN'
  10372. OR [Object] LIKE '% TIME %' OR [Object] LIKE '% TIME' OR [Object] = 'TIME'
  10373. OR [Object] LIKE '% TIMESTAMP %' OR [Object] LIKE '% TIMESTAMP' OR [Object] = 'TIMESTAMP'
  10374. OR [Object] LIKE '% TIMEZONE_HOUR %' OR [Object] LIKE '% TIMEZONE_HOUR' OR [Object] = 'TIMEZONE_HOUR'
  10375. OR [Object] LIKE '% TIMEZONE_MINUTE %' OR [Object] LIKE '% TIMEZONE_MINUTE' OR [Object] = 'TIMEZONE_MINUTE'
  10376. OR [Object] LIKE '% TO %' OR [Object] LIKE '% TO' OR [Object] = 'TO'
  10377. OR [Object] LIKE '% TOP %' OR [Object] LIKE '% TOP' OR [Object] = 'TOP'
  10378. OR [Object] LIKE '% TRAILING %' OR [Object] LIKE '% TRAILING' OR [Object] = 'TRAILING'
  10379. OR [Object] LIKE '% TRAN %' OR [Object] LIKE '% TRAN' OR [Object] = 'TRAN'
  10380. OR [Object] LIKE '% TRANSACTION %' OR [Object] LIKE '% TRANSACTION' OR [Object] = 'TRANSACTION'
  10381. OR [Object] LIKE '% TRANSLATE %' OR [Object] LIKE '% TRANSLATE' OR [Object] = 'TRANSLATE'
  10382. OR [Object] LIKE '% TRANSLATION %' OR [Object] LIKE '% TRANSLATION' OR [Object] = 'TRANSLATION'
  10383. OR [Object] LIKE '% TREAT %' OR [Object] LIKE '% TREAT' OR [Object] = 'TREAT'
  10384. OR [Object] LIKE '% TRIGGER %' OR [Object] LIKE '% TRIGGER' OR [Object] = 'TRIGGER'
  10385. OR [Object] LIKE '% TRIM %' OR [Object] LIKE '% TRIM' OR [Object] = 'TRIM'
  10386. OR [Object] LIKE '% TRUE %' OR [Object] LIKE '% TRUE' OR [Object] = 'TRUE'
  10387. OR [Object] LIKE '% TRUNCATE %' OR [Object] LIKE '% TRUNCATE' OR [Object] = 'TRUNCATE'
  10388. OR [Object] LIKE '% UNDER %' OR [Object] LIKE '% UNDER' OR [Object] = 'UNDER'
  10389. OR [Object] LIKE '% UNION %' OR [Object] LIKE '% UNION' OR [Object] = 'UNION'
  10390. OR [Object] LIKE '% UNIQUE %' OR [Object] LIKE '% UNIQUE' OR [Object] = 'UNIQUE'
  10391. OR [Object] LIKE '% UNKNOWN %' OR [Object] LIKE '% UNKNOWN' OR [Object] = 'UNKNOWN'
  10392. OR [Object] LIKE '% UNNEST %' OR [Object] LIKE '% UNNEST' OR [Object] = 'UNNEST'
  10393. OR [Object] LIKE '% UPDATE %' OR [Object] LIKE '% UPDATE' OR [Object] = 'UPDATE'
  10394. OR [Object] LIKE '% UPDATETEXT %' OR [Object] LIKE '% UPDATETEXT' OR [Object] = 'UPDATETEXT'
  10395. OR [Object] LIKE '% UPPER %' OR [Object] LIKE '% UPPER' OR [Object] = 'UPPER'
  10396. OR [Object] LIKE '% USAGE %' OR [Object] LIKE '% USAGE' OR [Object] = 'USAGE'
  10397. OR [Object] LIKE '% USE %' OR [Object] LIKE '% USE' OR [Object] = 'USE'
  10398. OR [Object] LIKE '% USER %' OR [Object] LIKE '% USER' OR [Object] = 'USER'
  10399. OR [Object] LIKE '% USING %' OR [Object] LIKE '% USING' OR [Object] = 'USING'
  10400. OR [Object] LIKE '% VALUE %' OR [Object] LIKE '% VALUE' OR [Object] = 'VALUE'
  10401. OR [Object] LIKE '% VALUES %' OR [Object] LIKE '% VALUES' OR [Object] = 'VALUES'
  10402. OR [Object] LIKE '% VARCHAR %' OR [Object] LIKE '% VARCHAR' OR [Object] = 'VARCHAR'
  10403. OR [Object] LIKE '% VARIABLE %' OR [Object] LIKE '% VARIABLE' OR [Object] = 'VARIABLE'
  10404. OR [Object] LIKE '% VARYING %' OR [Object] LIKE '% VARYING' OR [Object] = 'VARYING'
  10405. OR [Object] LIKE '% VIEW %' OR [Object] LIKE '% VIEW' OR [Object] = 'VIEW'
  10406. OR [Object] LIKE '% WAITFOR %' OR [Object] LIKE '% WAITFOR' OR [Object] = 'WAITFOR'
  10407. OR [Object] LIKE '% WHEN %' OR [Object] LIKE '% WHEN' OR [Object] = 'WHEN'
  10408. OR [Object] LIKE '% WHENEVER %' OR [Object] LIKE '% WHENEVER' OR [Object] = 'WHENEVER'
  10409. OR [Object] LIKE '% WHERE %' OR [Object] LIKE '% WHERE' OR [Object] = 'WHERE'
  10410. OR [Object] LIKE '% WHILE %' OR [Object] LIKE '% WHILE' OR [Object] = 'WHILE'
  10411. OR [Object] LIKE '% WITH %' OR [Object] LIKE '% WITH' OR [Object] = 'WITH'
  10412. OR [Object] LIKE '% WITHOUT %' OR [Object] LIKE '% WITHOUT' OR [Object] = 'WITHOUT'
  10413. OR [Object] LIKE '% WORK %' OR [Object] LIKE '% WORK' OR [Object] = 'WORK'
  10414. OR [Object] LIKE '% WRITE %' OR [Object] LIKE '% WRITE' OR [Object] = 'WRITE'
  10415. OR [Object] LIKE '% WRITETEXT %' OR [Object] LIKE '% WRITETEXT' OR [Object] = 'WRITETEXT'
  10416. OR [Object] LIKE '% YEAR %' OR [Object] LIKE '% YEAR' OR [Object] = 'YEAR'
  10417. OR [Object] LIKE '% ZONE %' OR [Object] LIKE '% ZONE' OR [Object] = 'ZONE');
  10418. /* http://msdn.microsoft.com/en-us/library/ms186755.aspx */
  10419. INSERT INTO #tmpfinalobjectnames
  10420. SELECT 5, [DBName], [schemaName], [Object], [Col], type_desc, NULL
  10421. FROM #tmpobjectnames
  10422. WHERE [type] IN ('FN','FS','TF','IF') AND [Object] LIKE 'fn[_]%'
  10423. AND [Object] NOT IN ('fn_diagram_objects');
  10424. IF (SELECT COUNT(*) FROM #tmpfinalobjectnames) > 0
  10425. BEGIN
  10426. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check], '[WARNING: Reserved words or special characters have been found in object names]' AS [Deviation]
  10427. END
  10428. ELSE
  10429. BEGIN
  10430. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check], '[OK]' AS [Deviation]
  10431. END;
  10432. IF (SELECT COUNT(*) FROM #tmpfinalobjectnames) > 0
  10433. BEGIN
  10434. SELECT 'Naming_checks' AS [Category], 'Object_Naming_Convention' AS [Check],
  10435. CASE [Deviation] WHEN 1 THEN '[sp_ as prefix for stored procedures]'
  10436. WHEN 2 THEN '[Special character as part of object name]'
  10437. WHEN 3 THEN '[Special character as part of column name]'
  10438. WHEN 4 THEN '[Reserved words as part of object name]'
  10439. WHEN 5 THEN '[fn_ as prefix for user defined functions]'
  10440. END AS [Deviation],
  10441. [DBName] AS [Database_Name], [schemaName] AS [Schema_Name], [Object] AS [Object_Name], QUOTENAME([Col]) AS [Col], [type_desc] AS [Object_Type]
  10442. FROM #tmpfinalobjectnames
  10443. ORDER BY [Deviation], type_desc, [DBName], [schemaName], [Object];
  10444. END;
  10445. RAISERROR (N'|-Starting Security Checks', 10, 1) WITH NOWAIT
  10446. --------------------------------------------------------------------------------------------------------------------------------
  10447. -- Password check subsection
  10448. --------------------------------------------------------------------------------------------------------------------------------
  10449. RAISERROR (N' |-Starting Password check', 10, 1) WITH NOWAIT
  10450. DECLARE @passwords TABLE ([Deviation] VARCHAR(15), [Name] sysname, [CreateDate] DATETIME)
  10451. DECLARE @word TABLE (word NVARCHAR(50))
  10452. INSERT INTO @word values (0)
  10453. INSERT INTO @word values (1)
  10454. INSERT INTO @word values (12)
  10455. INSERT INTO @word values (123)
  10456. INSERT INTO @word values (1234)
  10457. INSERT INTO @word values (12345)
  10458. INSERT INTO @word values (123456)
  10459. INSERT INTO @word values (1234567)
  10460. INSERT INTO @word values (12345678)
  10461. INSERT INTO @word values (123456789)
  10462. INSERT INTO @word values (1234567890)
  10463. INSERT INTO @word values (11111)
  10464. INSERT INTO @word values (111111)
  10465. INSERT INTO @word values (1111111)
  10466. INSERT INTO @word values (11111111)
  10467. INSERT INTO @word values (21)
  10468. INSERT INTO @word values (321)
  10469. INSERT INTO @word values (4321)
  10470. INSERT INTO @word values (54321)
  10471. INSERT INTO @word values (654321)
  10472. INSERT INTO @word values (7654321)
  10473. INSERT INTO @word values (87654321)
  10474. INSERT INTO @word values (987654321)
  10475. INSERT INTO @word values (0987654321)
  10476. INSERT INTO @word values ('pwd')
  10477. INSERT INTO @word values ('Password')
  10478. INSERT INTO @word values ('password')
  10479. INSERT INTO @word values ('P@ssw0rd')
  10480. INSERT INTO @word values ('p@ssw0rd')
  10481. INSERT INTO @word values ('Teste')
  10482. INSERT INTO @word values ('teste')
  10483. INSERT INTO @word values ('Test')
  10484. INSERT INTO @word values ('test')
  10485. INSERT INTO @word values ('')
  10486. INSERT INTO @word values ('p@wd')
  10487. INSERT INTO @passwords
  10488. SELECT DISTINCT 'Weak_Password' AS Deviation, RTRIM(s.name) AS [Name], createdate AS [CreateDate]
  10489. FROM @word d
  10490. INNER JOIN master.sys.syslogins s ON PWDCOMPARE(RTRIM(RTRIM(d.word)), s.[password]) = 1
  10491. UNION ALL
  10492. SELECT 'NULL_Passwords' AS Deviation, RTRIM(name) AS [Name], createdate AS [CreateDate]
  10493. FROM master.sys.syslogins
  10494. WHERE [password] IS NULL
  10495. AND isntname = 0
  10496. AND name NOT IN ('MSCRMSqlClrLogin','##MS_SmoExtendedSigningCertificate##','##MS_PolicySigningCertificate##','##MS_SQLResourceSigningCertificate##','##MS_SQLReplicationSigningCertificate##','##MS_SQLAuthenticatorCertificate##','##MS_AgentSigningCertificate##','##MS_SQLEnableSystemAssemblyLoadingUser##')
  10497. UNION ALL
  10498. SELECT DISTINCT 'Name=Password' AS Deviation, RTRIM(s.name) AS [Name], createdate AS [CreateDate]
  10499. FROM master.sys.syslogins s
  10500. WHERE PWDCOMPARE(RTRIM(RTRIM(s.name)), s.[password]) = 1
  10501. ORDER BY [Deviation], [Name]
  10502. IF (SELECT COUNT([Deviation]) FROM @passwords) > 0
  10503. BEGIN
  10504. 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]
  10505. SELECT 'Security_checks' AS [Category], 'Password_checks' AS [Information], [Deviation], [Name], [CreateDate]
  10506. FROM @passwords
  10507. ORDER BY [Deviation], [Name]
  10508. END
  10509. ELSE
  10510. BEGIN
  10511. SELECT 'Security_checks' AS [Category], 'Password_checks' AS [Check], '[OK]' AS [Deviation]
  10512. END;
  10513. RAISERROR (N'|-Starting Maintenance and Monitoring Checks', 10, 1) WITH NOWAIT
  10514. --------------------------------------------------------------------------------------------------------------------------------
  10515. -- SQL Agent alerts for severe errors subsection
  10516. --------------------------------------------------------------------------------------------------------------------------------
  10517. RAISERROR (N' |-Starting SQL Agent alerts for severe errors', 10, 1) WITH NOWAIT
  10518. IF (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 1) = 0 AND (SELECT [perm] FROM @permstbl_msdb WHERE [id] = 2) = 0
  10519. BEGIN
  10520. 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')
  10521. --RETURN
  10522. END
  10523. ELSE
  10524. BEGIN
  10525. 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]
  10526. FROM msdb.dbo.sysalerts
  10527. WHERE [message_id] IN (825,833,855,856,3452,3619,17179,17883,17884,17887,17888,17890,28036) OR severity = 10
  10528. UNION ALL
  10529. 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]
  10530. FROM msdb.dbo.sysalerts
  10531. WHERE [message_id] IN (610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300) OR severity = 16
  10532. UNION ALL
  10533. 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]
  10534. FROM msdb.dbo.sysalerts
  10535. WHERE [message_id] IN (802,845,1101,1105,1121,1214,8642,9002) OR severity = 17
  10536. UNION ALL
  10537. 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]
  10538. FROM msdb.dbo.sysalerts
  10539. WHERE [message_id] IN (701) OR severity = 19
  10540. UNION ALL
  10541. 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]
  10542. FROM msdb.dbo.sysalerts
  10543. WHERE [message_id] IN (3624) OR severity = 20
  10544. UNION ALL
  10545. 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]
  10546. FROM msdb.dbo.sysalerts
  10547. WHERE [message_id] IN (605) OR severity = 21
  10548. UNION ALL
  10549. 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]
  10550. FROM msdb.dbo.sysalerts
  10551. WHERE [message_id] IN (5180,8966) OR severity = 22
  10552. UNION ALL
  10553. 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]
  10554. FROM msdb.dbo.sysalerts
  10555. WHERE [message_id] IN (5572,9100) OR severity = 23
  10556. UNION ALL
  10557. 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]
  10558. FROM msdb.dbo.sysalerts
  10559. WHERE [message_id] IN (823,824,832) OR severity = 24
  10560. 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
  10561. 610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300, -- Sev 16
  10562. 802,845,1101,1105,1121,1214,8642,9002, -- Sev 17
  10563. 701, -- Sev 19
  10564. 3624, -- Sev 20
  10565. 605, -- Sev 21
  10566. 5180,8966, -- Sev 22
  10567. 5572,9100, -- Sev 23
  10568. 823,824,832 -- Sev 24
  10569. ) OR [severity] >= 17)) > 0
  10570. BEGIN
  10571. 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]
  10572. FROM msdb.dbo.sysalerts
  10573. WHERE ([message_id] IN (825,833,855,856,3452,3619,17179,17883,17884,17887,17888,17890,28036, -- Sev 10
  10574. 610,2508,2511,3271,5228,5229,5242,5243,5250,5901,8621,17065,17066,17067,17130,17300, -- Sev 16
  10575. 802,845,1101,1105,1121,1214,8642,9002, -- Sev 17
  10576. 701, -- Sev 19
  10577. 3624, -- Sev 20
  10578. 605, -- Sev 21
  10579. 5180,8966, -- Sev 22
  10580. 5572,9100, -- Sev 23
  10581. 823,824,832 -- Sev 24
  10582. ) OR [severity] >= 17);
  10583. END
  10584. END;
  10585. --------------------------------------------------------------------------------------------------------------------------------
  10586. -- DBCC CHECKDB, Direct Catalog Updates and Data Purity subsection
  10587. --------------------------------------------------------------------------------------------------------------------------------
  10588. RAISERROR (N' |-Starting DBCC CHECKDB, Direct Catalog Updates and Data Purity', 10, 1) WITH NOWAIT
  10589. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  10590. DROP TABLE #output_dbinfo;
  10591. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  10592. CREATE TABLE #output_dbinfo (ParentObject VARCHAR(255), [Object] VARCHAR(255), Field VARCHAR(255), [value] VARCHAR(255))
  10593. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  10594. DROP TABLE #dbinfo;
  10595. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  10596. 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)
  10597. IF (ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1)
  10598. BEGIN
  10599. --DECLARE @dbname NVARCHAR(255);
  10600. DECLARE @dbcc bit, @catupd bit, @purity bit;
  10601. DECLARE curDBs CURSOR FAST_FORWARD FOR SELECT name FROM master.sys.databases (NOLOCK) WHERE is_read_only = 0 AND [state] = 0
  10602. OPEN curDBs
  10603. FETCH NEXT FROM curDBs INTO @dbname
  10604. WHILE (@@FETCH_STATUS = 0)
  10605. BEGIN
  10606. SET @dbname = RTRIM(LTRIM(@dbname))
  10607. INSERT INTO #output_dbinfo
  10608. EXEC('DBCC DBINFO(''' + @dbname + ''') WITH TABLERESULTS, NO_INFOMSGS')
  10609. INSERT INTO #dbinfo (dbname, lst_known_checkdb)
  10610. SELECT @dbname, [value] FROM #output_dbinfo WHERE Field LIKE 'dbi_dbccLastKnownGood%';
  10611. UPDATE #dbinfo
  10612. SET #dbinfo.updSysCatalog = #output_dbinfo.[value]
  10613. FROM #output_dbinfo
  10614. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_updSysCatalog%';
  10615. UPDATE #dbinfo
  10616. SET #dbinfo.dbi_createVersion = #output_dbinfo.[value]
  10617. FROM #output_dbinfo
  10618. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_createVersion%';
  10619. UPDATE #dbinfo
  10620. SET #dbinfo.dbi_dbccFlags = #output_dbinfo.[value]
  10621. FROM #output_dbinfo
  10622. WHERE #dbinfo.dbname = @dbname AND #output_dbinfo.Field LIKE 'dbi_dbccFlags%';
  10623. TRUNCATE TABLE #output_dbinfo;
  10624. FETCH NEXT FROM curDBs INTO @dbname
  10625. END
  10626. CLOSE curDBs
  10627. DEALLOCATE curDBs;
  10628. ;WITH cte_dbcc (name, lst_known_checkdb) AS (SELECT sd.name, tmpdbi.lst_known_checkdb
  10629. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10630. WHERE sd.database_id <> 2 AND is_read_only = 0 AND [state] = 0)
  10631. SELECT @dbcc = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10632. FROM cte_dbcc WHERE DATEDIFF(dd, lst_known_checkdb, GETDATE()) > 7 OR lst_known_checkdb IS NULL;
  10633. ;WITH cte_catupd (name, updSysCatalog) AS (SELECT sd.name, tmpdbi.updSysCatalog
  10634. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10635. WHERE sd.database_id <> 2 AND is_read_only = 0 AND [state] = 0)
  10636. SELECT @catupd = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10637. FROM cte_catupd WHERE updSysCatalog > '1900-01-01 00:00:00.000';
  10638. ;WITH cte_purity (name, dbi_createVersion, dbi_dbccFlags) AS (SELECT sd.name, tmpdbi.dbi_createVersion, tmpdbi.dbi_dbccFlags
  10639. FROM master.sys.databases sd (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON sd.name = tmpdbi.dbname
  10640. WHERE sd.database_id > 4 AND is_read_only = 0 AND [state] = 0)
  10641. SELECT @purity = CASE WHEN COUNT(name) > 0 THEN 1 ELSE 0 END
  10642. FROM cte_purity WHERE dbi_createVersion <= 611 AND dbi_dbccFlags = 0; -- <= SQL Server 2005
  10643. IF @dbcc = 1
  10644. BEGIN
  10645. 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]
  10646. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'DBCC_CHECKDB' AS [Information], [name] AS [Database_Name], MAX(lst_known_checkdb) AS Last_Known_CHECKDB
  10647. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10648. WHERE database_id <> 2 AND is_read_only = 0 AND [state] = 0
  10649. GROUP BY [name]
  10650. HAVING DATEDIFF(dd, MAX(lst_known_checkdb), GETDATE()) > 7 OR MAX(lst_known_checkdb) IS NULL
  10651. ORDER BY [name]
  10652. END
  10653. ELSE
  10654. BEGIN
  10655. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'DBCC_CHECKDB' AS [Check], '[OK]' AS [Deviation]
  10656. END;
  10657. IF @catupd = 1
  10658. BEGIN
  10659. SELECT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Check], '[WARNING: Microsoft does not support direct catalog updates to databases.]' AS [Deviation]
  10660. SELECT DISTINCT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Information], [name] AS [Database_Name], MAX(updSysCatalog) AS Last_Direct_Catalog_Update
  10661. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10662. WHERE database_id <> 2 AND is_read_only = 0 AND [state] = 0
  10663. GROUP BY [name]
  10664. HAVING (MAX(updSysCatalog) > '1900-01-01 00:00:00.000')
  10665. ORDER BY [name]
  10666. END
  10667. ELSE
  10668. BEGIN
  10669. SELECT 'Instance_checks' AS [Category], 'Direct_Catalog_Updates' AS [Check], '[OK]' AS [Deviation]
  10670. END;
  10671. -- http://support.microsoft.com/kb/923247/en-us
  10672. -- http://www.sqlskills.com/blogs/paul/checkdb-from-every-angle-how-to-tell-if-data-purity-checks-will-be-run
  10673. IF @purity = 1
  10674. BEGIN
  10675. 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]
  10676. 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
  10677. FROM master.sys.databases (NOLOCK) LEFT JOIN #dbinfo tmpdbi ON name = tmpdbi.dbname
  10678. WHERE database_id > 4 AND dbi_createVersion <= 611 AND dbi_dbccFlags = 0 AND is_read_only = 0 AND [state] = 0
  10679. ORDER BY [name]
  10680. END
  10681. ELSE
  10682. BEGIN
  10683. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Databases_need_data_purity_check' AS [Check], '[OK]' AS [Deviation]
  10684. END;
  10685. END
  10686. ELSE
  10687. BEGIN
  10688. RAISERROR('[WARNING: Only a sysadmin can run the "DBCC CHECKDB, Direct Catalog Updates and Data Purity" checks. Bypassing check]', 16, 1, N'sysadmin')
  10689. --RETURN
  10690. END;
  10691. --------------------------------------------------------------------------------------------------------------------------------
  10692. -- AlwaysOn/Mirroring automatic page repair subsection
  10693. -- Refer to "Automatic Page Repair" BOL entry for more information (http://msdn.microsoft.com/en-us/library/bb677167.aspx)
  10694. --------------------------------------------------------------------------------------------------------------------------------
  10695. IF @sqlmajorver > 9
  10696. BEGIN
  10697. RAISERROR (N' |-Starting AlwaysOn/Mirroring automatic page repair', 10, 1) WITH NOWAIT
  10698. IF @sqlmajorver > 10
  10699. BEGIN
  10700. DECLARE @HadrRep int--, @sqlcmd NVARCHAR(4000), @params NVARCHAR(500)
  10701. SET @sqlcmd = N'SELECT @HadrRepOUT = COUNT(*) FROM sys.dm_hadr_auto_page_repair';
  10702. SET @params = N'@HadrRepOUT int OUTPUT';
  10703. EXECUTE sp_executesql @sqlcmd, @params, @HadrRepOUT=@HadrRep OUTPUT;
  10704. END
  10705. ELSE
  10706. BEGIN
  10707. SET @HadrRep = 0
  10708. END;
  10709. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  10710. DROP TABLE #pagerepair;
  10711. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  10712. 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)
  10713. IF (SELECT COUNT(*) FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)) > 0
  10714. BEGIN
  10715. INSERT INTO #pagerepair
  10716. SELECT DB_NAME(database_id) AS [Database_Name], [file_id], [page_id], [error_type], page_status, MAX(modification_time), 'Mirroring' AS [Repair_Source]
  10717. FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)
  10718. GROUP BY database_id, [file_id], [page_id], [error_type], page_status
  10719. END
  10720. IF @HadrRep > 0
  10721. BEGIN
  10722. INSERT INTO #pagerepair
  10723. 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]')
  10724. END;
  10725. IF (SELECT COUNT(*) FROM sys.dm_db_mirroring_auto_page_repair (NOLOCK)) > 0
  10726. OR @HadrRep > 0
  10727. BEGIN
  10728. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Check], '[WARNING: Page repairs have been found. Check for suspect pages]' AS [Deviation]
  10729. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Information], dbname AS [Database_Name],
  10730. [file_id] AS [File_ID],
  10731. [page_id] AS [Page_ID],
  10732. CASE [error_type]
  10733. WHEN -1 THEN 'Error 823'
  10734. WHEN 1 THEN 'Unspecified Error 824'
  10735. WHEN 2 THEN 'Bad Checksum'
  10736. WHEN 3 THEN 'Torn Page'
  10737. ELSE NULL
  10738. END AS [Error_Type],
  10739. CASE page_status
  10740. WHEN 2 THEN 'Queued for request from partner'
  10741. WHEN 3 THEN 'Request sent to partner'
  10742. WHEN 4 THEN 'Queued for automatic page repair'
  10743. WHEN 5 THEN 'Automatic page repair succeeded'
  10744. WHEN 6 THEN 'Irreparable'
  10745. END AS [Page_Status],
  10746. lst_modification_time AS [Last_Modification_Time], [Repair_Source]
  10747. FROM #pagerepair
  10748. END
  10749. ELSE
  10750. BEGIN
  10751. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Auto_Page_repairs' AS [Check], '[None]' AS [Deviation], '' AS [Source]
  10752. END
  10753. END;
  10754. --------------------------------------------------------------------------------------------------------------------------------
  10755. -- Suspect pages subsection
  10756. -- Refer to "Manage the suspect_pages Table" BOL entry for more information (http://msdn.microsoft.com/en-us/library/ms191301.aspx)
  10757. --------------------------------------------------------------------------------------------------------------------------------
  10758. RAISERROR (N' |-Starting Suspect pages', 10, 1) WITH NOWAIT
  10759. IF (SELECT COUNT(*) FROM msdb.dbo.suspect_pages WHERE (event_type = 1 OR event_type = 2 OR event_type = 3)) > 0
  10760. BEGIN
  10761. 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]
  10762. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Suspect_Pages' AS [Information], DB_NAME(database_id) AS [Database_Name],
  10763. [file_id] AS [File_ID],
  10764. [page_id] AS [Page_ID],
  10765. CASE event_type
  10766. WHEN 1 THEN 'Error 823 or unspecified Error 824'
  10767. WHEN 2 THEN 'Bad Checksum'
  10768. WHEN 3 THEN 'Torn Page'
  10769. ELSE NULL
  10770. END AS [Event_Type],
  10771. error_count AS [Error_Count],
  10772. last_update_date AS [Last_Update_Date]
  10773. FROM msdb.dbo.suspect_pages (NOLOCK)
  10774. WHERE (event_type = 1 OR event_type = 2 OR event_type = 3)
  10775. ORDER BY DB_NAME(database_id), last_update_date DESC, [file_id], [page_id]
  10776. END
  10777. ELSE
  10778. BEGIN
  10779. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Suspect_Pages' AS [Check], '[None]' AS [Deviation]
  10780. END;
  10781. --------------------------------------------------------------------------------------------------------------------------------
  10782. -- Replication Errors subsection
  10783. --------------------------------------------------------------------------------------------------------------------------------
  10784. IF @replication = 1 AND (SELECT COUNT(*) FROM master.sys.databases (NOLOCK) WHERE [name] = 'distribution') > 0
  10785. BEGIN
  10786. RAISERROR (N' |-Starting Replication Errors', 10, 1) WITH NOWAIT
  10787. IF (SELECT COUNT(*) FROM distribution.dbo.MSdistribution_history AS msh
  10788. INNER JOIN distribution.dbo.MSrepl_errors AS mse ON mse.id = msh.error_id
  10789. INNER JOIN distribution.dbo.MSdistribution_agents AS msa ON msh.agent_id = msa.id
  10790. WHERE mse.time >= DATEADD(hh, - 24, GETDATE())) > 0
  10791. BEGIN
  10792. 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]
  10793. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Lst_24H' AS [Information],
  10794. msa.[name] AS [Distribution_Agent], msa.publisher_db AS [Publisher_DB],
  10795. msa.publication AS [Publication], msa.subscriber_db AS [Subscriber_DB], mse.error_code
  10796. FROM distribution.dbo.MSdistribution_history AS msh
  10797. INNER JOIN distribution.dbo.MSrepl_errors AS mse ON mse.id = msh.error_id
  10798. INNER JOIN distribution.dbo.MSdistribution_agents AS msa ON msh.agent_id = msa.id
  10799. WHERE mse.time >= DATEADD(hh, - 24, GETDATE())
  10800. GROUP BY msa.[name], msa.publisher_db, msa.publication, msa.subscriber_db, mse.error_code
  10801. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Details' AS [Information], msh.time,
  10802. msa.[name] AS [Distribution_Agent], msa.publisher_db AS [Publisher_DB],
  10803. msa.publication AS [Publication], msa.subscriber_db AS [Subscriber_DB],
  10804. mse.error_code, mse.error_text
  10805. FROM distribution.dbo.MSdistribution_history AS msh (NOLOCK)
  10806. INNER JOIN distribution.dbo.MSrepl_errors AS mse (NOLOCK) ON mse.id = msh.error_id AND mse.time = msh.time
  10807. INNER JOIN distribution.dbo.MSdistribution_agents AS msa (NOLOCK) ON msh.agent_id = msa.id
  10808. WHERE (mse.time >= DATEADD(hh, - 24, GETDATE()))
  10809. ORDER BY msh.time
  10810. END
  10811. ELSE
  10812. BEGIN
  10813. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Repl_Errors_Lst_24H' AS [Check], '[None]' AS [Deviation]
  10814. END
  10815. END;
  10816. --------------------------------------------------------------------------------------------------------------------------------
  10817. -- Errorlog based checks subsection
  10818. -- Because it is a string based search, add other search conditions as deemed fit.
  10819. --------------------------------------------------------------------------------------------------------------------------------
  10820. RAISERROR (N' |-Starting Errorlog based checks', 10, 1) WITH NOWAIT
  10821. --DECLARE @lognumber int, @logcount int
  10822. DECLARE @langid smallint
  10823. SELECT @langid = lcid FROM sys.syslanguages WHERE name = @@LANGUAGE
  10824. IF ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) = 1 -- Is sysadmin
  10825. OR ISNULL(IS_SRVROLEMEMBER(N'securityadmin'), 0) = 1 -- Is securityadmin
  10826. OR ((SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'sp_readerrorlog') > 0
  10827. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_readerrorlog') > 0
  10828. AND (SELECT COUNT([name]) FROM @permstbl WHERE [name] = 'xp_enumerrorlogs') > 0)
  10829. BEGIN
  10830. SET @lognumber = 0
  10831. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10832. DROP TABLE #dbcc;
  10833. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10834. CREATE TABLE #dbcc (rowid int IDENTITY(1,1) PRIMARY KEY, logid int NULL, logdate DATETIME, spid VARCHAR(50), logmsg VARCHAR(4000))
  10835. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  10836. CREATE INDEX [dbcc_logmsg] ON dbo.[#dbcc](logid)
  10837. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  10838. DROP TABLE #avail_logs;
  10839. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  10840. CREATE TABLE #avail_logs (lognum int, logdate DATETIME, logsize int)
  10841. -- Get the number of available logs
  10842. INSERT INTO #avail_logs
  10843. EXEC xp_enumerrorlogs
  10844. SELECT @logcount = MAX(lognum) FROM #avail_logs
  10845. WHILE @lognumber < @logcount
  10846. BEGIN
  10847. -- Cycle thru sql error logs
  10848. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''15 seconds'''
  10849. BEGIN TRY
  10850. INSERT INTO #dbcc (logdate, spid, logmsg)
  10851. EXECUTE (@sqlcmd);
  10852. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10853. END TRY
  10854. BEGIN CATCH
  10855. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10856. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 1. ' + ERROR_MESSAGE()
  10857. RAISERROR (@ErrorMessage, 16, 1);
  10858. END CATCH
  10859. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''deadlock'''
  10860. BEGIN TRY
  10861. INSERT INTO #dbcc (logdate, spid, logmsg)
  10862. EXECUTE (@sqlcmd);
  10863. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10864. END TRY
  10865. BEGIN CATCH
  10866. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10867. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 2. ' + ERROR_MESSAGE()
  10868. RAISERROR (@ErrorMessage, 16, 1);
  10869. END CATCH
  10870. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''stack dump'''
  10871. BEGIN TRY
  10872. INSERT INTO #dbcc (logdate, spid, logmsg)
  10873. EXECUTE (@sqlcmd);
  10874. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10875. END TRY
  10876. BEGIN CATCH
  10877. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10878. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 3. ' + ERROR_MESSAGE()
  10879. RAISERROR (@ErrorMessage, 16, 1);
  10880. END CATCH
  10881. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''Error:'''
  10882. BEGIN TRY
  10883. INSERT INTO #dbcc (logdate, spid, logmsg)
  10884. EXECUTE (@sqlcmd);
  10885. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10886. END TRY
  10887. BEGIN CATCH
  10888. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10889. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 4. ' + ERROR_MESSAGE()
  10890. RAISERROR (@ErrorMessage, 16, 1);
  10891. END CATCH
  10892. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''A significant part of sql server process memory has been paged out'''
  10893. BEGIN TRY
  10894. INSERT INTO #dbcc (logdate, spid, logmsg)
  10895. EXECUTE (@sqlcmd);
  10896. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10897. END TRY
  10898. BEGIN CATCH
  10899. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10900. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 5. ' + ERROR_MESSAGE()
  10901. RAISERROR (@ErrorMessage, 16, 1);
  10902. END CATCH
  10903. SELECT @sqlcmd = 'EXEC master..sp_readerrorlog ' + CONVERT(VARCHAR(3),@lognumber) + ', 1, ''cachestore flush'''
  10904. BEGIN TRY
  10905. INSERT INTO #dbcc (logdate, spid, logmsg)
  10906. EXECUTE (@sqlcmd);
  10907. UPDATE #dbcc SET logid = @lognumber WHERE logid IS NULL;
  10908. END TRY
  10909. BEGIN CATCH
  10910. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
  10911. SELECT @ErrorMessage = 'Errorlog based subsection - Error raised in TRY block 6. ' + ERROR_MESSAGE()
  10912. RAISERROR (@ErrorMessage, 16, 1);
  10913. END CATCH
  10914. -- Next log
  10915. --SET @lognumber = @lognumber + 1
  10916. SELECT @lognumber = MIN(lognum) FROM #avail_logs WHERE lognum > @lognumber
  10917. END
  10918. IF (SELECT COUNT([rowid]) FROM #dbcc) > 0
  10919. BEGIN
  10920. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog' AS [Check], '[WARNING: Errorlog contains important messages.]' AS [Deviation];
  10921. ;WITH cte_dbcc (err, errcnt, logdate, logmsg)
  10922. AS (SELECT CASE WHEN logmsg LIKE 'Error: %' THEN RIGHT(LEFT(#dbcc.logmsg, CHARINDEX(',', #dbcc.logmsg)-1), CHARINDEX(',', #dbcc.logmsg)-8)
  10923. WHEN logmsg LIKE 'SQL Server has encountered % longer than 15 seconds %' THEN CONVERT(CHAR(3),833)
  10924. WHEN logmsg LIKE 'A significant part of sql server process memory has been paged out%' THEN CONVERT(CHAR(5),17890)
  10925. ELSE '' END AS err,
  10926. COUNT(logmsg) AS errcnt,
  10927. logdate,
  10928. 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'
  10929. 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.'
  10930. ELSE logmsg END AS logmsg
  10931. FROM #dbcc
  10932. GROUP BY logmsg, logdate
  10933. )
  10934. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog_Summary' AS [Information],
  10935. err AS [Error_Number],
  10936. SUM(errcnt) AS Error_Count,
  10937. MIN(logdate) AS [First_Logged_Date],
  10938. MAX(logdate) AS [Last_Logged_Date],
  10939. logmsg AS [Logged_Message],
  10940. CASE WHEN logmsg LIKE 'Error: 825%' THEN 'IO transient failure. Possible corruption'
  10941. 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'
  10942. WHEN logmsg LIKE 'Error: 855%' OR logmsg LIKE 'Error: 856%' THEN 'Hardware memory corruption'
  10943. WHEN logmsg LIKE 'Error: 3452%' THEN 'Metadata inconsistency in DB. Run DBCC CHECKIDENT'
  10944. WHEN logmsg LIKE 'Error: 3619%' THEN 'Chkpoint failed. No Log space available'
  10945. WHEN logmsg LIKE 'Error: 9002%' THEN 'No Log space available'
  10946. WHEN logmsg LIKE 'Error: 17204%' OR logmsg LIKE 'Error: 17207%' THEN 'Error opening file during startup process'
  10947. WHEN logmsg LIKE 'Error: 17179%' THEN 'No AWE - LPIM related'
  10948. WHEN logmsg LIKE 'Error: 17890%' THEN 'sqlservr process paged out'
  10949. WHEN logmsg LIKE 'Error: 2508%' THEN 'Catalog views inaccuracies in DB. Run DBCC UPDATEUSAGE'
  10950. WHEN logmsg LIKE 'Error: 2511%' THEN 'Index Keys errors'
  10951. WHEN logmsg LIKE 'Error: 3271%' THEN 'IO nonrecoverable error'
  10952. WHEN logmsg LIKE 'Error: 5228%' OR logmsg LIKE 'Error: 5229%' THEN 'Online Index operation errors'
  10953. WHEN logmsg LIKE 'Error: 5242%' THEN 'Page structural inconsistency'
  10954. WHEN logmsg LIKE 'Error: 5243%' THEN 'In-memory structural inconsistency'
  10955. WHEN logmsg LIKE 'Error: 5250%' THEN 'Corrupt page. Error cannot be fixed'
  10956. WHEN logmsg LIKE 'Error: 5901%' THEN 'Chkpoint failed. Possible corruption'
  10957. WHEN logmsg LIKE 'Error: 17130%' THEN 'No lock memory'
  10958. WHEN logmsg LIKE 'Error: 17300%' THEN 'Unable to run new system task'
  10959. WHEN logmsg LIKE 'Error: 802%' THEN 'No BP memory'
  10960. WHEN logmsg LIKE 'Error: 845%' OR logmsg LIKE 'Error: 1105%' OR logmsg LIKE 'Error: 1121%' THEN 'No disk space available'
  10961. WHEN logmsg LIKE 'Error: 1214%' THEN 'Internal parallelism error'
  10962. WHEN logmsg LIKE 'Error: 823%' OR logmsg LIKE 'Error: 824%' THEN 'IO failure. Possible corruption'
  10963. WHEN logmsg LIKE 'Error: 832%' THEN 'Page checksum error. Possible corruption'
  10964. 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'
  10965. WHEN logmsg LIKE 'Error: 5572%' THEN 'Possible FILESTREAM corruption'
  10966. WHEN logmsg LIKE 'Error: 9100%' THEN 'Possible index corruption'
  10967. -- How To Diagnose and Correct Errors 17883, 17884, 17887, and 17888 (http://technet.microsoft.com/en-us/library/cc917684.aspx)
  10968. WHEN logmsg LIKE 'Error: 17883%' THEN 'Non-yielding scheduler: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10969. WHEN logmsg LIKE 'Error: 17884%' OR logmsg LIKE 'Error: 17888%' THEN 'Deadlocked scheduler: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10970. WHEN logmsg LIKE 'Error: 17887%' THEN 'IO completion error: http://technet.microsoft.com/en-us/library/cc917684.aspx'
  10971. WHEN logmsg LIKE 'Error: 1205%' THEN 'Deadlocked transaction'
  10972. WHEN logmsg LIKE 'Error: 610%' THEN 'Page header invalid. Possible corruption'
  10973. WHEN logmsg LIKE 'Error: 8621%' THEN 'QP stack overflow during optimization. Please simplify the query'
  10974. WHEN logmsg LIKE 'Error: 8642%' THEN 'QP insufficient threads for parallelism'
  10975. WHEN logmsg LIKE 'Error: 701%' THEN 'Insufficient memory'
  10976. -- How to troubleshoot SQL Server error 8645 (http://support.microsoft.com/kb/309256)
  10977. WHEN logmsg LIKE 'Error: 8645%' THEN 'Insufficient memory: http://support.microsoft.com/kb/309256'
  10978. WHEN logmsg LIKE 'Error: 605%' THEN 'Page retrieval failed. Possible corruption'
  10979. -- How to troubleshoot Msg 5180 (http://support.microsoft.com/kb/2015747)
  10980. WHEN logmsg LIKE 'Error: 5180%' THEN 'Invalid file ID. Possible corruption: http://support.microsoft.com/kb/2015747'
  10981. WHEN logmsg LIKE 'Error: 8966%' THEN 'Unable to read and latch on a PFS or GAM page'
  10982. WHEN logmsg LIKE 'Error: 9001%' OR logmsg LIKE 'Error: 9002%' THEN 'Transaction log errors.'
  10983. WHEN logmsg LIKE 'Error: 9003%' OR logmsg LIKE 'Error: 9004%' OR logmsg LIKE 'Error: 9015%' THEN 'Transaction log errors. Possible corruption'
  10984. -- How to reduce paging of buffer pool memory in the 64-bit version of SQL Server (http://support.microsoft.com/kb/918483)
  10985. 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'
  10986. WHEN logmsg LIKE '%cachestore flush%' THEN 'CacheStore flush'
  10987. ELSE '' END AS [Comment],
  10988. 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','%'), '%%%', '%')
  10989. 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)
  10990. ELSE '' END AS [Look_for_Message_example]
  10991. FROM cte_dbcc
  10992. GROUP BY err, logmsg
  10993. ORDER BY SUM(errcnt) DESC;
  10994. IF @logdetail = 1
  10995. BEGIN
  10996. 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],
  10997. CASE WHEN logmsg LIKE 'Error: 825%' THEN 'IO transient failure. Possible corruption'
  10998. WHEN logmsg LIKE 'Error: 833%' OR logmsg LIKE 'SQL Server has encountered % longer than 15 seconds %' THEN 'Long IO detected'
  10999. WHEN logmsg LIKE 'Error: 855%' OR logmsg LIKE 'Error: 856%' THEN 'Hardware memory corruption'
  11000. WHEN logmsg LIKE 'Error: 3452%' THEN 'Metadata inconsistency in DB. Run DBCC CHECKIDENT'
  11001. WHEN logmsg LIKE 'Error: 3619%' THEN 'Chkpoint failed. No Log space available'
  11002. WHEN logmsg LIKE 'Error: 9002%' THEN 'No Log space available'
  11003. WHEN logmsg LIKE 'Error: 17179%' THEN 'No AWE - LPIM related'
  11004. WHEN logmsg LIKE 'Error: 17890%' THEN 'sqlservr process paged out'
  11005. WHEN logmsg LIKE 'Error: 17204%' OR logmsg LIKE 'Error: 17207%' THEN 'Error opening file during startup process'
  11006. WHEN logmsg LIKE 'Error: 2508%' THEN 'Catalog views inaccuracies in DB. Run DBCC UPDATEUSAGE'
  11007. WHEN logmsg LIKE 'Error: 2511%' THEN 'Index Keys errors'
  11008. WHEN logmsg LIKE 'Error: 3271%' THEN 'IO nonrecoverable error'
  11009. WHEN logmsg LIKE 'Error: 5228%' OR logmsg LIKE 'Error: 5229%' THEN 'Online Index operation errors'
  11010. WHEN logmsg LIKE 'Error: 5242%' THEN 'Page structural inconsistency'
  11011. WHEN logmsg LIKE 'Error: 5243%' THEN 'In-memory structural inconsistency'
  11012. WHEN logmsg LIKE 'Error: 5250%' THEN 'Corrupt page. Error cannot be fixed'
  11013. WHEN logmsg LIKE 'Error: 5901%' THEN 'Chkpoint failed. Possible corruption'
  11014. WHEN logmsg LIKE 'Error: 17130%' THEN 'No lock memory'
  11015. WHEN logmsg LIKE 'Error: 17300%' THEN 'Unable to run new system task'
  11016. WHEN logmsg LIKE 'Error: 802%' THEN 'No BP memory'
  11017. WHEN logmsg LIKE 'Error: 845%' OR logmsg LIKE 'Error: 1105%' OR logmsg LIKE 'Error: 1121%' THEN 'No disk space available'
  11018. WHEN logmsg LIKE 'Error: 1214%' THEN 'Internal parallelism error'
  11019. WHEN logmsg LIKE 'Error: 823%' OR logmsg LIKE 'Error: 824%' THEN 'IO failure. Possible corruption'
  11020. WHEN logmsg LIKE 'Error: 832%' THEN 'Page checksum error. Possible corruption'
  11021. 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'
  11022. WHEN logmsg LIKE 'Error: 5572%' THEN 'Possible FILESTREAM corruption'
  11023. WHEN logmsg LIKE 'Error: 9100%' THEN 'Possible index corruption'
  11024. -- How To Diagnose and Correct Errors 17883, 17884, 17887, and 17888 (http://technet.microsoft.com/en-us/library/cc917684.aspx)
  11025. WHEN logmsg LIKE 'Error: 17883%' THEN 'Non-yielding scheduler'
  11026. WHEN logmsg LIKE 'Error: 17884%' OR logmsg LIKE 'Error: 17888%' THEN 'Deadlocked scheduler'
  11027. WHEN logmsg LIKE 'Error: 17887%' THEN 'IO completion error'
  11028. WHEN logmsg LIKE 'Error: 1205%' THEN 'Deadlocked transaction'
  11029. WHEN logmsg LIKE 'Error: 610%' THEN 'Page header invalid. Possible corruption'
  11030. WHEN logmsg LIKE 'Error: 8621%' THEN 'QP stack overflow during optimization. Please simplify the query'
  11031. WHEN logmsg LIKE 'Error: 8642%' THEN 'QP insufficient threads for parallelism'
  11032. WHEN logmsg LIKE 'Error: 701%' THEN 'Insufficient memory'
  11033. -- How to troubleshoot SQL Server error 8645 (http://support.microsoft.com/kb/309256)
  11034. WHEN logmsg LIKE 'Error: 8645%' THEN 'Insufficient memory'
  11035. WHEN logmsg LIKE 'Error: 605%' THEN 'Page retrieval failed. Possible corruption'
  11036. -- How to troubleshoot Msg 5180 (http://support.microsoft.com/kb/2015747)
  11037. WHEN logmsg LIKE 'Error: 5180%' THEN 'Invalid file ID. Possible corruption'
  11038. WHEN logmsg LIKE 'Error: 8966%' THEN 'Unable to read and latch on a PFS or GAM page'
  11039. WHEN logmsg LIKE 'Error: 9001%' OR logmsg LIKE 'Error: 9002%' THEN 'Transaction log errors.'
  11040. WHEN logmsg LIKE 'Error: 9003%' OR logmsg LIKE 'Error: 9004%' OR logmsg LIKE 'Error: 9015%' THEN 'Transaction log errors. Possible corruption'
  11041. -- How to reduce paging of buffer pool memory in the 64-bit version of SQL Server (http://support.microsoft.com/kb/918483)
  11042. 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'
  11043. WHEN logmsg LIKE '%cachestore flush%' THEN 'CacheStore flush'
  11044. ELSE '' END AS [Comment]
  11045. FROM #dbcc
  11046. ORDER BY logdate DESC
  11047. END
  11048. END
  11049. ELSE
  11050. BEGIN
  11051. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'Errorlog' AS [Check], '[OK]' AS [Deviation]
  11052. END;
  11053. END
  11054. ELSE
  11055. BEGIN
  11056. RAISERROR('[WARNING: Only a sysadmin or securityadmin can run the "Errorlog" check. Bypassing check]', 16, 1, N'permissions')
  11057. 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')
  11058. --RETURN
  11059. END;
  11060. --------------------------------------------------------------------------------------------------------------------------------
  11061. -- System health error checks subsection
  11062. --------------------------------------------------------------------------------------------------------------------------------
  11063. IF @sqlmajorver > 10
  11064. BEGIN
  11065. RAISERROR (N' |-Starting System health checks', 10, 1) WITH NOWAIT
  11066. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11067. DROP TABLE #SystemHealthSessionData;
  11068. IF NOT EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11069. CREATE TABLE #SystemHealthSessionData (target_data XML)
  11070. -- Store the XML data in a temporary table
  11071. INSERT INTO #SystemHealthSessionData
  11072. SELECT CAST(xet.target_data AS XML)
  11073. FROM sys.dm_xe_session_targets xet
  11074. INNER JOIN sys.dm_xe_sessions xe ON xe.address = xet.event_session_address
  11075. WHERE xe.name = 'system_health'
  11076. IF (SELECT COUNT(*) FROM #SystemHealthSessionData a WHERE CONVERT(VARCHAR(max), target_data) LIKE '%error_reported%') > 0
  11077. BEGIN
  11078. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors' AS [Check], '[WARNING: System Health Session contains important messages.]' AS [Deviation];
  11079. -- Get statistical information about all the errors reported
  11080. ;WITH cteHealthSession (EventXML) AS (SELECT C.query('.') EventXML
  11081. FROM #SystemHealthSessionData a
  11082. CROSS APPLY a.target_data.nodes('/RingBufferTarget/event') AS T(C)
  11083. ),
  11084. cteErrorReported (EventTime, ErrorNumber) AS (SELECT EventXML.value('(/event/@timestamp)[1]', 'datetime') AS EventTime,
  11085. EventXML.value('(/event/data[@name="error_number"]/value)[1]', 'int') AS ErrorNumber
  11086. FROM cteHealthSession
  11087. WHERE EventXML.value('(/event/@name)[1]', 'VARCHAR(500)') = 'error_reported'
  11088. )
  11089. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors_Summary' AS [Information],
  11090. ErrorNumber AS [Error_Number],
  11091. MIN(EventTime) AS [First_Logged_Date],
  11092. MAX(EventTime) AS [Last_Logged_Date],
  11093. COUNT(ErrorNumber) AS Error_Count,
  11094. 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]
  11095. FROM cteErrorReported a
  11096. INNER JOIN sys.messages b ON a.ErrorNumber = b.message_id
  11097. WHERE b.language_id = @langid
  11098. GROUP BY a.ErrorNumber, b.[text]
  11099. -- Get detailed information about all the errors reported
  11100. ;WITH cteHealthSession AS (SELECT C.query('.').value('(/event/@timestamp)[1]', 'datetime') AS EventTime,
  11101. C.query('.').value('(/event/data[@name="error_number"]/value)[1]', 'int') AS ErrorNumber,
  11102. C.query('.').value('(/event/data[@name="severity"]/value)[1]', 'int') AS ErrorSeverity,
  11103. C.query('.').value('(/event/data[@name="state"]/value)[1]', 'int') AS ErrorState,
  11104. C.query('.').value('(/event/data[@name="message"]/value)[1]', 'VARCHAR(MAX)') AS ErrorText,
  11105. C.query('.').value('(/event/action[@name="session_id"]/value)[1]', 'int') AS SessionID,
  11106. C.query('.').value('(/event/data[@name="category"]/text)[1]', 'VARCHAR(10)') AS ErrorCategory
  11107. FROM #SystemHealthSessionData a
  11108. CROSS APPLY a.target_data.nodes('/RingBufferTarget/event') AS T(C)
  11109. WHERE C.query('.').value('(/event/@name)[1]', 'VARCHAR(500)') = 'error_reported')
  11110. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors_Detail' AS [Information],
  11111. EventTime AS [Logged_Date],
  11112. ErrorNumber AS [Error_Number],
  11113. ErrorSeverity AS [Error_Sev],
  11114. ErrorState AS [Error_State],
  11115. ErrorText AS [Logged_Message],
  11116. SessionID
  11117. FROM cteHealthSession
  11118. ORDER BY EventTime
  11119. END
  11120. ELSE
  11121. BEGIN
  11122. SELECT 'Maintenance_Monitoring_checks' AS [Category], 'SystemHealth_Errors' AS [Check], '[OK]' AS [Deviation]
  11123. END;
  11124. END;
  11125. --------------------------------------------------------------------------------------------------------------------------------
  11126. -- Clean up temp objects
  11127. --------------------------------------------------------------------------------------------------------------------------------
  11128. RAISERROR (N'Clearing up temporary objects', 10, 1) WITH NOWAIT
  11129. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbinfo'))
  11130. DROP TABLE #dbinfo;
  11131. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#output_dbinfo'))
  11132. DROP TABLE #output_dbinfo;
  11133. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIOStall'))
  11134. DROP TABLE #tblIOStall;
  11135. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs1'))
  11136. DROP TABLE #tmpdbs1;
  11137. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs0'))
  11138. DROP TABLE #tmpdbs0;
  11139. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerfCount'))
  11140. DROP TABLE #tblPerfCount;
  11141. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.tblPerfThresholds'))
  11142. DROP TABLE tempdb.dbo.tblPerfThresholds;
  11143. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHypObj'))
  11144. DROP TABLE #tblHypObj;
  11145. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs1'))
  11146. DROP TABLE #tblIxs1;
  11147. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs2'))
  11148. DROP TABLE #tblIxs2;
  11149. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs3'))
  11150. DROP TABLE #tblIxs3;
  11151. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs4'))
  11152. DROP TABLE #tblIxs4;
  11153. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs5'))
  11154. DROP TABLE #tblIxs5;
  11155. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblIxs6'))
  11156. DROP TABLE #tblIxs6;
  11157. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFK'))
  11158. DROP TABLE #tblFK;
  11159. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dbcc'))
  11160. DROP TABLE #dbcc;
  11161. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#avail_logs'))
  11162. DROP TABLE #avail_logs;
  11163. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info1'))
  11164. DROP TABLE #log_info1;
  11165. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#log_info2'))
  11166. DROP TABLE #log_info2;
  11167. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpobjectnames'))
  11168. DROP TABLE #tmpobjectnames;
  11169. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpfinalobjectnames'))
  11170. DROP TABLE #tmpfinalobjectnames;
  11171. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWaits'))
  11172. DROP TABLE #tblWaits;
  11173. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalWaits'))
  11174. DROP TABLE #tblFinalWaits;
  11175. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblLatches'))
  11176. DROP TABLE #tblLatches;
  11177. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalLatches'))
  11178. DROP TABLE #tblFinalLatches;
  11179. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexCreation'))
  11180. DROP TABLE #IndexCreation;
  11181. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#IndexRedundant'))
  11182. DROP TABLE #IndexRedundant;
  11183. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblBlkChains'))
  11184. DROP TABLE #tblBlkChains;
  11185. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsSamp'))
  11186. DROP TABLE #tblStatsSamp;
  11187. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksBefore'))
  11188. DROP TABLE #tblSpinlocksBefore;
  11189. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblSpinlocksAfter'))
  11190. DROP TABLE #tblSpinlocksAfter;
  11191. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblFinalSpinlocks'))
  11192. DROP TABLE #tblFinalSpinlocks;
  11193. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#pagerepair'))
  11194. DROP TABLE #pagerepair;
  11195. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_io_virtual_file_stats'))
  11196. DROP TABLE #tmp_dm_io_virtual_file_stats;
  11197. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmp_dm_exec_query_stats'))
  11198. DROP TABLE #tmp_dm_exec_query_stats;
  11199. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#dm_exec_query_stats'))
  11200. DROP TABLE #dm_exec_query_stats;
  11201. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIOReq'))
  11202. DROP TABLE #tblPendingIOReq;
  11203. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPendingIO'))
  11204. DROP TABLE #tblPendingIO;
  11205. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#qpwarnings'))
  11206. DROP TABLE #qpwarnings;
  11207. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblStatsUpd'))
  11208. DROP TABLE #tblStatsUpd;
  11209. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblPerSku'))
  11210. DROP TABLE #tblPerSku;
  11211. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblColStoreIXs'))
  11212. DROP TABLE #tblColStoreIXs;
  11213. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#SystemHealthSessionData'))
  11214. DROP TABLE #SystemHealthSessionData;
  11215. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbfiledetail'))
  11216. DROP TABLE #tmpdbfiledetail;
  11217. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblHints'))
  11218. DROP TABLE #tblHints;
  11219. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblTriggers'))
  11220. DROP TABLE #tblTriggers;
  11221. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS'))
  11222. DROP TABLE #tmpIPS;
  11223. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblCode'))
  11224. DROP TABLE #tblCode;
  11225. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblWorking'))
  11226. DROP TABLE #tblWorking;
  11227. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpdbs_userchoice'))
  11228. DROP TABLE #tmpdbs_userchoice;
  11229. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluNodesOutput'))
  11230. DROP TABLE #xp_cmdshell_CluNodesOutput;
  11231. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_CluOutput'))
  11232. DROP TABLE #xp_cmdshell_CluOutput;
  11233. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_Nodes'))
  11234. DROP TABLE #xp_cmdshell_Nodes;
  11235. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEOutput'))
  11236. DROP TABLE #xp_cmdshell_QFEOutput;
  11237. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_QFEFinal'))
  11238. DROP TABLE #xp_cmdshell_QFEFinal;
  11239. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#RegResult'))
  11240. DROP TABLE #RegResult;
  11241. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ServiceStatus'))
  11242. DROP TABLE #ServiceStatus;
  11243. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_AcctSPNoutput'))
  11244. DROP TABLE #xp_cmdshell_AcctSPNoutput;
  11245. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#xp_cmdshell_DupSPNoutput'))
  11246. DROP TABLE #xp_cmdshell_DupSPNoutput;
  11247. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#FinalDupSPN'))
  11248. DROP TABLE #FinalDupSPN;
  11249. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#ScopedDupSPN'))
  11250. DROP TABLE #ScopedDupSPN;
  11251. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblDRI'))
  11252. DROP TABLE #tblDRI;
  11253. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tblInMemDBs'))
  11254. DROP TABLE #tblInMemDBs;
  11255. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXIS'))
  11256. DROP TABLE #tmpXIS;
  11257. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpXNCIS'))
  11258. DROP TABLE #tmpXNCIS;
  11259. IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#tmpIPS_CI'))
  11260. DROP TABLE #tmpIPS_CI;
  11261. 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')
  11262. 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')
  11263. 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')
  11264. 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')
  11265. RAISERROR (N'All done!', 10, 1) WITH NOWAIT
  11266. GO