sql server command line tools to manage your server

4
enter email address Join Latest SQL Server Tips SQL Server Monitoring with Powershell and the SQL Server Platform: Data Collection (Part 1 of 3) The SQL Server Job Management You Wish You Had SQL Server Command Line Tools To Manage Your Server By: Greg Robidoux | Read Comments (4) | Related Tips: More > Monitoring Problem There are several useful commands and functions that are available in SQL Server, but not knowing what they are where to find more information about them is sometimes a problem. Having these commands at your fingertips is helpful when trying to solve a problem or for just doing general analysis on your database instances. Solution Following is a list of useful commands that can be run using Query Analyzer. A lot of this information can be retrie using Enterprise Manager, but it is often faster to use these commands directly in Query Analyzer as well as more detailed information is provided. Each of these commands has different functionality and knowing that the comman exists and what types of information they produce is extremely helpful in managing your SQL Server environment Command Purpose Sample Usage sp_helpdb This gives you information about all databases in the instance or specific information about one database. sp_helpdb sp_helpdb databasename fn_virtualfilestats This command will show you the number of read and writes to a data file. Use sp_helpdb with the database name to see the logical file numbers for the data files and the database id. SELECT * FROM :: fn_virtualfilestats(dabaseid, logicalfileid) SELECT * FROM :: fn_virtualfilestats(1, 1) fn_get_sql() Returns the text of the SQL statement for the specified SQL handle. This is similar to using DBCC INPUTBUFFER, but this command will show you additional information. This can also be embedded in a process easier then using the DBCC command MSSQLTips additional info DECLARE @Handle binary(20) SELECT @Handle = sql_handle FROM sysprocesses WHERE spid = 52 SELECT * FROM ::fn_get_sql(@Handle) sp_lock This command shows you all of the locks that the system is currently tracking This is similar to information you can see in Enterprise Manager. sp_lock sp_lock spid sp_lock spid1, spid2 sp_help This command gives you information about the objects within a database. The command without an objectname will give you a list of all objects within the database. sp_help sp_help objectname sp_who2 Gives you process information similar to what you see when using Enterprise Manager. sp_who2 sp_who2 spid sp_helpindex Gives you information about the indexes on a table as well as the columns used for the index. MSSQLTips additional info sp_helpindex objectname sp_spaceused This command shows you how much space has been allocated for the database (or if specified an object) and how much space is being used. sp_spaceused sp_spaceused objectname DBCC CACHESTATS Displays information about the objects currently in the buffer cache. DBCC CACHESTATS DBCC CHECKDB This will check the allocation of all pages in the database as well as check for any integrity issues. DBCC CHECKDB

Upload: nikhil-vyas

Post on 13-Sep-2015

233 views

Category:

Documents


7 download

DESCRIPTION

important sql tools

TRANSCRIPT

  • 5/14/2015 SQLServerCommandLineToolsToManageYourServer

    http://www.mssqltips.com/sqlservertip/1029/sqlservercommandlinetoolstomanageyourserver/ 1/4

    enteremailaddress Join

    LatestSQLServerTips

    SQLServerMonitoringwithPowershellandtheSQLServerPlatform:DataCollection(Part1of3)

    TheSQLServerJobManagementYouWishYouHad

    SQLServerCommandLineToolsToManageYourServer

    By:GregRobidoux|ReadComments(4)|RelatedTips:More>Monitoring

    ProblemThereareseveralusefulcommandsandfunctionsthatareavailableinSQLServer,butnotknowingwhattheyareorwheretofindmoreinformationaboutthemissometimesaproblem.Havingthesecommandsatyourfingertipsisveryhelpfulwhentryingtosolveaproblemorforjustdoinggeneralanalysisonyourdatabaseinstances.

    SolutionFollowingisalistofusefulcommandsthatcanberunusingQueryAnalyzer.AlotofthisinformationcanberetrievedusingEnterpriseManager,butitisoftenfastertousethesecommandsdirectlyinQueryAnalyzeraswellasmoredetailedinformationisprovided.EachofthesecommandshasdifferentfunctionalityandknowingthatthecommandexistsandwhattypesofinformationtheyproduceisextremelyhelpfulinmanagingyourSQLServerenvironment

    Command Purpose SampleUsagesp_helpdb Thisgivesyouinformationaboutalldatabasesinthe

    instanceorspecificinformationaboutonedatabase. sp_helpdbsp_helpdbdatabasename

    fn_virtualfilestats Thiscommandwillshowyouthenumberofreadandwritestoadatafile.Usesp_helpdbwiththedatabasenametoseethelogicalfilenumbersforthedatafilesandthedatabaseid.

    SELECT*FROM::fn_virtualfilestats(dabaseid,logicalfileid)SELECT*FROM::fn_virtualfilestats(1,1)

    fn_get_sql() ReturnsthetextoftheSQLstatementforthespecifiedSQLhandle.ThisissimilartousingDBCCINPUTBUFFER,butthiscommandwillshowyouadditionalinformation.ThiscanalsobeembeddedinaprocesseasierthenusingtheDBCCcommand

    MSSQLTipsadditionalinfo

    DECLARE@Handlebinary(20)SELECT@Handle=sql_handleFROMsysprocessesWHEREspid=52SELECT*FROM::fn_get_sql(@Handle)

    sp_lock ThiscommandshowsyouallofthelocksthatthesystemiscurrentlytrackingThisissimilartoinformationyoucanseeinEnterpriseManager.

    sp_locksp_lockspidsp_lockspid1,spid2

    sp_help Thiscommandgivesyouinformationabouttheobjectswithinadatabase.Thecommandwithoutanobjectnamewillgiveyoualistofallobjectswithinthedatabase.

    sp_helpsp_helpobjectname

    sp_who2 GivesyouprocessinformationsimilartowhatyouseewhenusingEnterpriseManager. sp_who2

    sp_who2spid

    sp_helpindex Givesyouinformationabouttheindexesonatableaswellasthecolumnsusedfortheindex.

    MSSQLTipsadditionalinfo

    sp_helpindexobjectname

    sp_spaceused Thiscommandshowsyouhowmuchspacehasbeenallocatedforthedatabase(orifspecifiedanobject)andhowmuchspaceisbeingused.

    sp_spaceusedsp_spaceusedobjectname

    DBCCCACHESTATS Displaysinformationabouttheobjectscurrentlyinthebuffercache. DBCCCACHESTATS

    DBCCCHECKDB Thiswillchecktheallocationofallpagesinthedatabaseaswellascheckforanyintegrityissues. DBCCCHECKDB

  • 5/14/2015 SQLServerCommandLineToolsToManageYourServer

    http://www.mssqltips.com/sqlservertip/1029/sqlservercommandlinetoolstomanageyourserver/ 2/4

    TroubleshootingCommonSQLServerBulkInsertErrors

    SQLServerAnalysisServiceLevelsofGranularity

    MonitorSQLServerTransactionLogFileFreeSpace

    FreeSQLServerLearning

    Avoiding,Detecting,andRepairingSQLServerDatabaseCorruption

    IsHApittingSQLDatabaseAdminsagainstVMAdmins?KeepingthePeacewithSANLessclusters.

    TheArtofStressFreeDatabaseAdministration

    SQLServerAuditwithSQLComplianceManagerandSQLSecure

    HowtoRollyourOwnValue,RegExandSoundExPatternProfilerinSSIS

    GregRobidouxisthePresidentofEdgewoodSolutionsandacofounderofMSSQLTips.com.

    Viewallmytips

    RelatedResources

    MoreSQLServerDBATips...

    DBCCCHECKTABLE Thiswillchecktheallocationofallpagesforaspecifictableorindexaswellascheckforanyintegrityissues. DBCCCHECKTABLE

    (tableName')

    DBCCDBREINDEX Thiscommandwillreindexyourtable.Iftheindexnameisleftoutthenallindexesarerebuilt.Ifthefillfactorissetto0thenthiswillusetheoriginalfillfactorwhenthetablewascreated.

    MSSQLTipsadditionalinfo

    DBCCDBREINDEX(tablename,indexname,fillfactor)DBCCDBREINDEX(authors,'',70)DBCCDBREINDEX('pubs.dbo.authors',UPKCL_auidind,80)

    DBCCPROCCACHE Thiscommandwillshowyouinformationabouttheprocedurecacheandhowmuchisbeingused.Spotlightwillalsoshowyouthissameinformation.

    DBCCPROCCACHE

    DBCCMEMORYSTATUS DisplayshowtheSQLServerbuffercacheisdividedup,includingbufferactivity. DBCCMEMORYSTATUS

    DBCCSHOWCONTIG Thiscommandgivesyouinformationabouthowmuchspaceisusedforatableandindexes.Informationprovidedincludesnumberofpagesusedaswellashowfragmentedthedataisinthedatabase.

    DBCCSHOWCONTIGDBCCSHOWCONTIGWITHALL_INDEXESDBCCSHOWCONTIGtablename

    DBCCSHOW_STATISTICS Thiswillshowhowstatisticsarelaidoutforanindex.Youcanseehowdistributedthedataisandwhethertheindexisreallyagoodcandidateornot.

    DBCCSHOW_STATISTICS(tablename,indexname)

    DBCCSHRINKFILE Thiswillallowyoutoshrinkoneofthedatabasefiles.Thisisequivalenttodoingadatabaseshrink,butyoucanspecifywhatfileandthesizetoshrinkitto.Usethesp_helpdbcommandalongwiththedatabasenametoseetheactualfilenamesused.

    MSSQLTipsadditionalinfo

    DBCCSHRINKFILE(filename,sizeinMB)DBCCSHRINKFILE(DataFile,1000)

    DBCCSQLPERF Thiscommandwillshowyoumuchofthetransactionlogsarebeingused. DBCC

    SQLPERF(LOGSPACE)

    DBCCTRACEON Thiscommandwillturnonatraceflagtocaptureeventsintheerrorlog.TraceFlag1204capturesDeadlockinformation.

    DBCCTRACEON(traceflag)

    DBCCTRACEOFF Thiscommandturnsoffatraceflag.DBCCTRACEOFF(traceflag)

    NextSteps

    GetfamiliarwiththesecommandlinefunctionsthatyoucanputtouseimmediatelyTaketimetolearnmoreaboutthesedifferentoptionsandwhenspecificcommandsshouldbeusedandhowtheyshouldbeusedLookforfuturetipsoneachofthesecommands

    LastUpdate:7/28/2006

    Abouttheauthor

    Print Tweet 0 BecomeapaidauthorShare 0Like

  • 5/14/2015 SQLServerCommandLineToolsToManageYourServer

    http://www.mssqltips.com/sqlservertip/1029/sqlservercommandlinetoolstomanageyourserver/ 3/4

    SQLServerSecurityEssentials

    EnterEmailAddress Join

    LearnMore

    Postacommentorlettheauthorknowthistiphelpedyou.Allcommentsarereviewed,sostayonsubjectorwemaydeleteyourcomment.

    *Name *Email Notifyforupdates

    ***NOTE***IfyouwanttoincludecodefromSQLServerManagementStudio(SSMS)inyourpost,pleasecopythecodefromSSMSandpastethecodeintoatexteditorlikeNotePadbeforecopyingthecodebelowtoremovetheSSMSformatting.

    Note:youremailaddressisnotpublished.Requiredfieldsaremarkedwithanasterisk(*)

    GetfreeSQLtips:

    *EnterCode SaveComment

    Tuesday,January28,20149:47:14PMSaritHod ReadTheTip

    CanyoupleasementionSQLS*PlusthisisagreatfreecommandlinetoolforSQLServer

    Saturday,November03,20122:26:33AMRon ReadTheTip

    Thanks.

    DoyouhaveupdatesforSS2008R2?

    Wednesday,July18,20122:01:25PMJeremyKadlec ReadTheTip

    Sandip,

    Iwouldcheckoutthesetips:

    http://www.mssqltips.com/sqlservertipcategory/25/maintenance/

    http://www.mssqltips.com/sqlservertipcategory/91/maintenanceplans/

    HTH.

    Thankyou,JeremyKadlec

    Wednesday,July18,20121:51:21AMsandipdeshmukh ReadTheTip

    informationregardingSQLServerCommandLineToolsToManageYourServerisverygoodwithallimportantinformation.

    thanks,

    ifposibblepleasesendmethealldatabasescriptwhichicanuseforDatabasemaintanance.

    thanks&Regards,

    SandipDeshmukh

    Paragraph

  • 5/14/2015 SQLServerCommandLineToolsToManageYourServer

    http://www.mssqltips.com/sqlservertip/1029/sqlservercommandlinetoolstomanageyourserver/ 4/4

    SponsorInformation

    Follow

    GetFreeSQLTips

    Twitter

    LinkedIn

    Google+

    Facebook

    Pinterest

    RSS

    Learning

    DBAs

    Developers

    BIProfessionals

    Careers

    QandA

    Today'sTip

    Resources

    Tutorials

    Webcasts

    Whitepapers

    Tools

    Search

    TipCategories

    SearchByTipID

    TopTen

    Authors

    Community

    FirstTimer?

    Pictures

    FreeTshirt

    Contribute

    Events

    UserGroups

    AuthoroftheYear

    MoreInfo

    Join

    About

    Copyright

    Privacy

    Disclaimer

    Feedback

    Advertise

    Copyright(c)20062015EdgewoodSolutions,LLCAllrightsreservedSomenamesandproductslistedaretheregisteredtrademarksoftheirrespectiveowners.